Set cursor to hint that you can drag automation up and down in object/range link...
[ardour.git] / gtk2_ardour / editor.cc
1 /*
2     Copyright (C) 2000-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 /* Note: public Editor methods are documented in public_editor.h */
21
22 #define __STDC_LIMIT_MACROS 1
23 #include <stdint.h>
24 #include <unistd.h>
25 #include <cstdlib>
26 #include <cmath>
27 #include <string>
28 #include <algorithm>
29 #include <map>
30
31 #include "ardour_ui.h"
32 /*
33  * ardour_ui.h include was moved to the top of the list
34  * due to a conflicting definition of 'Style' between
35  * Apple's MacTypes.h and BarController.
36  */
37
38 #include <boost/none.hpp>
39
40 #include <sigc++/bind.h>
41
42 #include "pbd/convert.h"
43 #include "pbd/error.h"
44 #include "pbd/enumwriter.h"
45 #include "pbd/memento_command.h"
46 #include "pbd/unknown_type.h"
47
48 #include <glibmm/miscutils.h>
49 #include <gtkmm/image.h>
50 #include <gdkmm/color.h>
51 #include <gdkmm/bitmap.h>
52
53 #include <gtkmm2ext/grouped_buttons.h>
54 #include <gtkmm2ext/gtk_ui.h>
55 #include <gtkmm2ext/tearoff.h>
56 #include <gtkmm2ext/utils.h>
57 #include <gtkmm2ext/window_title.h>
58 #include <gtkmm2ext/choice.h>
59 #include <gtkmm2ext/cell_renderer_pixbuf_toggle.h>
60
61 #include "ardour/audio_diskstream.h"
62 #include "ardour/audio_track.h"
63 #include "ardour/audioplaylist.h"
64 #include "ardour/audioregion.h"
65 #include "ardour/location.h"
66 #include "ardour/midi_region.h"
67 #include "ardour/plugin_manager.h"
68 #include "ardour/profile.h"
69 #include "ardour/route_group.h"
70 #include "ardour/session_directory.h"
71 #include "ardour/session_route.h"
72 #include "ardour/session_state_utils.h"
73 #include "ardour/tempo.h"
74 #include "ardour/utils.h"
75 #include "ardour/session_playlists.h"
76 #include "ardour/audioengine.h"
77
78 #include "control_protocol/control_protocol.h"
79
80 #include "editor.h"
81 #include "keyboard.h"
82 #include "marker.h"
83 #include "playlist_selector.h"
84 #include "audio_region_view.h"
85 #include "rgb_macros.h"
86 #include "selection.h"
87 #include "audio_streamview.h"
88 #include "time_axis_view.h"
89 #include "audio_time_axis.h"
90 #include "utils.h"
91 #include "crossfade_view.h"
92 #include "canvas-noevent-text.h"
93 #include "editing.h"
94 #include "public_editor.h"
95 #include "crossfade_edit.h"
96 #include "canvas_impl.h"
97 #include "actions.h"
98 #include "sfdb_ui.h"
99 #include "gui_thread.h"
100 #include "simpleline.h"
101 #include "rhythm_ferret.h"
102 #include "actions.h"
103 #include "tempo_lines.h"
104 #include "analysis_window.h"
105 #include "bundle_manager.h"
106 #include "global_port_matrix.h"
107 #include "editor_drag.h"
108 #include "editor_group_tabs.h"
109 #include "automation_time_axis.h"
110 #include "editor_routes.h"
111 #include "midi_time_axis.h"
112 #include "mixer_strip.h"
113 #include "editor_route_groups.h"
114 #include "editor_regions.h"
115 #include "editor_locations.h"
116 #include "editor_snapshots.h"
117 #include "editor_summary.h"
118
119 #include "i18n.h"
120
121 #ifdef WITH_CMT
122 #include "imageframe_socket_handler.h"
123 #endif
124
125 using namespace std;
126 using namespace ARDOUR;
127 using namespace PBD;
128 using namespace Gtk;
129 using namespace Glib;
130 using namespace Gtkmm2ext;
131 using namespace Editing;
132
133 using PBD::internationalize;
134 using PBD::atoi;
135 using Gtkmm2ext::Keyboard;
136
137 const double Editor::timebar_height = 15.0;
138
139 #include "editor_xpms"
140
141 static const gchar *_snap_type_strings[] = {
142         N_("CD Frames"),
143         N_("Timecode Frames"),
144         N_("Timecode Seconds"),
145         N_("Timecode Minutes"),
146         N_("Seconds"),
147         N_("Minutes"),
148         N_("Beats/32"),
149         N_("Beats/28"),
150         N_("Beats/24"),
151         N_("Beats/20"),
152         N_("Beats/16"),
153         N_("Beats/14"),
154         N_("Beats/12"),
155         N_("Beats/10"),
156         N_("Beats/8"),
157         N_("Beats/7"),
158         N_("Beats/6"),
159         N_("Beats/5"),
160         N_("Beats/4"),
161         N_("Beats/3"),
162         N_("Beats/2"),
163         N_("Beats"),
164         N_("Bars"),
165         N_("Marks"),
166         N_("Region starts"),
167         N_("Region ends"),
168         N_("Region syncs"),
169         N_("Region bounds"),
170         0
171 };
172
173 static const gchar *_snap_mode_strings[] = {
174         N_("No Grid"),
175         N_("Grid"),
176         N_("Magnetic"),
177         0
178 };
179
180 static const gchar *_edit_point_strings[] = {
181         N_("Playhead"),
182         N_("Marker"),
183         N_("Mouse"),
184         0
185 };
186
187 static const gchar *_zoom_focus_strings[] = {
188         N_("Left"),
189         N_("Right"),
190         N_("Center"),
191         N_("Playhead"),
192         N_("Mouse"),
193         N_("Edit point"),
194         0
195 };
196
197 #ifdef USE_RUBBERBAND
198 static const gchar *_rb_opt_strings[] = {
199         N_("Mushy"),
200         N_("Smooth"),
201         N_("Balanced multitimbral mixture"),
202         N_("Unpitched percussion with stable notes"),
203         N_("Crisp monophonic instrumental"),
204         N_("Unpitched solo percussion"),
205         N_("Resample without preserving pitch"),
206         0
207 };
208 #endif
209
210 /* Soundfile  drag-n-drop */
211
212 Gdk::Cursor* Editor::cross_hair_cursor = 0;
213 Gdk::Cursor* Editor::selector_cursor = 0;
214 Gdk::Cursor* Editor::trimmer_cursor = 0;
215 Gdk::Cursor* Editor::left_side_trim_cursor = 0;
216 Gdk::Cursor* Editor::right_side_trim_cursor = 0;
217 Gdk::Cursor* Editor::fade_in_cursor = 0;
218 Gdk::Cursor* Editor::fade_out_cursor = 0;
219 Gdk::Cursor* Editor::grabber_cursor = 0;
220 Gdk::Cursor* Editor::grabber_note_cursor = 0;
221 Gdk::Cursor* Editor::grabber_edit_point_cursor = 0;
222 Gdk::Cursor* Editor::zoom_cursor = 0;
223 Gdk::Cursor* Editor::time_fx_cursor = 0;
224 Gdk::Cursor* Editor::fader_cursor = 0;
225 Gdk::Cursor* Editor::speaker_cursor = 0;
226 Gdk::Cursor* Editor::midi_pencil_cursor = 0;
227 Gdk::Cursor* Editor::midi_select_cursor = 0;
228 Gdk::Cursor* Editor::midi_resize_cursor = 0;
229 Gdk::Cursor* Editor::midi_erase_cursor = 0;
230 Gdk::Cursor* Editor::wait_cursor = 0;
231 Gdk::Cursor* Editor::timebar_cursor = 0;
232 Gdk::Cursor* Editor::transparent_cursor = 0;
233 Gdk::Cursor* Editor::up_down_cursor = 0;
234
235 void
236 show_me_the_size (Requisition* r, const char* what)
237 {
238         cerr << "size of " << what << " = " << r->width << " x " << r->height << endl;
239 }
240
241 #ifdef GTKOSX
242 static void
243 pane_size_watcher (Paned* pane)
244 {
245        /* if the handle of a pane vanishes into (at least) the tabs of a notebook,
246           it is no longer accessible. so stop that. this doesn't happen on X11,
247           just the quartz backend.
248
249           ugh.
250        */
251
252        int max_width_of_lhs = GTK_WIDGET(pane->gobj())->allocation.width - 25;
253
254        gint pos = pane->get_position ();
255
256        if (pos > max_width_of_lhs) {
257                pane->set_position (max_width_of_lhs);
258        }
259 }
260 #endif
261
262 Editor::Editor ()
263         : _join_object_range_state (JOIN_OBJECT_RANGE_NONE)
264
265           /* time display buttons */
266         , minsec_label (_("Mins:Secs"))
267         , bbt_label (_("Bars:Beats"))
268         , timecode_label (_("Timecode"))
269         , frame_label (_("Samples"))
270         , tempo_label (_("Tempo"))
271         , meter_label (_("Meter"))
272         , mark_label (_("Location Markers"))
273         , range_mark_label (_("Range Markers"))
274         , transport_mark_label (_("Loop/Punch Ranges"))
275         , cd_mark_label (_("CD Markers"))
276         , edit_packer (4, 4, true)
277
278           /* the values here don't matter: layout widgets
279              reset them as needed.
280           */
281
282         , vertical_adjustment (0.0, 0.0, 10.0, 400.0)
283
284           /* tool bar related */
285
286         , zoom_range_clock (X_("zoomrange"), false, X_("ZoomRangeClock"), true, false, true)
287
288         , toolbar_selection_clock_table (2,3)
289
290         , automation_mode_button (_("mode"))
291         , global_automation_button (_("automation"))
292
293         , midi_panic_button (_("Panic"))
294
295 #ifdef WITH_CMT
296         , image_socket_listener(0)
297 #endif
298
299           /* nudge */
300
301         , nudge_clock (X_("nudge"), false, X_("NudgeClock"), true, false, true)
302         , meters_running(false)
303         , _pending_locate_request (false)
304         , _pending_initial_locate (false)
305 {
306         constructed = false;
307
308         /* we are a singleton */
309
310         PublicEditor::_instance = this;
311
312         _have_idled = false;
313
314         selection = new Selection (this);
315         cut_buffer = new Selection (this);
316
317         clicked_regionview = 0;
318         clicked_axisview = 0;
319         clicked_routeview = 0;
320         clicked_crossfadeview = 0;
321         clicked_control_point = 0;
322         last_update_frame = 0;
323         _drags = new DragManager (this);
324         current_mixer_strip = 0;
325         current_bbt_points = 0;
326         tempo_lines = 0;
327
328         snap_type_strings =  I18N (_snap_type_strings);
329         snap_mode_strings =  I18N (_snap_mode_strings);
330         zoom_focus_strings = I18N (_zoom_focus_strings);
331         edit_point_strings = I18N (_edit_point_strings);
332 #ifdef USE_RUBBERBAND
333         rb_opt_strings = I18N (_rb_opt_strings);
334         rb_current_opt = 4;
335 #endif
336
337         snap_threshold = 5.0;
338         bbt_beat_subdivision = 4;
339         _canvas_width = 0;
340         _canvas_height = 0;
341         last_autoscroll_x = 0;
342         last_autoscroll_y = 0;
343         autoscroll_active = false;
344         autoscroll_timeout_tag = -1;
345         logo_item = 0;
346
347         analysis_window = 0;
348
349         current_interthread_info = 0;
350         _show_measures = true;
351         show_gain_after_trim = false;
352         verbose_cursor_on = true;
353         last_item_entered = 0;
354         last_item_entered_n = 0;
355
356         have_pending_keyboard_selection = false;
357         _follow_playhead = true;
358         _stationary_playhead = false;
359         _xfade_visibility = true;
360         editor_ruler_menu = 0;
361         no_ruler_shown_update = false;
362         marker_menu = 0;
363         session_range_marker_menu = 0;
364         range_marker_menu = 0;
365         marker_menu_item = 0;
366         tempo_or_meter_marker_menu = 0;
367         transport_marker_menu = 0;
368         new_transport_marker_menu = 0;
369         editor_mixer_strip_width = Wide;
370         show_editor_mixer_when_tracks_arrive = false;
371         region_edit_menu_split_multichannel_item = 0;
372         region_edit_menu_split_item = 0;
373         temp_location = 0;
374         leftmost_frame = 0;
375         current_stepping_trackview = 0;
376         entered_track = 0;
377         entered_regionview = 0;
378         entered_marker = 0;
379         clear_entered_track = false;
380         current_timefx = 0;
381         playhead_cursor = 0;
382         button_release_can_deselect = true;
383         _dragging_playhead = false;
384         _dragging_edit_point = false;
385         select_new_marker = false;
386         rhythm_ferret = 0;
387         _bundle_manager = 0;
388         no_save_visual = false;
389         resize_idle_id = -1;
390
391         scrubbing_direction = 0;
392
393         sfbrowser = 0;
394
395         location_marker_color = ARDOUR_UI::config()->canvasvar_LocationMarker.get();
396         location_range_color = ARDOUR_UI::config()->canvasvar_LocationRange.get();
397         location_cd_marker_color = ARDOUR_UI::config()->canvasvar_LocationCDMarker.get();
398         location_loop_color = ARDOUR_UI::config()->canvasvar_LocationLoop.get();
399         location_punch_color = ARDOUR_UI::config()->canvasvar_LocationPunch.get();
400
401         _edit_point = EditAtMouse;
402         _internal_editing = false;
403         current_canvas_cursor = 0;
404
405         frames_per_unit = 2048; /* too early to use reset_zoom () */
406
407         _scroll_callbacks = 0;
408
409         zoom_focus = ZoomFocusLeft;
410         set_zoom_focus (ZoomFocusLeft);
411         zoom_range_clock.ValueChanged.connect (sigc::mem_fun(*this, &Editor::zoom_adjustment_changed));
412
413         bbt_label.set_name ("EditorTimeButton");
414         bbt_label.set_size_request (-1, (int)timebar_height);
415         bbt_label.set_alignment (1.0, 0.5);
416         bbt_label.set_padding (5,0);
417         bbt_label.hide ();
418         bbt_label.set_no_show_all();
419         minsec_label.set_name ("EditorTimeButton");
420         minsec_label.set_size_request (-1, (int)timebar_height);
421         minsec_label.set_alignment (1.0, 0.5);
422         minsec_label.set_padding (5,0);
423         minsec_label.hide ();
424         minsec_label.set_no_show_all();
425         timecode_label.set_name ("EditorTimeButton");
426         timecode_label.set_size_request (-1, (int)timebar_height);
427         timecode_label.set_alignment (1.0, 0.5);
428         timecode_label.set_padding (5,0);
429         timecode_label.hide ();
430         timecode_label.set_no_show_all();
431         frame_label.set_name ("EditorTimeButton");
432         frame_label.set_size_request (-1, (int)timebar_height);
433         frame_label.set_alignment (1.0, 0.5);
434         frame_label.set_padding (5,0);
435         frame_label.hide ();
436         frame_label.set_no_show_all();
437
438         tempo_label.set_name ("EditorTimeButton");
439         tempo_label.set_size_request (-1, (int)timebar_height);
440         tempo_label.set_alignment (1.0, 0.5);
441         tempo_label.set_padding (5,0);
442         tempo_label.hide();
443         tempo_label.set_no_show_all();
444         meter_label.set_name ("EditorTimeButton");
445         meter_label.set_size_request (-1, (int)timebar_height);
446         meter_label.set_alignment (1.0, 0.5);
447         meter_label.set_padding (5,0);
448         meter_label.hide();
449         meter_label.set_no_show_all();
450         mark_label.set_name ("EditorTimeButton");
451         mark_label.set_size_request (-1, (int)timebar_height);
452         mark_label.set_alignment (1.0, 0.5);
453         mark_label.set_padding (5,0);
454         mark_label.hide();
455         mark_label.set_no_show_all();
456         cd_mark_label.set_name ("EditorTimeButton");
457         cd_mark_label.set_size_request (-1, (int)timebar_height);
458         cd_mark_label.set_alignment (1.0, 0.5);
459         cd_mark_label.set_padding (5,0);
460         cd_mark_label.hide();
461         cd_mark_label.set_no_show_all();
462         range_mark_label.set_name ("EditorTimeButton");
463         range_mark_label.set_size_request (-1, (int)timebar_height);
464         range_mark_label.set_alignment (1.0, 0.5);
465         range_mark_label.set_padding (5,0);
466         range_mark_label.hide();
467         range_mark_label.set_no_show_all();
468         transport_mark_label.set_name ("EditorTimeButton");
469         transport_mark_label.set_size_request (-1, (int)timebar_height);
470         transport_mark_label.set_alignment (1.0, 0.5);
471         transport_mark_label.set_padding (5,0);
472         transport_mark_label.hide();
473         transport_mark_label.set_no_show_all();
474
475         initialize_rulers ();
476         initialize_canvas ();
477         _summary = new EditorSummary (this);
478
479         selection->TimeChanged.connect (sigc::mem_fun(*this, &Editor::time_selection_changed));
480         selection->TracksChanged.connect (sigc::mem_fun(*this, &Editor::track_selection_changed));
481         editor_regions_selection_changed_connection = selection->RegionsChanged.connect (sigc::mem_fun(*this, &Editor::region_selection_changed));
482         selection->PointsChanged.connect (sigc::mem_fun(*this, &Editor::point_selection_changed));
483         selection->MarkersChanged.connect (sigc::mem_fun(*this, &Editor::marker_selection_changed));
484
485         edit_controls_vbox.set_spacing (0);
486         vertical_adjustment.signal_value_changed().connect (sigc::mem_fun(*this, &Editor::tie_vertical_scrolling), true);
487         track_canvas->signal_map_event().connect (sigc::mem_fun (*this, &Editor::track_canvas_map_handler));
488
489         HBox* h = manage (new HBox);
490         _group_tabs = new EditorGroupTabs (this);
491         h->pack_start (*_group_tabs, PACK_SHRINK);
492         h->pack_start (edit_controls_vbox);
493         controls_layout.add (*h);
494
495         controls_layout.set_name ("EditControlsBase");
496         controls_layout.add_events (Gdk::SCROLL_MASK);
497         controls_layout.signal_scroll_event().connect (sigc::mem_fun(*this, &Editor::control_layout_scroll), false);
498
499         controls_layout.add_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK|Gdk::ENTER_NOTIFY_MASK|Gdk::LEAVE_NOTIFY_MASK);
500         controls_layout.signal_button_release_event().connect (sigc::mem_fun(*this, &Editor::edit_controls_button_release));
501         controls_layout_size_request_connection = controls_layout.signal_size_request().connect (sigc::mem_fun (*this, &Editor::controls_layout_size_request));
502
503         build_cursors ();
504
505         ArdourCanvas::Canvas* time_pad = manage(new ArdourCanvas::Canvas());
506         ArdourCanvas::SimpleLine* pad_line_1 = manage(new ArdourCanvas::SimpleLine(*time_pad->root(),
507                         0.0, 1.0, 100.0, 1.0));
508         pad_line_1->property_color_rgba() = 0xFF0000FF;
509         pad_line_1->show();
510         time_pad->show();
511
512         time_canvas_vbox.set_size_request (-1, (int)(timebar_height * visible_timebars) + 2);
513         time_canvas_vbox.set_size_request (-1, -1);
514
515         ruler_label_event_box.add (ruler_label_vbox);
516         ruler_label_event_box.set_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK);
517         ruler_label_event_box.signal_button_release_event().connect (sigc::mem_fun(*this, &Editor::ruler_label_button_release));
518
519         time_button_event_box.add (time_button_vbox);
520         time_button_event_box.set_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK);
521         time_button_event_box.signal_button_release_event().connect (sigc::mem_fun(*this, &Editor::ruler_label_button_release));
522
523         /* these enable us to have a dedicated window (for cursor setting, etc.)
524            for the canvas areas.
525         */
526
527         track_canvas_event_box.add (*track_canvas);
528
529         time_canvas_event_box.add (time_canvas_vbox);
530         time_canvas_event_box.set_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK|Gdk::POINTER_MOTION_MASK);
531
532         edit_packer.set_col_spacings (0);
533         edit_packer.set_row_spacings (0);
534         edit_packer.set_homogeneous (false);
535         edit_packer.set_border_width (0);
536         edit_packer.set_name ("EditorWindow");
537
538         /* labels for the rulers */
539         edit_packer.attach (ruler_label_event_box,   1, 2, 0, 1,    FILL,        SHRINK, 0, 0);
540         /* labels for the marker "tracks" */
541         edit_packer.attach (time_button_event_box,   1, 2, 1, 2,    FILL,        SHRINK, 0, 0);
542         /* the rulers */
543         edit_packer.attach (time_canvas_event_box,   2, 3, 0, 1,    FILL|EXPAND, FILL, 0, 0);
544         /* track controls */
545         edit_packer.attach (controls_layout,         0, 2, 2, 3,    FILL,        FILL|EXPAND, 0, 0);
546         /* main canvas */
547         edit_packer.attach (track_canvas_event_box,  2, 3, 1, 3,    FILL|EXPAND, FILL|EXPAND, 0, 0);
548
549         bottom_hbox.set_border_width (2);
550         bottom_hbox.set_spacing (3);
551
552         _route_groups = new EditorRouteGroups (this);
553         _routes = new EditorRoutes (this);
554         _regions = new EditorRegions (this);
555         _snapshots = new EditorSnapshots (this);
556         _locations = new EditorLocations (this);
557
558         Gtk::Label* nlabel;
559
560         nlabel = manage (new Label (_("Regions")));
561         nlabel->set_angle (-90);
562         the_notebook.append_page (_regions->widget (), *nlabel);
563         nlabel = manage (new Label (_("Tracks & Busses")));
564         nlabel->set_angle (-90);
565         the_notebook.append_page (_routes->widget (), *nlabel);
566         nlabel = manage (new Label (_("Snapshots")));
567         nlabel->set_angle (-90);
568         the_notebook.append_page (_snapshots->widget (), *nlabel);
569         nlabel = manage (new Label (_("Route Groups")));
570         nlabel->set_angle (-90);
571         the_notebook.append_page (_route_groups->widget (), *nlabel);
572         nlabel = manage (new Label (_("Ranges & Marks")));
573         nlabel->set_angle (-90);
574         the_notebook.append_page (_locations->widget (), *nlabel);
575
576         the_notebook.set_show_tabs (true);
577         the_notebook.set_scrollable (true);
578         the_notebook.popup_disable ();
579         the_notebook.set_tab_pos (Gtk::POS_RIGHT);
580         the_notebook.show_all ();
581         
582         post_maximal_editor_width = 0;
583         post_maximal_horizontal_pane_position = 0;
584         post_maximal_editor_height = 0;
585         post_maximal_vertical_pane_position = 0;
586
587         editor_summary_pane.pack1(edit_packer);
588
589         Button* summary_arrows_left_left = manage (new Button);
590         summary_arrows_left_left->add (*manage (new Arrow (ARROW_LEFT, SHADOW_NONE)));
591         summary_arrows_left_left->signal_pressed().connect (sigc::hide_return (sigc::mem_fun (*this, &Editor::horizontal_scroll_left_press)));
592         summary_arrows_left_left->signal_released().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_left_release));
593         Button* summary_arrows_left_right = manage (new Button);
594         summary_arrows_left_right->add (*manage (new Arrow (ARROW_RIGHT, SHADOW_NONE)));
595         summary_arrows_left_right->signal_pressed().connect (sigc::hide_return (sigc::mem_fun (*this, &Editor::horizontal_scroll_right_press)));
596         summary_arrows_left_right->signal_released().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_right_release));
597         VBox* summary_arrows_left = manage (new VBox);
598         summary_arrows_left->pack_start (*summary_arrows_left_left);
599         summary_arrows_left->pack_start (*summary_arrows_left_right);
600
601         Button* summary_arrows_right_left = manage (new Button);
602         summary_arrows_right_left->add (*manage (new Arrow (ARROW_LEFT, SHADOW_NONE)));
603         summary_arrows_right_left->signal_pressed().connect (sigc::hide_return (sigc::mem_fun (*this, &Editor::horizontal_scroll_left_press)));
604         summary_arrows_right_left->signal_released().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_left_release));
605         Button* summary_arrows_right_right = manage (new Button);
606         summary_arrows_right_right->add (*manage (new Arrow (ARROW_RIGHT, SHADOW_NONE)));
607         summary_arrows_right_right->signal_pressed().connect (sigc::hide_return (sigc::mem_fun (*this, &Editor::horizontal_scroll_right_press)));
608         summary_arrows_right_right->signal_released().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_right_release));
609         VBox* summary_arrows_right = manage (new VBox);
610         summary_arrows_right->pack_start (*summary_arrows_right_left);
611         summary_arrows_right->pack_start (*summary_arrows_right_right);
612
613         Frame* summary_frame = manage (new Frame);
614         summary_frame->set_shadow_type (Gtk::SHADOW_ETCHED_IN);
615         summary_frame->add (*_summary);
616         summary_frame->show ();
617
618         _summary_hbox.pack_start (*summary_arrows_left, false, false);
619         _summary_hbox.pack_start (*summary_frame, true, true);
620         _summary_hbox.pack_start (*summary_arrows_right, false, false);
621         
622         editor_summary_pane.pack2 (_summary_hbox);
623
624         edit_pane.pack1 (editor_summary_pane, true, true);
625         edit_pane.pack2 (the_notebook, false, true);
626
627         editor_summary_pane.signal_size_allocate().connect (sigc::bind (sigc::mem_fun (*this, &Editor::pane_allocation_handler), static_cast<Paned*> (&editor_summary_pane)));
628
629         /* XXX: editor_summary_pane might need similar special OS X treatment to the edit_pane */
630
631         edit_pane.signal_size_allocate().connect (sigc::bind (sigc::mem_fun(*this, &Editor::pane_allocation_handler), static_cast<Paned*> (&edit_pane)));
632 #ifdef GTKOSX
633         Glib::PropertyProxy<int> proxy = edit_pane.property_position();
634         proxy.signal_changed().connect (bind (sigc::ptr_fun (pane_size_watcher), static_cast<Paned*> (&edit_pane)));
635 #endif
636         top_hbox.pack_start (toolbar_frame, false, true);
637
638         HBox *hbox = manage (new HBox);
639         hbox->pack_start (edit_pane, true, true);
640
641         global_vpacker.pack_start (top_hbox, false, false);
642         global_vpacker.pack_start (*hbox, true, true);
643
644         global_hpacker.pack_start (global_vpacker, true, true);
645
646         set_name ("EditorWindow");
647         add_accel_group (ActionManager::ui_manager->get_accel_group());
648
649         status_bar_hpacker.show ();
650
651         vpacker.pack_end (status_bar_hpacker, false, false);
652         vpacker.pack_end (global_hpacker, true, true);
653
654         /* register actions now so that set_state() can find them and set toggles/checks etc */
655
656         register_actions ();
657
658         setup_toolbar ();
659         setup_midi_toolbar ();
660
661         _snap_type = SnapToBeat;
662         set_snap_to (_snap_type);
663         _snap_mode = SnapOff;
664         set_snap_mode (_snap_mode);
665         set_mouse_mode (MouseObject, true);
666         set_edit_point_preference (EditAtMouse, true);
667
668         _playlist_selector = new PlaylistSelector();
669         _playlist_selector->signal_delete_event().connect (sigc::bind (sigc::ptr_fun (just_hide_it), static_cast<Window *> (_playlist_selector)));
670
671         RegionView::RegionViewGoingAway.connect (*this, invalidator (*this),  ui_bind (&Editor::catch_vanishing_regionview, this, _1), gui_context());
672
673         /* nudge stuff */
674
675         nudge_forward_button.add (*(manage (new Image (::get_icon("nudge_right")))));
676         nudge_backward_button.add (*(manage (new Image (::get_icon("nudge_left")))));
677
678         nudge_forward_button.set_name ("TransportButton");
679         nudge_backward_button.set_name ("TransportButton");
680
681         fade_context_menu.set_name ("ArdourContextMenu");
682
683         /* icons, titles, WM stuff */
684
685         list<Glib::RefPtr<Gdk::Pixbuf> > window_icons;
686         Glib::RefPtr<Gdk::Pixbuf> icon;
687
688         if ((icon = ::get_icon ("ardour_icon_16px")) != 0) {
689                 window_icons.push_back (icon);
690         }
691         if ((icon = ::get_icon ("ardour_icon_22px")) != 0) {
692                 window_icons.push_back (icon);
693         }
694         if ((icon = ::get_icon ("ardour_icon_32px")) != 0) {
695                 window_icons.push_back (icon);
696         }
697         if ((icon = ::get_icon ("ardour_icon_48px")) != 0) {
698                 window_icons.push_back (icon);
699         }
700         if (!window_icons.empty()) {
701                 set_icon_list (window_icons);
702                 set_default_icon_list (window_icons);
703         }
704
705         WindowTitle title(Glib::get_application_name());
706         title += _("Editor");
707         set_title (title.get_string());
708         set_wmclass (X_("ardour_editor"), PROGRAM_NAME);
709
710         add (vpacker);
711         add_events (Gdk::KEY_PRESS_MASK|Gdk::KEY_RELEASE_MASK);
712
713         signal_configure_event().connect (sigc::mem_fun (*ARDOUR_UI::instance(), &ARDOUR_UI::configure_handler));
714         signal_delete_event().connect (sigc::mem_fun (*ARDOUR_UI::instance(), &ARDOUR_UI::exit_on_main_window_close));
715
716         /* allow external control surfaces/protocols to do various things */
717
718         ControlProtocol::ZoomToSession.connect (*this, invalidator (*this), boost::bind (&Editor::temporal_zoom_session, this), gui_context());
719         ControlProtocol::ZoomIn.connect (*this, invalidator (*this), boost::bind (&Editor::temporal_zoom_step, this, false), gui_context());
720         ControlProtocol::ZoomOut.connect (*this, invalidator (*this), boost::bind (&Editor::temporal_zoom_step, this, true), gui_context());
721         ControlProtocol::ScrollTimeline.connect (*this, invalidator (*this), ui_bind (&Editor::control_scroll, this, _1), gui_context());
722         BasicUI::AccessAction.connect (*this, invalidator (*this), ui_bind (&Editor::access_action, this, _1, _2), gui_context());
723         
724         /* problematic: has to return a value and thus cannot be x-thread */
725
726         Session::AskAboutPlaylistDeletion.connect_same_thread (*this, boost::bind (&Editor::playlist_deletion_dialog, this, _1));
727
728         Config->ParameterChanged.connect (*this, invalidator (*this), ui_bind (&Editor::parameter_changed, this, _1), gui_context());
729
730         TimeAxisView::CatchDeletion.connect (*this, invalidator (*this), ui_bind (&Editor::timeaxisview_deleted, this, _1), gui_context());
731
732         _last_normalization_value = 0;
733
734         constructed = true;
735         instant_save ();
736 }
737
738 Editor::~Editor()
739 {
740 #ifdef WITH_CMT
741         if(image_socket_listener) {
742                 if(image_socket_listener->is_connected())
743                 {
744                         image_socket_listener->close_connection() ;
745                 }
746
747                 delete image_socket_listener ;
748                 image_socket_listener = 0 ;
749         }
750 #endif
751
752         delete _routes;
753         delete _route_groups;
754         delete track_canvas;
755         delete _drags;
756 }
757
758 void
759 Editor::add_toplevel_controls (Container& cont)
760 {
761         vpacker.pack_start (cont, false, false);
762         cont.show_all ();
763 }
764
765 void
766 Editor::catch_vanishing_regionview (RegionView *rv)
767 {
768         /* note: the selection will take care of the vanishing
769            audioregionview by itself.
770         */
771
772         if (_drags->active() && _drags->have_item (rv->get_canvas_group()) && !_drags->ending()) {
773                 _drags->abort ();
774         }
775
776         if (clicked_regionview == rv) {
777                 clicked_regionview = 0;
778         }
779
780         if (entered_regionview == rv) {
781                 set_entered_regionview (0);
782         }
783 }
784
785 void
786 Editor::set_entered_regionview (RegionView* rv)
787 {
788         if (rv == entered_regionview) {
789                 return;
790         }
791
792         if (entered_regionview) {
793                 entered_regionview->exited ();
794         }
795
796         if ((entered_regionview = rv) != 0) {
797                 entered_regionview->entered (internal_editing ());
798         }
799 }
800
801 void
802 Editor::set_entered_track (TimeAxisView* tav)
803 {
804         if (entered_track) {
805                 entered_track->exited ();
806         }
807
808         if ((entered_track = tav) != 0) {
809                 entered_track->entered ();
810         }
811 }
812
813 void
814 Editor::show_window ()
815 {
816         if (! is_visible ()) {
817                 show_all ();
818
819                 /* re-hide editor list if necessary */
820                 editor_list_button_toggled ();
821
822                 /* re-hide summary widget if necessary */
823                 parameter_changed ("show-summary");
824
825                 parameter_changed ("show-edit-group-tabs");
826
827                 /* now reset all audio_time_axis heights, because widgets might need
828                    to be re-hidden
829                 */
830
831                 TimeAxisView *tv;
832
833                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
834                         tv = (static_cast<TimeAxisView*>(*i));
835                         tv->reset_height ();
836                 }
837
838                 reset_zoom (frames_per_unit);
839         }
840
841         present ();
842 }
843
844 void
845 Editor::instant_save ()
846 {
847         if (!constructed || !ARDOUR_UI::instance()->session_loaded) {
848                 return;
849         }
850
851         if (_session) {
852                 _session->add_instant_xml(get_state());
853         } else {
854                 Config->add_instant_xml(get_state());
855         }
856 }
857
858 void
859 Editor::zoom_adjustment_changed ()
860 {
861         if (_session == 0) {
862                 return;
863         }
864
865         double fpu = zoom_range_clock.current_duration() / _canvas_width;
866
867         if (fpu < 1.0) {
868                 fpu = 1.0;
869                 zoom_range_clock.set ((nframes64_t) floor (fpu * _canvas_width));
870         } else if (fpu > _session->current_end_frame() / _canvas_width) {
871                 fpu = _session->current_end_frame() / _canvas_width;
872                 zoom_range_clock.set ((nframes64_t) floor (fpu * _canvas_width));
873         }
874
875         temporal_zoom (fpu);
876 }
877
878 void
879 Editor::control_scroll (float fraction)
880 {
881         ENSURE_GUI_THREAD (*this, &Editor::control_scroll, fraction)
882
883         if (!_session) {
884                 return;
885         }
886
887         double step = fraction * current_page_frames();
888
889         /*
890                 _control_scroll_target is an optional<T>
891
892                 it acts like a pointer to an nframes64_t, with
893                 a operator conversion to boolean to check
894                 that it has a value could possibly use
895                 playhead_cursor->current_frame to store the
896                 value and a boolean in the class to know
897                 when it's out of date
898         */
899
900         if (!_control_scroll_target) {
901                 _control_scroll_target = _session->transport_frame();
902                 _dragging_playhead = true;
903         }
904
905         if ((fraction < 0.0f) && (*_control_scroll_target < (nframes64_t) fabs(step))) {
906                 *_control_scroll_target = 0;
907         } else if ((fraction > 0.0f) && (max_frames - *_control_scroll_target < step)) {
908                 *_control_scroll_target = max_frames - (current_page_frames()*2); // allow room for slop in where the PH is on the screen
909         } else {
910                 *_control_scroll_target += (nframes64_t) floor (step);
911         }
912
913         /* move visuals, we'll catch up with it later */
914
915         playhead_cursor->set_position (*_control_scroll_target);
916         UpdateAllTransportClocks (*_control_scroll_target);
917
918         if (*_control_scroll_target > (current_page_frames() / 2)) {
919                 /* try to center PH in window */
920                 reset_x_origin (*_control_scroll_target - (current_page_frames()/2));
921         } else {
922                 reset_x_origin (0);
923         }
924
925         /*
926                 Now we do a timeout to actually bring the session to the right place
927                 according to the playhead. This is to avoid reading disk buffers on every
928                 call to control_scroll, which is driven by ScrollTimeline and therefore
929                 probably by a control surface wheel which can generate lots of events.
930         */
931         /* cancel the existing timeout */
932
933         control_scroll_connection.disconnect ();
934
935         /* add the next timeout */
936
937         control_scroll_connection = Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun (*this, &Editor::deferred_control_scroll), *_control_scroll_target), 250);
938 }
939
940 bool
941 Editor::deferred_control_scroll (nframes64_t /*target*/)
942 {
943         _session->request_locate (*_control_scroll_target, _session->transport_rolling());
944         // reset for next stream
945         _control_scroll_target = boost::none;
946         _dragging_playhead = false;
947         return false;
948 }
949
950 void
951 Editor::access_action (std::string action_group, std::string action_item)
952 {
953         if (!_session) {
954                 return;
955         }
956
957         ENSURE_GUI_THREAD (*this, &Editor::access_action, action_group, action_item)
958
959         RefPtr<Action> act;
960         act = ActionManager::get_action( action_group.c_str(), action_item.c_str() );
961
962         if (act) {
963                 act->activate();
964         }
965 }
966
967 void
968 Editor::on_realize ()
969 {
970         Window::on_realize ();
971         Realized ();
972 }
973
974 void
975 Editor::map_position_change (nframes64_t frame)
976 {
977         ENSURE_GUI_THREAD (*this, &Editor::map_position_change, frame)
978
979         if (_session == 0) {
980                 return;
981         }
982
983         if (_follow_playhead) {
984                 center_screen (frame);
985         }
986
987         playhead_cursor->set_position (frame);
988 }
989
990 void
991 Editor::center_screen (nframes64_t frame)
992 {
993         double page = _canvas_width * frames_per_unit;
994
995         /* if we're off the page, then scroll.
996          */
997
998         if (frame < leftmost_frame || frame >= leftmost_frame + page) {
999                 center_screen_internal (frame, page);
1000         }
1001 }
1002
1003 void
1004 Editor::center_screen_internal (nframes64_t frame, float page)
1005 {
1006         page /= 2;
1007
1008         if (frame > page) {
1009                 frame -= (nframes64_t) page;
1010         } else {
1011                 frame = 0;
1012         }
1013
1014         reset_x_origin (frame);
1015 }
1016
1017
1018 void
1019 Editor::update_title ()
1020 {
1021         ENSURE_GUI_THREAD (*this, &Editor::update_title)
1022
1023         if (_session) {
1024                 bool dirty = _session->dirty();
1025
1026                 string session_name;
1027
1028                 if (_session->snap_name() != _session->name()) {
1029                         session_name = _session->snap_name();
1030                 } else {
1031                         session_name = _session->name();
1032                 }
1033
1034                 if (dirty) {
1035                         session_name = "*" + session_name;
1036                 }
1037
1038                 WindowTitle title(session_name);
1039                 title += Glib::get_application_name();
1040                 set_title (title.get_string());
1041         }
1042 }
1043
1044 void
1045 Editor::set_session (Session *t)
1046 {
1047         SessionHandlePtr::set_session (t);
1048
1049         if (!_session) {
1050                 return;
1051         }
1052
1053         zoom_range_clock.set_session (_session);
1054         _playlist_selector->set_session (_session);
1055         nudge_clock.set_session (_session);
1056         _summary->set_session (_session);
1057         _group_tabs->set_session (_session);
1058         _route_groups->set_session (_session);
1059         _regions->set_session (_session);
1060         _snapshots->set_session (_session);
1061         _routes->set_session (_session);
1062         _locations->set_session (_session);
1063
1064         if (rhythm_ferret) {
1065                 rhythm_ferret->set_session (_session);
1066         }
1067
1068         if (analysis_window) {
1069                 analysis_window->set_session (_session);
1070         }
1071
1072         if (sfbrowser) {
1073                 sfbrowser->set_session (_session);
1074         }
1075
1076         compute_fixed_ruler_scale ();
1077
1078         /* there are never any selected regions at startup */
1079         sensitize_the_right_region_actions (false);
1080
1081         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
1082         set_state (*node, Stateful::loading_state_version);
1083
1084         /* catch up with the playhead */
1085
1086         _session->request_locate (playhead_cursor->current_frame);
1087         _pending_initial_locate = true;
1088
1089         update_title ();
1090
1091         /* These signals can all be emitted by a non-GUI thread. Therefore the
1092            handlers for them must not attempt to directly interact with the GUI,
1093            but use Gtkmm2ext::UI::instance()->call_slot();
1094         */
1095
1096         _session->StepEditStatusChange.connect (_session_connections, invalidator (*this), ui_bind(&Editor::step_edit_status_change, this, _1), gui_context());
1097         _session->TransportStateChange.connect (_session_connections, invalidator (*this), boost::bind (&Editor::map_transport_state, this), gui_context());
1098         _session->PositionChanged.connect (_session_connections, invalidator (*this), ui_bind (&Editor::map_position_change, this, _1), gui_context());
1099         _session->RouteAdded.connect (_session_connections, invalidator (*this), ui_bind (&Editor::handle_new_route, this, _1), gui_context());
1100         _session->DirtyChanged.connect (_session_connections, invalidator (*this), boost::bind (&Editor::update_title, this), gui_context());
1101         _session->TimecodeOffsetChanged.connect (_session_connections, invalidator (*this), boost::bind (&Editor::update_just_timecode, this), gui_context());
1102         _session->tempo_map().PropertyChanged.connect (_session_connections, invalidator (*this), ui_bind (&Editor::tempo_map_changed, this, _1), gui_context());
1103         _session->Located.connect (_session_connections, invalidator (*this), boost::bind (&Editor::located, this), gui_context());
1104         _session->config.ParameterChanged.connect (_session_connections, invalidator (*this), ui_bind (&Editor::parameter_changed, this, _1), gui_context());
1105         _session->StateSaved.connect (_session_connections, invalidator (*this), ui_bind (&Editor::session_state_saved, this, _1), gui_context());
1106         _session->locations()->added.connect (_session_connections, invalidator (*this), ui_bind (&Editor::add_new_location, this, _1), gui_context());
1107         _session->locations()->removed.connect (_session_connections, invalidator (*this), ui_bind (&Editor::location_gone, this, _1), gui_context());
1108         _session->locations()->changed.connect (_session_connections, invalidator (*this), boost::bind (&Editor::refresh_location_display, this), gui_context());
1109         _session->locations()->StateChanged.connect (_session_connections, invalidator (*this), ui_bind (&Editor::refresh_location_display_s, this, _1), gui_context());
1110         _session->history().Changed.connect (_session_connections, invalidator (*this), boost::bind (&Editor::history_changed, this), gui_context());
1111
1112         if (Profile->get_sae()) {
1113                 BBT_Time bbt;
1114                 bbt.bars = 0;
1115                 bbt.beats = 0;
1116                 bbt.ticks = 120;
1117                 nframes_t pos = _session->tempo_map().bbt_duration_at (0, bbt, 1);
1118                 nudge_clock.set_mode(AudioClock::BBT);
1119                 nudge_clock.set (pos, true, 0, AudioClock::BBT);
1120
1121         } else {
1122                 nudge_clock.set (_session->frame_rate() * 5, true, 0, AudioClock::Timecode); // default of 5 seconds
1123         }
1124
1125         playhead_cursor->canvas_item.show ();
1126
1127         Location* loc = _session->locations()->auto_loop_location();
1128         if (loc == 0) {
1129                 loc = new Location (*_session, 0, _session->current_end_frame(), _("Loop"),(Location::Flags) (Location::IsAutoLoop | Location::IsHidden));
1130                 if (loc->start() == loc->end()) {
1131                         loc->set_end (loc->start() + 1);
1132                 }
1133                 _session->locations()->add (loc, false);
1134                 _session->set_auto_loop_location (loc);
1135         } else {
1136                 // force name
1137                 loc->set_name (_("Loop"));
1138         }
1139
1140         loc = _session->locations()->auto_punch_location();
1141         if (loc == 0) {
1142                 loc = new Location (*_session, 0, _session->current_end_frame(), _("Punch"), (Location::Flags) (Location::IsAutoPunch | Location::IsHidden));
1143                 if (loc->start() == loc->end()) {
1144                         loc->set_end (loc->start() + 1);
1145                 }
1146                 _session->locations()->add (loc, false);
1147                 _session->set_auto_punch_location (loc);
1148         } else {
1149                 // force name
1150                 loc->set_name (_("Punch"));
1151         }
1152
1153         boost::function<void (string)> pc (boost::bind (&Editor::parameter_changed, this, _1));
1154         Config->map_parameters (pc);
1155         _session->config.map_parameters (pc);
1156
1157         refresh_location_display ();
1158
1159         restore_ruler_visibility ();
1160         //tempo_map_changed (PropertyChange (0));
1161         _session->tempo_map().apply_with_metrics (*this, &Editor::draw_metric_marks);
1162
1163         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
1164                 (static_cast<TimeAxisView*>(*i))->set_samples_per_unit (frames_per_unit);
1165         }
1166
1167         super_rapid_screen_update_connection = ARDOUR_UI::instance()->SuperRapidScreenUpdate.connect (
1168                 sigc::mem_fun (*this, &Editor::super_rapid_screen_update)
1169                 );
1170         
1171         switch (_snap_type) {
1172         case SnapToRegionStart:
1173         case SnapToRegionEnd:
1174         case SnapToRegionSync:
1175         case SnapToRegionBoundary:
1176                 build_region_boundary_cache ();
1177                 break;
1178
1179         default:
1180                 break;
1181         }
1182
1183         /* register for undo history */
1184         _session->register_with_memento_command_factory(_id, this);
1185
1186         start_updating_meters ();
1187 }
1188
1189 void
1190 Editor::build_cursors ()
1191 {
1192         using namespace Gdk;
1193
1194         Gdk::Color mbg ("#000000" ); /* Black */
1195         Gdk::Color mfg ("#0000ff" ); /* Blue. */
1196
1197         {
1198                 RefPtr<Bitmap> source, mask;
1199                 source = Bitmap::create (mag_bits, mag_width, mag_height);
1200                 mask = Bitmap::create (magmask_bits, mag_width, mag_height);
1201                 zoom_cursor = new Gdk::Cursor (source, mask, mfg, mbg, mag_x_hot, mag_y_hot);
1202         }
1203
1204         Gdk::Color fbg ("#ffffff" );
1205         Gdk::Color ffg  ("#000000" );
1206
1207         {
1208                 RefPtr<Bitmap> source, mask;
1209
1210                 source = Bitmap::create (fader_cursor_bits, fader_cursor_width, fader_cursor_height);
1211                 mask = Bitmap::create (fader_cursor_mask_bits, fader_cursor_width, fader_cursor_height);
1212                 fader_cursor = new Gdk::Cursor (source, mask, ffg, fbg, fader_cursor_x_hot, fader_cursor_y_hot);
1213         }
1214
1215         {
1216                 RefPtr<Bitmap> source, mask;
1217                 source = Bitmap::create (speaker_cursor_bits, speaker_cursor_width, speaker_cursor_height);
1218                 mask = Bitmap::create (speaker_cursor_mask_bits, speaker_cursor_width, speaker_cursor_height);
1219                 speaker_cursor = new Gdk::Cursor (source, mask, ffg, fbg, speaker_cursor_x_hot, speaker_cursor_y_hot);
1220         }
1221
1222         {
1223                 RefPtr<Bitmap> bits;
1224                 char pix[4] = { 0, 0, 0, 0 };
1225                 bits = Bitmap::create (pix, 2, 2);
1226                 Gdk::Color c;
1227                 transparent_cursor = new Gdk::Cursor (bits, bits, c, c, 0, 0);
1228         }
1229
1230         {
1231                 RefPtr<Bitmap> bits;
1232                 char pix[4] = { 0, 0, 0, 0 };
1233                 bits = Bitmap::create (pix, 2, 2);
1234                 Gdk::Color c;
1235                 transparent_cursor = new Gdk::Cursor (bits, bits, c, c, 0, 0);
1236         }
1237
1238
1239         grabber_cursor = new Gdk::Cursor (HAND2);
1240
1241         {
1242                 Glib::RefPtr<Gdk::Pixbuf> grabber_note_pixbuf (::get_icon ("grabber_note"));
1243                 grabber_note_cursor = new Gdk::Cursor (Gdk::Display::get_default(), grabber_note_pixbuf, 5, 10);
1244         }
1245
1246         {
1247                 Glib::RefPtr<Gdk::Pixbuf> grabber_edit_point_pixbuf (::get_icon ("grabber_edit_point"));
1248                 grabber_edit_point_cursor = new Gdk::Cursor (Gdk::Display::get_default(), grabber_edit_point_pixbuf, 5, 17);
1249         }
1250
1251         cross_hair_cursor = new Gdk::Cursor (CROSSHAIR);
1252         trimmer_cursor =  new Gdk::Cursor (SB_H_DOUBLE_ARROW);
1253
1254         {
1255                 Glib::RefPtr<Gdk::Pixbuf> apixbuf (::get_icon ("trim_left_cursor"));
1256                 left_side_trim_cursor = new Gdk::Cursor (Gdk::Display::get_default(), apixbuf, 5, 11);
1257         }
1258
1259         {
1260                 Glib::RefPtr<Gdk::Pixbuf> apixbuf (::get_icon ("trim_right_cursor"));
1261                 right_side_trim_cursor = new Gdk::Cursor (Gdk::Display::get_default(), apixbuf, 23, 11);
1262         }
1263
1264         {
1265                 Glib::RefPtr<Gdk::Pixbuf> apixbuf (::get_icon ("fade_in_cursor"));
1266                 fade_in_cursor = new Gdk::Cursor (Gdk::Display::get_default(), apixbuf, 0, 40);
1267         }
1268
1269         {
1270                 Glib::RefPtr<Gdk::Pixbuf> apixbuf (::get_icon ("fade_out_cursor"));
1271                 fade_out_cursor = new Gdk::Cursor (Gdk::Display::get_default(), apixbuf, 27, 40);
1272         }
1273
1274         selector_cursor = new Gdk::Cursor (XTERM);
1275         time_fx_cursor = new Gdk::Cursor (SIZING);
1276         wait_cursor = new Gdk::Cursor  (WATCH);
1277         timebar_cursor = new Gdk::Cursor(LEFT_PTR);
1278         midi_pencil_cursor = new Gdk::Cursor (PENCIL);
1279         midi_select_cursor = new Gdk::Cursor (CENTER_PTR);
1280         midi_resize_cursor = new Gdk::Cursor (SIZING);
1281         midi_erase_cursor = new Gdk::Cursor (DRAPED_BOX);
1282         up_down_cursor = new Gdk::Cursor (Gdk::SB_V_DOUBLE_ARROW);
1283 }
1284
1285 /** Pop up a context menu for when the user clicks on a fade in or fade out */
1286 void
1287 Editor::popup_fade_context_menu (int button, int32_t time, ArdourCanvas::Item* item, ItemType item_type)
1288 {
1289         using namespace Menu_Helpers;
1290         AudioRegionView* arv = static_cast<AudioRegionView*> (item->get_data ("regionview"));
1291
1292         if (arv == 0) {
1293                 fatal << _("programming error: fade in canvas item has no regionview data pointer!") << endmsg;
1294                 /*NOTREACHED*/
1295         }
1296
1297         MenuList& items (fade_context_menu.items());
1298
1299         items.clear ();
1300
1301         switch (item_type) {
1302         case FadeInItem:
1303         case FadeInHandleItem:
1304                 if (arv->audio_region()->fade_in_active()) {
1305                         items.push_back (MenuElem (_("Deactivate"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_active), false)));
1306                 } else {
1307                         items.push_back (MenuElem (_("Activate"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_active), true)));
1308                 }
1309
1310                 items.push_back (SeparatorElem());
1311
1312                 if (Profile->get_sae()) {
1313                         items.push_back (MenuElem (_("Linear"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Linear)));
1314                         items.push_back (MenuElem (_("Slowest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Fast)));
1315                 } else {
1316                         items.push_back (MenuElem (_("Linear"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Linear)));
1317                         items.push_back (MenuElem (_("Slowest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Fast)));
1318                         items.push_back (MenuElem (_("Slow"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::LogB)));
1319                         items.push_back (MenuElem (_("Fast"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::LogA)));
1320                         items.push_back (MenuElem (_("Fastest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Slow)));
1321                 }
1322
1323                 break;
1324
1325         case FadeOutItem:
1326         case FadeOutHandleItem:
1327                 if (arv->audio_region()->fade_out_active()) {
1328                         items.push_back (MenuElem (_("Deactivate"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_active), false)));
1329                 } else {
1330                         items.push_back (MenuElem (_("Activate"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_active), true)));
1331                 }
1332
1333                 items.push_back (SeparatorElem());
1334
1335                 if (Profile->get_sae()) {
1336                         items.push_back (MenuElem (_("Linear"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Linear)));
1337                         items.push_back (MenuElem (_("Slowest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Slow)));
1338                 } else {
1339                         items.push_back (MenuElem (_("Linear"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Linear)));
1340                         items.push_back (MenuElem (_("Slowest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Slow)));
1341                         items.push_back (MenuElem (_("Slow"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::LogA)));
1342                         items.push_back (MenuElem (_("Fast"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::LogB)));
1343                         items.push_back (MenuElem (_("Fastest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Fast)));
1344                 }
1345
1346                 break;
1347
1348         default:
1349                 fatal << _("programming error: ")
1350                       << X_("non-fade canvas item passed to popup_fade_context_menu()")
1351                       << endmsg;
1352                 /*NOTREACHED*/
1353         }
1354
1355         fade_context_menu.popup (button, time);
1356 }
1357
1358 void
1359 Editor::popup_track_context_menu (int button, int32_t time, ItemType item_type, bool with_selection, nframes64_t frame)
1360 {
1361         using namespace Menu_Helpers;
1362         Menu* (Editor::*build_menu_function)(nframes64_t);
1363         Menu *menu;
1364
1365         switch (item_type) {
1366         case RegionItem:
1367         case RegionViewName:
1368         case RegionViewNameHighlight:
1369         case LeftFrameHandle:
1370         case RightFrameHandle:
1371                 if (with_selection) {
1372                         build_menu_function = &Editor::build_track_selection_context_menu;
1373                 } else {
1374                         build_menu_function = &Editor::build_track_region_context_menu;
1375                 }
1376                 break;
1377
1378         case SelectionItem:
1379                 if (with_selection) {
1380                         build_menu_function = &Editor::build_track_selection_context_menu;
1381                 } else {
1382                         build_menu_function = &Editor::build_track_context_menu;
1383                 }
1384                 break;
1385
1386         case CrossfadeViewItem:
1387                 build_menu_function = &Editor::build_track_crossfade_context_menu;
1388                 break;
1389
1390         case StreamItem:
1391                 if (clicked_routeview->track()) {
1392                         build_menu_function = &Editor::build_track_context_menu;
1393                 } else {
1394                         build_menu_function = &Editor::build_track_bus_context_menu;
1395                 }
1396                 break;
1397
1398         default:
1399                 /* probably shouldn't happen but if it does, we don't care */
1400                 return;
1401         }
1402
1403         menu = (this->*build_menu_function)(frame);
1404         menu->set_name ("ArdourContextMenu");
1405
1406         /* now handle specific situations */
1407
1408         switch (item_type) {
1409         case RegionItem:
1410         case RegionViewName:
1411         case RegionViewNameHighlight:
1412         case LeftFrameHandle:
1413         case RightFrameHandle:
1414                 if (!with_selection) {
1415                         if (region_edit_menu_split_item) {
1416                                 if (clicked_regionview && clicked_regionview->region()->covers (get_preferred_edit_position())) {
1417                                         ActionManager::set_sensitive (ActionManager::edit_point_in_region_sensitive_actions, true);
1418                                 } else {
1419                                         ActionManager::set_sensitive (ActionManager::edit_point_in_region_sensitive_actions, false);
1420                                 }
1421                         }
1422                         if (region_edit_menu_split_multichannel_item) {
1423                                 if (clicked_regionview && clicked_regionview->region()->n_channels() > 1) {
1424                                         region_edit_menu_split_multichannel_item->set_sensitive (true);
1425                                 } else {
1426                                         region_edit_menu_split_multichannel_item->set_sensitive (false);
1427                                 }
1428                         }
1429                 }
1430                 break;
1431
1432         case SelectionItem:
1433                 break;
1434
1435         case CrossfadeViewItem:
1436                 break;
1437
1438         case StreamItem:
1439                 break;
1440
1441         default:
1442                 /* probably shouldn't happen but if it does, we don't care */
1443                 return;
1444         }
1445
1446         if (item_type != SelectionItem && clicked_routeview && clicked_routeview->audio_track()) {
1447
1448                 /* Bounce to disk */
1449
1450                 using namespace Menu_Helpers;
1451                 MenuList& edit_items  = menu->items();
1452
1453                 edit_items.push_back (SeparatorElem());
1454
1455                 switch (clicked_routeview->audio_track()->freeze_state()) {
1456                 case AudioTrack::NoFreeze:
1457                         edit_items.push_back (MenuElem (_("Freeze"), sigc::mem_fun(*this, &Editor::freeze_route)));
1458                         break;
1459
1460                 case AudioTrack::Frozen:
1461                         edit_items.push_back (MenuElem (_("Unfreeze"), sigc::mem_fun(*this, &Editor::unfreeze_route)));
1462                         break;
1463
1464                 case AudioTrack::UnFrozen:
1465                         edit_items.push_back (MenuElem (_("Freeze"), sigc::mem_fun(*this, &Editor::freeze_route)));
1466                         break;
1467                 }
1468
1469         }
1470
1471         if (item_type == StreamItem && clicked_routeview) {
1472                 clicked_routeview->build_underlay_menu(menu);
1473         }
1474
1475         menu->popup (button, time);
1476 }
1477
1478 Menu*
1479 Editor::build_track_context_menu (nframes64_t)
1480 {
1481         using namespace Menu_Helpers;
1482
1483         MenuList& edit_items = track_context_menu.items();
1484         edit_items.clear();
1485
1486         add_dstream_context_items (edit_items);
1487         return &track_context_menu;
1488 }
1489
1490 Menu*
1491 Editor::build_track_bus_context_menu (nframes64_t)
1492 {
1493         using namespace Menu_Helpers;
1494
1495         MenuList& edit_items = track_context_menu.items();
1496         edit_items.clear();
1497
1498         add_bus_context_items (edit_items);
1499         return &track_context_menu;
1500 }
1501
1502 Menu*
1503 Editor::build_track_region_context_menu (nframes64_t frame)
1504 {
1505         using namespace Menu_Helpers;
1506         MenuList& edit_items  = track_region_context_menu.items();
1507         edit_items.clear();
1508
1509         /* we've just cleared the track region context menu, so the menu that these
1510            two items were on will have disappeared; stop them dangling.
1511         */
1512         region_edit_menu_split_item = 0;
1513         region_edit_menu_split_multichannel_item = 0;
1514
1515         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (clicked_axisview);
1516
1517         if (rtv) {
1518                 boost::shared_ptr<Track> tr;
1519                 boost::shared_ptr<Playlist> pl;
1520
1521                 /* Don't offer a region submenu if we are in internal edit mode, as we don't select regions in this
1522                    mode and so offering region context is somewhat confusing.
1523                 */
1524                 if ((tr = rtv->track()) && ((pl = tr->playlist())) && !internal_editing()) {
1525                         Playlist::RegionList* regions = pl->regions_at ((nframes64_t) floor ( (double)frame * tr->speed()));
1526
1527                         if (selection->regions.size() > 1) {
1528                                 // there's already a multiple selection: just add a
1529                                 // single region context menu that will act on all
1530                                 // selected regions
1531
1532                                 list<boost::shared_ptr<Region> > regions;
1533                                 for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
1534                                         regions.push_back ((*i)->region ());
1535                                 }
1536                                 
1537                                 add_region_context_items (rtv->view(), regions, edit_items);
1538                         } else {
1539                                 for (Playlist::RegionList::reverse_iterator i = regions->rbegin(); i != regions->rend(); ++i) {
1540                                         list<boost::shared_ptr<Region> > regions;
1541                                         regions.push_back (*i);
1542                                         add_region_context_items (rtv->view(), regions, edit_items);
1543                                 }
1544                         }
1545
1546                         delete regions;
1547                 }
1548         }
1549
1550         add_dstream_context_items (edit_items);
1551
1552         return &track_region_context_menu;
1553 }
1554
1555 Menu*
1556 Editor::build_track_crossfade_context_menu (nframes64_t frame)
1557 {
1558         using namespace Menu_Helpers;
1559         MenuList& edit_items  = track_crossfade_context_menu.items();
1560         edit_items.clear ();
1561
1562         AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*> (clicked_axisview);
1563
1564         if (atv) {
1565                 boost::shared_ptr<Track> tr;
1566                 boost::shared_ptr<Playlist> pl;
1567                 boost::shared_ptr<AudioPlaylist> apl;
1568
1569                 if ((tr = atv->track()) && ((pl = tr->playlist()) != 0) && ((apl = boost::dynamic_pointer_cast<AudioPlaylist> (pl)) != 0)) {
1570
1571                         Playlist::RegionList* regions = pl->regions_at (frame);
1572                         AudioPlaylist::Crossfades xfades;
1573
1574                         apl->crossfades_at (frame, xfades);
1575
1576                         bool many = xfades.size() > 1;
1577
1578                         for (AudioPlaylist::Crossfades::iterator i = xfades.begin(); i != xfades.end(); ++i) {
1579                                 add_crossfade_context_items (atv->audio_view(), (*i), edit_items, many);
1580                         }
1581
1582                         if (selection->regions.size() > 1) {
1583                                 // there's already a multiple selection: just add a
1584                                 // single region context menu that will act on all
1585                                 // selected regions
1586
1587                                 list<boost::shared_ptr<Region> > regions;
1588                                 for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
1589                                         regions.push_back ((*i)->region ());
1590                                 }
1591
1592                                 add_region_context_items (atv->audio_view(), regions, edit_items);
1593                         } else {
1594                                 for (Playlist::RegionList::reverse_iterator i = regions->rbegin(); i != regions->rend(); ++i) {
1595                                         list<boost::shared_ptr<Region> > regions;
1596                                         regions.push_back (*i);
1597                                         add_region_context_items (atv->audio_view(), regions, edit_items);
1598                                 }
1599                         }
1600                         delete regions;
1601                 }
1602         }
1603
1604         add_dstream_context_items (edit_items);
1605
1606         return &track_crossfade_context_menu;
1607 }
1608
1609 void
1610 Editor::analyze_region_selection()
1611 {
1612         if (analysis_window == 0) {
1613                 analysis_window = new AnalysisWindow();
1614
1615                 if (_session != 0)
1616                         analysis_window->set_session(_session);
1617
1618                 analysis_window->show_all();
1619         }
1620
1621         analysis_window->set_regionmode();
1622         analysis_window->analyze();
1623
1624         analysis_window->present();
1625 }
1626
1627 void
1628 Editor::analyze_range_selection()
1629 {
1630         if (analysis_window == 0) {
1631                 analysis_window = new AnalysisWindow();
1632
1633                 if (_session != 0)
1634                         analysis_window->set_session(_session);
1635
1636                 analysis_window->show_all();
1637         }
1638
1639         analysis_window->set_rangemode();
1640         analysis_window->analyze();
1641
1642         analysis_window->present();
1643 }
1644
1645 Menu*
1646 Editor::build_track_selection_context_menu (nframes64_t)
1647 {
1648         using namespace Menu_Helpers;
1649         MenuList& edit_items  = track_selection_context_menu.items();
1650         edit_items.clear ();
1651
1652         add_selection_context_items (edit_items);
1653         // edit_items.push_back (SeparatorElem());
1654         // add_dstream_context_items (edit_items);
1655
1656         return &track_selection_context_menu;
1657 }
1658
1659 /** Add context menu items relevant to crossfades.
1660  * @param edit_items List to add the items to.
1661  */
1662 void
1663 Editor::add_crossfade_context_items (AudioStreamView* /*view*/, boost::shared_ptr<Crossfade> xfade, Menu_Helpers::MenuList& edit_items, bool many)
1664 {
1665         using namespace Menu_Helpers;
1666         Menu     *xfade_menu = manage (new Menu);
1667         MenuList& items       = xfade_menu->items();
1668         xfade_menu->set_name ("ArdourContextMenu");
1669         string str;
1670
1671         if (xfade->active()) {
1672                 str = _("Mute");
1673         } else {
1674                 str = _("Unmute");
1675         }
1676
1677         items.push_back (MenuElem (str, sigc::bind (sigc::mem_fun(*this, &Editor::toggle_xfade_active), boost::weak_ptr<Crossfade> (xfade))));
1678         items.push_back (MenuElem (_("Edit..."), sigc::bind (sigc::mem_fun(*this, &Editor::edit_xfade), boost::weak_ptr<Crossfade> (xfade))));
1679
1680         if (xfade->can_follow_overlap()) {
1681
1682                 if (xfade->following_overlap()) {
1683                         str = _("Convert to Short");
1684                 } else {
1685                         str = _("Convert to Full");
1686                 }
1687
1688                 items.push_back (MenuElem (str, sigc::bind (sigc::mem_fun(*this, &Editor::toggle_xfade_length), xfade)));
1689         }
1690
1691         if (many) {
1692                 str = xfade->out()->name();
1693                 str += "->";
1694                 str += xfade->in()->name();
1695         } else {
1696                 str = _("Crossfade");
1697         }
1698
1699         edit_items.push_back (MenuElem (str, *xfade_menu));
1700         edit_items.push_back (SeparatorElem());
1701 }
1702
1703 void
1704 Editor::xfade_edit_left_region ()
1705 {
1706         if (clicked_crossfadeview) {
1707                 clicked_crossfadeview->left_view.show_region_editor ();
1708         }
1709 }
1710
1711 void
1712 Editor::xfade_edit_right_region ()
1713 {
1714         if (clicked_crossfadeview) {
1715                 clicked_crossfadeview->right_view.show_region_editor ();
1716         }
1717 }
1718
1719 void
1720 Editor::add_region_context_items (StreamView* sv, list<boost::shared_ptr<Region> > regions, Menu_Helpers::MenuList& edit_items)
1721 {
1722         using namespace Menu_Helpers;
1723         Gtk::MenuItem* foo_item;
1724         Menu     *region_menu = manage (new Menu);
1725         MenuList& items       = region_menu->items();
1726         region_menu->set_name ("ArdourContextMenu");
1727
1728         /* Look through the regions that we are handling and make notes about what we have got */
1729         
1730         bool have_audio = false;
1731         bool have_midi = false;
1732         bool have_locked = false;
1733         bool have_unlocked = false;
1734         bool have_position_lock_style_audio = false;
1735         bool have_position_lock_style_music = false;
1736         bool have_muted = false;
1737         bool have_unmuted = false;
1738         bool have_opaque = false;
1739         bool have_non_opaque = false;
1740         bool have_not_at_natural_position = false;
1741         bool have_envelope_visible = false;
1742         bool have_envelope_invisible = false;
1743         bool have_envelope_active = false;
1744         bool have_envelope_inactive = false;
1745         bool have_non_unity_scale_amplitude = false;
1746
1747         for (list<boost::shared_ptr<Region> >::const_iterator i = regions.begin(); i != regions.end(); ++i) {
1748                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (*i);
1749                 if (ar) {
1750                         have_audio = true;
1751                 }
1752                 if (boost::dynamic_pointer_cast<MidiRegion> (*i)) {
1753                         have_midi = true;
1754                 }
1755
1756                 if ((*i)->locked()) {
1757                         have_locked = true;
1758                 } else {
1759                         have_unlocked = true;
1760                 }
1761
1762                 if ((*i)->position_lock_style() == MusicTime) {
1763                         have_position_lock_style_music = true;
1764                 } else {
1765                         have_position_lock_style_audio = true;
1766                 }
1767
1768                 if ((*i)->muted()) {
1769                         have_muted = true;
1770                 } else {
1771                         have_unmuted = true;
1772                 }
1773
1774                 if ((*i)->opaque()) {
1775                         have_opaque = true;
1776                 } else {
1777                         have_non_opaque = true;
1778                 }
1779
1780                 if (!(*i)->at_natural_position()) {
1781                         have_not_at_natural_position = true;
1782                 }
1783
1784                 if (ar) {
1785                         RegionView* rv = sv->find_view (ar);
1786                         AudioRegionView* arv = dynamic_cast<AudioRegionView*> (rv);
1787                         
1788                         if (arv->envelope_visible()) {
1789                                 have_envelope_visible = true;
1790                         } else {
1791                                 have_envelope_invisible = true;
1792                         }
1793
1794                         if (ar->envelope_active()) {
1795                                 have_envelope_active = true;
1796                         } else {
1797                                 have_envelope_inactive = true;
1798                         }
1799
1800                         if (ar->scale_amplitude() != 1) {
1801                                 have_non_unity_scale_amplitude = true;
1802                         }
1803                 }
1804         }
1805
1806         if (regions.size() == 1) {
1807
1808                 /* when this particular menu pops up, make the relevant region
1809                    become selected.
1810                 */
1811
1812                 region_menu->signal_map_event().connect (
1813                         sigc::bind (sigc::mem_fun(*this, &Editor::set_selected_regionview_from_map_event), sv, boost::weak_ptr<Region> (regions.front()))
1814                         );
1815
1816                 items.push_back (MenuElem (_("Rename..."), sigc::mem_fun(*this, &Editor::rename_region)));
1817                 
1818                 if (have_midi) {
1819                         items.push_back (MenuElem (_("List Editor..."), sigc::mem_fun(*this, &Editor::show_midi_list_editor)));
1820                 }
1821                 
1822                 items.push_back (MenuElem (_("Region Properties..."), sigc::mem_fun(*this, &Editor::edit_region)));
1823         }
1824
1825         items.push_back (MenuElem (_("Raise to Top Layer"), sigc::mem_fun(*this, &Editor::raise_region_to_top)));
1826         items.push_back (MenuElem (_("Lower to Bottom Layer"), sigc::mem_fun  (*this, &Editor::lower_region_to_bottom)));
1827         items.push_back (SeparatorElem());
1828         items.push_back (MenuElem (_("Define Sync Point"), sigc::mem_fun(*this, &Editor::set_region_sync_from_edit_point)));
1829         if (_edit_point == EditAtMouse) {
1830                 items.back ().set_sensitive (false);
1831         }
1832         items.push_back (MenuElem (_("Remove Sync Point"), sigc::mem_fun(*this, &Editor::remove_region_sync)));
1833         items.push_back (SeparatorElem());
1834
1835         items.push_back (MenuElem (_("Audition"), sigc::mem_fun(*this, &Editor::play_selected_region)));
1836         items.push_back (MenuElem (_("Export..."), sigc::mem_fun(*this, &Editor::export_region)));
1837         items.push_back (MenuElem (_("Bounce"), sigc::mem_fun(*this, &Editor::bounce_region_selection)));
1838
1839         if (have_audio) {
1840                 items.push_back (MenuElem (_("Spectral Analysis..."), sigc::mem_fun(*this, &Editor::analyze_region_selection)));
1841         }
1842
1843         items.push_back (SeparatorElem());
1844
1845         items.push_back (CheckMenuElem (_("Lock")));
1846         CheckMenuItem* region_lock_item = static_cast<CheckMenuItem*>(&items.back());
1847         if (have_locked && !have_unlocked) {
1848                 region_lock_item->set_active();
1849         } else if (have_locked && have_unlocked) {
1850                 region_lock_item->set_inconsistent ();
1851         }
1852         region_lock_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_region_lock));
1853
1854         items.push_back (CheckMenuElem (_("Glue to Bars and Beats")));
1855         CheckMenuItem* bbt_glue_item = static_cast<CheckMenuItem*>(&items.back());
1856
1857         if (have_position_lock_style_music && !have_position_lock_style_audio) {
1858                 bbt_glue_item->set_active ();
1859         } else if (have_position_lock_style_music && have_position_lock_style_audio) {
1860                 bbt_glue_item->set_inconsistent ();
1861         }
1862
1863         bbt_glue_item->signal_activate().connect (sigc::mem_fun (*this, &Editor::toggle_region_lock_style));
1864
1865         items.push_back (CheckMenuElem (_("Mute")));
1866         CheckMenuItem* region_mute_item = static_cast<CheckMenuItem*>(&items.back());
1867
1868         if (have_muted && !have_unmuted) {
1869                 region_mute_item->set_active();
1870         } else if (have_muted && have_unmuted) {
1871                 region_mute_item->set_inconsistent ();
1872         }
1873         
1874         region_mute_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_region_mute));
1875         
1876         items.push_back (MenuElem (_("Transpose..."), mem_fun(*this, &Editor::pitch_shift_regions)));
1877
1878         if (!Profile->get_sae()) {
1879                 items.push_back (CheckMenuElem (_("Opaque")));
1880                 CheckMenuItem* region_opaque_item = static_cast<CheckMenuItem*>(&items.back());
1881                 if (have_opaque && !have_non_opaque) {
1882                         region_opaque_item->set_active();
1883                 } else if (have_opaque && have_non_opaque) {
1884                         region_opaque_item->set_inconsistent ();
1885                 }
1886                 region_opaque_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_region_opaque));
1887         }
1888
1889         items.push_back (CheckMenuElem (_("Original Position"), sigc::mem_fun(*this, &Editor::naturalize)));
1890         if (!have_not_at_natural_position) {
1891                 items.back().set_sensitive (false);
1892         }
1893
1894         items.push_back (SeparatorElem());
1895
1896         if (have_audio) {
1897
1898                 if (!Profile->get_sae()) {
1899                         items.push_back (MenuElem (_("Reset Envelope"), sigc::mem_fun(*this, &Editor::reset_region_gain_envelopes)));
1900
1901                         items.push_back (CheckMenuElem (_("Envelope Visible")));
1902                         CheckMenuItem* region_envelope_visible_item = static_cast<CheckMenuItem*> (&items.back());
1903                         if (have_envelope_visible && !have_envelope_invisible) {
1904                                 region_envelope_visible_item->set_active ();
1905                         } else if (have_envelope_visible && have_envelope_invisible) {
1906                                 region_envelope_visible_item->set_inconsistent ();
1907                         }
1908                         region_envelope_visible_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_gain_envelope_visibility));
1909
1910                         items.push_back (CheckMenuElem (_("Envelope Active")));
1911                         CheckMenuItem* region_envelope_active_item = static_cast<CheckMenuItem*> (&items.back());
1912
1913                         if (have_envelope_active && !have_envelope_inactive) {
1914                                 region_envelope_active_item->set_active ();
1915                         } else if (have_envelope_active && have_envelope_inactive) {
1916                                 region_envelope_active_item->set_inconsistent ();
1917                         }
1918
1919                         region_envelope_active_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_gain_envelope_active));
1920                         items.push_back (SeparatorElem());
1921                 }
1922
1923                 items.push_back (MenuElem (_("Normalize..."), sigc::mem_fun(*this, &Editor::normalize_region)));
1924                 if (have_non_unity_scale_amplitude) {
1925                         items.push_back (MenuElem (_("Reset Gain"), sigc::mem_fun(*this, &Editor::reset_region_scale_amplitude)));
1926                 }
1927
1928         } else if (have_midi) {
1929                 items.push_back (MenuElem (_("Quantize"), sigc::mem_fun(*this, &Editor::quantize_region)));
1930                 items.push_back (MenuElem (_("Fork"), sigc::mem_fun(*this, &Editor::fork_region)));
1931                 items.push_back (SeparatorElem());
1932         }
1933
1934         items.push_back (MenuElem (_("Strip Silence..."), sigc::mem_fun (*this, &Editor::strip_region_silence)));
1935         items.push_back (MenuElem (_("Reverse"), sigc::mem_fun(*this, &Editor::reverse_region)));
1936         items.push_back (SeparatorElem());
1937
1938         /* range related stuff */
1939
1940         items.push_back (MenuElem (_("Add Single Range"), sigc::mem_fun (*this, &Editor::add_location_from_audio_region)));
1941         items.push_back (MenuElem (_("Add Range Markers"), sigc::mem_fun (*this, &Editor::add_locations_from_audio_region)));
1942         if (selection->regions.size() < 2) {
1943                 items.back().set_sensitive (false);
1944         }
1945
1946         items.push_back (MenuElem (_("Set Range Selection"), sigc::mem_fun (*this, &Editor::set_selection_from_region)));
1947         items.push_back (SeparatorElem());
1948
1949         /* Nudge region */
1950
1951         Menu *nudge_menu = manage (new Menu());
1952         MenuList& nudge_items = nudge_menu->items();
1953         nudge_menu->set_name ("ArdourContextMenu");
1954
1955         nudge_items.push_back (MenuElem (_("Nudge Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_forward), false, false))));
1956         nudge_items.push_back (MenuElem (_("Nudge Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_backward), false, false))));
1957         nudge_items.push_back (MenuElem (_("Nudge Forward by Capture Offset"), (sigc::mem_fun(*this, &Editor::nudge_forward_capture_offset))));
1958         nudge_items.push_back (MenuElem (_("Nudge Backward by Capture Offset"), (sigc::mem_fun(*this, &Editor::nudge_backward_capture_offset))));
1959
1960         items.push_back (MenuElem (_("Nudge"), *nudge_menu));
1961         items.push_back (SeparatorElem());
1962
1963         Menu *trim_menu = manage (new Menu);
1964         MenuList& trim_items = trim_menu->items();
1965         trim_menu->set_name ("ArdourContextMenu");
1966
1967         trim_items.push_back (MenuElem (_("Start to Edit Point"), sigc::mem_fun(*this, &Editor::trim_region_from_edit_point)));
1968         foo_item = &trim_items.back();
1969         if (_edit_point == EditAtMouse) {
1970                 foo_item->set_sensitive (false);
1971         }
1972         trim_items.push_back (MenuElem (_("Edit Point to End"), sigc::mem_fun(*this, &Editor::trim_region_to_edit_point)));
1973         foo_item = &trim_items.back();
1974         if (_edit_point == EditAtMouse) {
1975                 foo_item->set_sensitive (false);
1976         }
1977         trim_items.push_back (MenuElem (_("Trim to Loop"), sigc::mem_fun(*this, &Editor::trim_region_to_loop)));
1978         trim_items.push_back (MenuElem (_("Trim to Punch"), sigc::mem_fun(*this, &Editor::trim_region_to_punch)));
1979
1980         items.push_back (MenuElem (_("Trim"), *trim_menu));
1981         items.push_back (SeparatorElem());
1982
1983         items.push_back (MenuElem (_("Split"), (sigc::mem_fun(*this, &Editor::split))));
1984         region_edit_menu_split_item = &items.back();
1985
1986         if (_edit_point == EditAtMouse) {
1987                 region_edit_menu_split_item->set_sensitive (false);
1988         }
1989
1990         if (have_audio) {
1991                 items.push_back (MenuElem (_("Make Mono Regions"), (sigc::mem_fun(*this, &Editor::split_multichannel_region))));
1992                 region_edit_menu_split_multichannel_item = &items.back();
1993         }
1994
1995         items.push_back (MenuElem (_("Duplicate"), (sigc::bind (sigc::mem_fun(*this, &Editor::duplicate_dialog), false))));
1996         items.push_back (MenuElem (_("Multi-Duplicate..."), (sigc::bind (sigc::mem_fun(*this, &Editor::duplicate_dialog), true))));
1997         items.push_back (MenuElem (_("Fill Track"), (sigc::mem_fun(*this, &Editor::region_fill_track))));
1998         items.push_back (SeparatorElem());
1999         items.push_back (MenuElem (_("Remove"), sigc::mem_fun(*this, &Editor::remove_selected_regions)));
2000
2001         /* OK, stick the region submenu at the top of the list, and then add
2002            the standard items.
2003         */
2004
2005         /* we have to hack up the region name because "_" has a special
2006            meaning for menu titles.
2007         */
2008
2009         string::size_type pos = 0;
2010         string menu_item_name = (regions.size() == 1) ? regions.front()->name() : _("Selected Regions");
2011
2012         while ((pos = menu_item_name.find ("_", pos)) != string::npos) {
2013                 menu_item_name.replace (pos, 1, "__");
2014                 pos += 2;
2015         }
2016
2017         edit_items.push_back (MenuElem (menu_item_name, *region_menu));
2018         edit_items.push_back (SeparatorElem());
2019 }
2020
2021 /** Add context menu items relevant to selection ranges.
2022  * @param edit_items List to add the items to.
2023  */
2024 void
2025 Editor::add_selection_context_items (Menu_Helpers::MenuList& edit_items)
2026 {
2027         using namespace Menu_Helpers;
2028
2029         edit_items.push_back (MenuElem (_("Play Range"), sigc::mem_fun(*this, &Editor::play_selection)));
2030         edit_items.push_back (MenuElem (_("Loop Range"), sigc::bind (sigc::mem_fun(*this, &Editor::set_loop_from_selection), true)));
2031
2032         edit_items.push_back (SeparatorElem());
2033         edit_items.push_back (MenuElem (_("Spectral Analysis"), sigc::mem_fun(*this, &Editor::analyze_range_selection)));
2034
2035         if (!selection->regions.empty()) {
2036                 edit_items.push_back (SeparatorElem());
2037                 edit_items.push_back (MenuElem (_("Extend Range to End of Region"), sigc::bind (sigc::mem_fun(*this, &Editor::extend_selection_to_end_of_region), false)));
2038                 edit_items.push_back (MenuElem (_("Extend Range to Start of Region"), sigc::bind (sigc::mem_fun(*this, &Editor::extend_selection_to_start_of_region), false)));
2039         }
2040
2041         edit_items.push_back (SeparatorElem());
2042         edit_items.push_back (MenuElem (_("Convert to region in-place"), mem_fun(*this, &Editor::separate_region_from_selection)));
2043         edit_items.push_back (MenuElem (_("Convert to Region in Region List"), sigc::mem_fun(*this, &Editor::new_region_from_selection)));
2044
2045         edit_items.push_back (SeparatorElem());
2046         edit_items.push_back (MenuElem (_("Select All in Range"), sigc::mem_fun(*this, &Editor::select_all_selectables_using_time_selection)));
2047
2048         edit_items.push_back (SeparatorElem());
2049         edit_items.push_back (MenuElem (_("Set Loop from Range"), sigc::bind (sigc::mem_fun(*this, &Editor::set_loop_from_selection), false)));
2050         edit_items.push_back (MenuElem (_("Set Punch from Range"), sigc::mem_fun(*this, &Editor::set_punch_from_selection)));
2051
2052         edit_items.push_back (SeparatorElem());
2053         edit_items.push_back (MenuElem (_("Add Range Markers"), sigc::mem_fun (*this, &Editor::add_location_from_selection)));
2054
2055         edit_items.push_back (SeparatorElem());
2056         edit_items.push_back (MenuElem (_("Crop Region to Range"), sigc::mem_fun(*this, &Editor::crop_region_to_selection)));
2057         edit_items.push_back (MenuElem (_("Fill Range with Region"), sigc::mem_fun(*this, &Editor::region_fill_selection)));
2058         edit_items.push_back (MenuElem (_("Duplicate Range"), sigc::bind (sigc::mem_fun(*this, &Editor::duplicate_dialog), false)));
2059
2060         edit_items.push_back (SeparatorElem());
2061         edit_items.push_back (MenuElem (_("Consolidate Range"), sigc::bind (sigc::mem_fun(*this, &Editor::bounce_range_selection), true, false)));
2062         edit_items.push_back (MenuElem (_("Consolidate Range With Processing"), sigc::bind (sigc::mem_fun(*this, &Editor::bounce_range_selection), true, true)));
2063         edit_items.push_back (MenuElem (_("Bounce Range to Region List"), sigc::bind (sigc::mem_fun(*this, &Editor::bounce_range_selection), false, false)));
2064         edit_items.push_back (MenuElem (_("Bounce Range to Region List With Processing"), sigc::bind (sigc::mem_fun(*this, &Editor::bounce_range_selection), false, true)));
2065         edit_items.push_back (MenuElem (_("Export Range"), sigc::mem_fun(*this, &Editor::export_selection)));
2066 }
2067
2068
2069 void
2070 Editor::add_dstream_context_items (Menu_Helpers::MenuList& edit_items)
2071 {
2072         using namespace Menu_Helpers;
2073
2074         /* Playback */
2075
2076         Menu *play_menu = manage (new Menu);
2077         MenuList& play_items = play_menu->items();
2078         play_menu->set_name ("ArdourContextMenu");
2079
2080         play_items.push_back (MenuElem (_("Play From Edit Point"), sigc::mem_fun(*this, &Editor::play_from_edit_point)));
2081         play_items.push_back (MenuElem (_("Play From Start"), sigc::mem_fun(*this, &Editor::play_from_start)));
2082         play_items.push_back (MenuElem (_("Play Region"), sigc::mem_fun(*this, &Editor::play_selected_region)));
2083         play_items.push_back (SeparatorElem());
2084         play_items.push_back (MenuElem (_("Loop Region"), sigc::mem_fun(*this, &Editor::loop_selected_region)));
2085
2086         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2087
2088         /* Selection */
2089
2090         Menu *select_menu = manage (new Menu);
2091         MenuList& select_items = select_menu->items();
2092         select_menu->set_name ("ArdourContextMenu");
2093
2094         select_items.push_back (MenuElem (_("Select All in Track"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2095         select_items.push_back (MenuElem (_("Select All"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all), Selection::Set)));
2096         select_items.push_back (MenuElem (_("Invert Selection in Track"), sigc::mem_fun(*this, &Editor::invert_selection_in_track)));
2097         select_items.push_back (MenuElem (_("Invert Selection"), sigc::mem_fun(*this, &Editor::invert_selection)));
2098         select_items.push_back (SeparatorElem());
2099         select_items.push_back (MenuElem (_("Set Range to Loop Range"), sigc::mem_fun(*this, &Editor::set_selection_from_loop)));
2100         select_items.push_back (MenuElem (_("Set Range to Punch Range"), sigc::mem_fun(*this, &Editor::set_selection_from_punch)));
2101         select_items.push_back (SeparatorElem());
2102         select_items.push_back (MenuElem (_("Select All After Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_edit), true)));
2103         select_items.push_back (MenuElem (_("Select All Before Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_edit), false)));
2104         select_items.push_back (MenuElem (_("Select All After Playhead"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2105         select_items.push_back (MenuElem (_("Select All Before Playhead"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2106         select_items.push_back (MenuElem (_("Select All Between Playhead and Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_between), false)));
2107         select_items.push_back (MenuElem (_("Select All Within Playhead and Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_between), true)));
2108         select_items.push_back (MenuElem (_("Select Range Between Playhead and Edit Point"), sigc::mem_fun(*this, &Editor::select_range_between)));
2109
2110         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2111
2112         /* Cut-n-Paste */
2113
2114         Menu *cutnpaste_menu = manage (new Menu);
2115         MenuList& cutnpaste_items = cutnpaste_menu->items();
2116         cutnpaste_menu->set_name ("ArdourContextMenu");
2117
2118         cutnpaste_items.push_back (MenuElem (_("Cut"), sigc::mem_fun(*this, &Editor::cut)));
2119         cutnpaste_items.push_back (MenuElem (_("Copy"), sigc::mem_fun(*this, &Editor::copy)));
2120         cutnpaste_items.push_back (MenuElem (_("Paste"), sigc::bind (sigc::mem_fun(*this, &Editor::paste), 1.0f)));
2121
2122         cutnpaste_items.push_back (SeparatorElem());
2123
2124         cutnpaste_items.push_back (MenuElem (_("Align"), sigc::bind (sigc::mem_fun(*this, &Editor::align), ARDOUR::SyncPoint)));
2125         cutnpaste_items.push_back (MenuElem (_("Align Relative"), sigc::bind (sigc::mem_fun(*this, &Editor::align_relative), ARDOUR::SyncPoint)));
2126
2127         edit_items.push_back (MenuElem (_("Edit"), *cutnpaste_menu));
2128
2129         /* Adding new material */
2130
2131         edit_items.push_back (SeparatorElem());
2132         edit_items.push_back (MenuElem (_("Insert Selected Region"), sigc::bind (sigc::mem_fun(*this, &Editor::insert_region_list_selection), 1.0f)));
2133         edit_items.push_back (MenuElem (_("Insert Existing Media"), sigc::bind (sigc::mem_fun(*this, &Editor::add_external_audio_action), ImportToTrack)));
2134
2135         /* Nudge track */
2136
2137         Menu *nudge_menu = manage (new Menu());
2138         MenuList& nudge_items = nudge_menu->items();
2139         nudge_menu->set_name ("ArdourContextMenu");
2140
2141         edit_items.push_back (SeparatorElem());
2142         nudge_items.push_back (MenuElem (_("Nudge Entire Track Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), false, true))));
2143         nudge_items.push_back (MenuElem (_("Nudge Track After Edit Point Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), true, true))));
2144         nudge_items.push_back (MenuElem (_("Nudge Entire Track Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), false, false))));
2145         nudge_items.push_back (MenuElem (_("Nudge Track After Edit Point Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), true, false))));
2146
2147         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2148 }
2149
2150 void
2151 Editor::add_bus_context_items (Menu_Helpers::MenuList& edit_items)
2152 {
2153         using namespace Menu_Helpers;
2154
2155         /* Playback */
2156
2157         Menu *play_menu = manage (new Menu);
2158         MenuList& play_items = play_menu->items();
2159         play_menu->set_name ("ArdourContextMenu");
2160
2161         play_items.push_back (MenuElem (_("Play From Edit Point"), sigc::mem_fun(*this, &Editor::play_from_edit_point)));
2162         play_items.push_back (MenuElem (_("Play From Start"), sigc::mem_fun(*this, &Editor::play_from_start)));
2163         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2164
2165         /* Selection */
2166
2167         Menu *select_menu = manage (new Menu);
2168         MenuList& select_items = select_menu->items();
2169         select_menu->set_name ("ArdourContextMenu");
2170
2171         select_items.push_back (MenuElem (_("Select All in Track"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2172         select_items.push_back (MenuElem (_("Select All"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all), Selection::Set)));
2173         select_items.push_back (MenuElem (_("Invert Selection in Track"), sigc::mem_fun(*this, &Editor::invert_selection_in_track)));
2174         select_items.push_back (MenuElem (_("Invert Selection"), sigc::mem_fun(*this, &Editor::invert_selection)));
2175         select_items.push_back (SeparatorElem());
2176         select_items.push_back (MenuElem (_("Select All After Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_edit), true)));
2177         select_items.push_back (MenuElem (_("Select All Before Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_edit), false)));
2178         select_items.push_back (MenuElem (_("Select All After Playhead"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2179         select_items.push_back (MenuElem (_("Select All Before Playhead"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2180
2181         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2182
2183         /* Cut-n-Paste */
2184
2185         Menu *cutnpaste_menu = manage (new Menu);
2186         MenuList& cutnpaste_items = cutnpaste_menu->items();
2187         cutnpaste_menu->set_name ("ArdourContextMenu");
2188
2189         cutnpaste_items.push_back (MenuElem (_("Cut"), sigc::mem_fun(*this, &Editor::cut)));
2190         cutnpaste_items.push_back (MenuElem (_("Copy"), sigc::mem_fun(*this, &Editor::copy)));
2191         cutnpaste_items.push_back (MenuElem (_("Paste"), sigc::bind (sigc::mem_fun(*this, &Editor::paste), 1.0f)));
2192
2193         Menu *nudge_menu = manage (new Menu());
2194         MenuList& nudge_items = nudge_menu->items();
2195         nudge_menu->set_name ("ArdourContextMenu");
2196
2197         edit_items.push_back (SeparatorElem());
2198         nudge_items.push_back (MenuElem (_("Nudge Entire Track Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), false, true))));
2199         nudge_items.push_back (MenuElem (_("Nudge Track After Edit Point Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), true, true))));
2200         nudge_items.push_back (MenuElem (_("Nudge Entire Track Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), false, false))));
2201         nudge_items.push_back (MenuElem (_("Nudge Track After Edit Point Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), true, false))));
2202
2203         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2204 }
2205
2206 SnapType
2207 Editor::snap_type() const
2208 {
2209         return _snap_type;
2210 }
2211
2212 SnapMode
2213 Editor::snap_mode() const
2214 {
2215         return _snap_mode;
2216 }
2217
2218 void
2219 Editor::set_snap_to (SnapType st)
2220 {
2221         unsigned int snap_ind = (unsigned int)st;
2222
2223         _snap_type = st;
2224
2225         if (snap_ind > snap_type_strings.size() - 1) {
2226                 snap_ind = 0;
2227                 _snap_type = (SnapType)snap_ind;
2228         }
2229
2230         string str = snap_type_strings[snap_ind];
2231
2232         if (str != snap_type_selector.get_active_text()) {
2233                 snap_type_selector.set_active_text (str);
2234         }
2235
2236         instant_save ();
2237
2238         switch (_snap_type) {
2239         case SnapToBeatDiv32:
2240         case SnapToBeatDiv28:
2241         case SnapToBeatDiv24:
2242         case SnapToBeatDiv20:
2243         case SnapToBeatDiv16:
2244         case SnapToBeatDiv14:
2245         case SnapToBeatDiv12:
2246         case SnapToBeatDiv10:
2247         case SnapToBeatDiv8:
2248         case SnapToBeatDiv7:
2249         case SnapToBeatDiv6:
2250         case SnapToBeatDiv5:
2251         case SnapToBeatDiv4:
2252         case SnapToBeatDiv3:
2253         case SnapToBeatDiv2:
2254                 compute_bbt_ruler_scale (leftmost_frame, leftmost_frame + current_page_frames());
2255                 update_tempo_based_rulers ();
2256                 break;
2257
2258         case SnapToRegionStart:
2259         case SnapToRegionEnd:
2260         case SnapToRegionSync:
2261         case SnapToRegionBoundary:
2262                 build_region_boundary_cache ();
2263                 break;
2264
2265         default:
2266                 /* relax */
2267                 break;
2268         }
2269
2270         SnapChanged (); /* EMIT SIGNAL */
2271 }
2272
2273 void
2274 Editor::set_snap_mode (SnapMode mode)
2275 {
2276         _snap_mode = mode;
2277         string str = snap_mode_strings[(int)mode];
2278
2279         if (str != snap_mode_selector.get_active_text ()) {
2280                 snap_mode_selector.set_active_text (str);
2281         }
2282
2283         instant_save ();
2284 }
2285 void
2286 Editor::set_edit_point_preference (EditPoint ep, bool force)
2287 {
2288         bool changed = (_edit_point != ep);
2289
2290         _edit_point = ep;
2291         string str = edit_point_strings[(int)ep];
2292
2293         if (str != edit_point_selector.get_active_text ()) {
2294                 edit_point_selector.set_active_text (str);
2295         }
2296
2297         set_canvas_cursor ();
2298
2299         if (!force && !changed) {
2300                 return;
2301         }
2302
2303         const char* action=NULL;
2304
2305         switch (_edit_point) {
2306         case EditAtPlayhead:
2307                 action = "edit-at-playhead";
2308                 break;
2309         case EditAtSelectedMarker:
2310                 action = "edit-at-marker";
2311                 break;
2312         case EditAtMouse:
2313                 action = "edit-at-mouse";
2314                 break;
2315         }
2316
2317         Glib::RefPtr<Action> act = ActionManager::get_action ("Editor", action);
2318         if (act) {
2319                 Glib::RefPtr<RadioAction>::cast_dynamic(act)->set_active (true);
2320         }
2321
2322         nframes64_t foo;
2323         bool in_track_canvas;
2324
2325         if (!mouse_frame (foo, in_track_canvas)) {
2326                 in_track_canvas = false;
2327         }
2328
2329         reset_canvas_action_sensitivity (in_track_canvas);
2330
2331         instant_save ();
2332 }
2333
2334 int
2335 Editor::set_state (const XMLNode& node, int /*version*/)
2336 {
2337         const XMLProperty* prop;
2338         XMLNode* geometry;
2339         int x, y, xoff, yoff;
2340         Gdk::Geometry g;
2341
2342         if ((prop = node.property ("id")) != 0) {
2343                 _id = prop->value ();
2344         }
2345
2346         g.base_width = default_width;
2347         g.base_height = default_height;
2348         x = 1;
2349         y = 1;
2350         xoff = 0;
2351         yoff = 21;
2352
2353         if ((geometry = find_named_node (node, "geometry")) != 0) {
2354
2355                 XMLProperty* prop;
2356
2357                 if ((prop = geometry->property("x_size")) == 0) {
2358                         prop = geometry->property ("x-size");
2359                 }
2360                 if (prop) {
2361                         g.base_width = atoi(prop->value());
2362                 }
2363                 if ((prop = geometry->property("y_size")) == 0) {
2364                         prop = geometry->property ("y-size");
2365                 }
2366                 if (prop) {
2367                         g.base_height = atoi(prop->value());
2368                 }
2369
2370                 if ((prop = geometry->property ("x_pos")) == 0) {
2371                         prop = geometry->property ("x-pos");
2372                 }
2373                 if (prop) {
2374                         x = atoi (prop->value());
2375
2376                 }
2377                 if ((prop = geometry->property ("y_pos")) == 0) {
2378                         prop = geometry->property ("y-pos");
2379                 }
2380                 if (prop) {
2381                         y = atoi (prop->value());
2382                 }
2383
2384                 if ((prop = geometry->property ("x_off")) == 0) {
2385                         prop = geometry->property ("x-off");
2386                 }
2387                 if (prop) {
2388                         xoff = atoi (prop->value());
2389                 }
2390                 if ((prop = geometry->property ("y_off")) == 0) {
2391                         prop = geometry->property ("y-off");
2392                 }
2393                 if (prop) {
2394                         yoff = atoi (prop->value());
2395                 }
2396         }
2397
2398         set_default_size (g.base_width, g.base_height);
2399         move (x, y);
2400
2401         if (_session && (prop = node.property ("playhead"))) {
2402                 nframes64_t pos;
2403                 sscanf (prop->value().c_str(), "%" PRIi64, &pos);
2404                 playhead_cursor->set_position (pos);
2405         } else {
2406                 playhead_cursor->set_position (0);
2407         }
2408         
2409         if ((prop = node.property ("mixer-width"))) {
2410                 editor_mixer_strip_width = Width (string_2_enum (prop->value(), editor_mixer_strip_width));
2411         }
2412
2413         if ((prop = node.property ("zoom-focus"))) {
2414                 set_zoom_focus ((ZoomFocus) atoi (prop->value()));
2415         }
2416
2417         if ((prop = node.property ("zoom"))) {
2418                 reset_zoom (PBD::atof (prop->value()));
2419         }
2420
2421         if ((prop = node.property ("snap-to"))) {
2422                 set_snap_to ((SnapType) atoi (prop->value()));
2423         }
2424
2425         if ((prop = node.property ("snap-mode"))) {
2426                 set_snap_mode ((SnapMode) atoi (prop->value()));
2427         }
2428
2429         if ((prop = node.property ("mouse-mode"))) {
2430                 MouseMode m = str2mousemode(prop->value());
2431                 set_mouse_mode (m, true);
2432         } else {
2433                 set_mouse_mode (MouseObject, true);
2434         }
2435
2436         if ((prop = node.property ("left-frame")) != 0){
2437                 nframes64_t pos;
2438                 if (sscanf (prop->value().c_str(), "%" PRId64, &pos) == 1) {
2439                         reset_x_origin (pos);
2440                 }
2441         }
2442
2443         if ((prop = node.property ("y-origin")) != 0) {
2444                 reset_y_origin (atof (prop->value ()));
2445         }
2446
2447         if ((prop = node.property ("internal-edit"))) {
2448                 bool yn = string_is_affirmative (prop->value());
2449                 RefPtr<Action> act = ActionManager::get_action (X_("MouseMode"), X_("toggle-internal-edit"));
2450                 if (act) {
2451                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2452                         tact->set_active (!yn);
2453                         tact->set_active (yn);
2454                 }
2455         }
2456
2457         if ((prop = node.property ("join-object-range"))) {
2458                 join_object_range_button.set_active (string_is_affirmative (prop->value ()));
2459         }
2460
2461         if ((prop = node.property ("edit-point"))) {
2462                 set_edit_point_preference ((EditPoint) string_2_enum (prop->value(), _edit_point), true);
2463         }
2464
2465         if ((prop = node.property ("show-measures"))) {
2466                 bool yn = string_is_affirmative (prop->value());
2467                 _show_measures = !yn;
2468                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleMeasureVisibility"));
2469                 if (act) {
2470                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2471                         /* do it twice to force the change */
2472                         tact->set_active (!yn);
2473                         tact->set_active (yn);
2474                 }
2475         }
2476
2477         if ((prop = node.property ("follow-playhead"))) {
2478                 bool yn = string_is_affirmative (prop->value());
2479                 set_follow_playhead (yn);
2480                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
2481                 if (act) {
2482                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2483                         if (tact->get_active() != yn) {
2484                                 tact->set_active (yn);
2485                         }
2486                 }
2487         }
2488
2489         if ((prop = node.property ("stationary-playhead"))) {
2490                 bool yn = (prop->value() == "yes");
2491                 set_stationary_playhead (yn);
2492                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-stationary-playhead"));
2493                 if (act) {
2494                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2495                         if (tact->get_active() != yn) {
2496                                 tact->set_active (yn);
2497                         }
2498                 }
2499         }
2500         
2501         if ((prop = node.property ("region-list-sort-type"))) {
2502                 RegionListSortType st;
2503                 _regions->reset_sort_type ((RegionListSortType) string_2_enum (prop->value(), st), true);
2504         }
2505
2506         if ((prop = node.property ("xfades-visible"))) {
2507                 bool yn = string_is_affirmative (prop->value());
2508                 _xfade_visibility = !yn;
2509                 // set_xfade_visibility (yn);
2510         }
2511
2512         if ((prop = node.property ("show-editor-mixer"))) {
2513
2514                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2515                 if (act) {
2516
2517                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2518                         bool yn = string_is_affirmative (prop->value());
2519
2520                         /* do it twice to force the change */
2521
2522                         tact->set_active (!yn);
2523                         tact->set_active (yn);
2524                 }
2525         }
2526
2527         if ((prop = node.property ("show-editor-list"))) {
2528
2529                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-list"));
2530                 assert(act);
2531                 if (act) {
2532
2533                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2534                         bool yn = string_is_affirmative (prop->value());
2535
2536                         /* do it twice to force the change */
2537
2538                         tact->set_active (!yn);
2539                         tact->set_active (yn);
2540                 }
2541         }
2542
2543         if ((prop = node.property (X_("editor-list-page")))) {
2544                 the_notebook.set_current_page (atoi (prop->value ()));
2545         }
2546
2547         XMLNodeList children = node.children ();
2548         for (XMLNodeList::const_iterator i = children.begin(); i != children.end(); ++i) {
2549                 selection->set_state (**i, Stateful::current_state_version);
2550         }
2551
2552         return 0;
2553 }
2554
2555 XMLNode&
2556 Editor::get_state ()
2557 {
2558         XMLNode* node = new XMLNode ("Editor");
2559         char buf[32];
2560
2561         _id.print (buf, sizeof (buf));
2562         node->add_property ("id", buf);
2563
2564         if (is_realized()) {
2565                 Glib::RefPtr<Gdk::Window> win = get_window();
2566
2567                 int x, y, xoff, yoff, width, height;
2568                 win->get_root_origin(x, y);
2569                 win->get_position(xoff, yoff);
2570                 win->get_size(width, height);
2571
2572                 XMLNode* geometry = new XMLNode ("geometry");
2573
2574                 snprintf(buf, sizeof(buf), "%d", width);
2575                 geometry->add_property("x-size", string(buf));
2576                 snprintf(buf, sizeof(buf), "%d", height);
2577                 geometry->add_property("y-size", string(buf));
2578                 snprintf(buf, sizeof(buf), "%d", x);
2579                 geometry->add_property("x-pos", string(buf));
2580                 snprintf(buf, sizeof(buf), "%d", y);
2581                 geometry->add_property("y-pos", string(buf));
2582                 snprintf(buf, sizeof(buf), "%d", xoff);
2583                 geometry->add_property("x-off", string(buf));
2584                 snprintf(buf, sizeof(buf), "%d", yoff);
2585                 geometry->add_property("y-off", string(buf));
2586                 snprintf(buf,sizeof(buf), "%d",gtk_paned_get_position (static_cast<Paned*>(&edit_pane)->gobj()));
2587                 geometry->add_property("edit-horizontal-pane-pos", string(buf));
2588                 snprintf(buf,sizeof(buf), "%d",gtk_paned_get_position (static_cast<Paned*>(&editor_summary_pane)->gobj()));
2589                 geometry->add_property("edit-vertical-pane-pos", string(buf));
2590
2591                 node->add_child_nocopy (*geometry);
2592         }
2593
2594         maybe_add_mixer_strip_width (*node);
2595
2596         snprintf (buf, sizeof(buf), "%d", (int) zoom_focus);
2597         node->add_property ("zoom-focus", buf);
2598         snprintf (buf, sizeof(buf), "%f", frames_per_unit);
2599         node->add_property ("zoom", buf);
2600         snprintf (buf, sizeof(buf), "%d", (int) _snap_type);
2601         node->add_property ("snap-to", buf);
2602         snprintf (buf, sizeof(buf), "%d", (int) _snap_mode);
2603         node->add_property ("snap-mode", buf);
2604
2605         node->add_property ("edit-point", enum_2_string (_edit_point));
2606
2607         snprintf (buf, sizeof (buf), "%" PRIi64, playhead_cursor->current_frame);
2608         node->add_property ("playhead", buf);
2609         snprintf (buf, sizeof (buf), "%" PRIi64, leftmost_frame);
2610         node->add_property ("left-frame", buf);
2611         snprintf (buf, sizeof (buf), "%f", vertical_adjustment.get_value ());
2612         node->add_property ("y-origin", buf);
2613
2614         node->add_property ("show-measures", _show_measures ? "yes" : "no");
2615         node->add_property ("follow-playhead", _follow_playhead ? "yes" : "no");
2616         node->add_property ("stationary-playhead", _stationary_playhead ? "yes" : "no");
2617         node->add_property ("xfades-visible", _xfade_visibility ? "yes" : "no");
2618         node->add_property ("region-list-sort-type", enum_2_string (_regions->sort_type ()));
2619         node->add_property ("mouse-mode", enum2str(mouse_mode));
2620         node->add_property ("internal-edit", _internal_editing ? "yes" : "no");
2621         node->add_property ("join-object-range", join_object_range_button.get_active () ? "yes" : "no");
2622
2623         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2624         if (act) {
2625                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2626                 node->add_property (X_("show-editor-mixer"), tact->get_active() ? "yes" : "no");
2627         }
2628
2629         act = ActionManager::get_action (X_("Editor"), X_("show-editor-list"));
2630         if (act) {
2631                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2632                 node->add_property (X_("show-editor-list"), tact->get_active() ? "yes" : "no");
2633         }
2634
2635         snprintf (buf, sizeof (buf), "%d", the_notebook.get_current_page ());
2636         node->add_property (X_("editor-list-page"), buf);
2637
2638         node->add_child_nocopy (selection->get_state ());
2639         
2640         return *node;
2641 }
2642
2643
2644
2645 /** @param y y offset from the top of all trackviews.
2646  *  @return pair: TimeAxisView that y is over, layer index.
2647  *  TimeAxisView may be 0.  Layer index is the layer number if the TimeAxisView is valid and is
2648  *  in stacked region display mode, otherwise 0.
2649  */
2650 std::pair<TimeAxisView *, layer_t>
2651 Editor::trackview_by_y_position (double y)
2652 {
2653         for (TrackViewList::iterator iter = track_views.begin(); iter != track_views.end(); ++iter) {
2654
2655                 std::pair<TimeAxisView*, int> const r = (*iter)->covers_y_position (y);
2656                 if (r.first) {
2657                         return r;
2658                 }
2659         }
2660
2661         return std::make_pair ( (TimeAxisView *) 0, 0);
2662 }
2663
2664 /** Snap a position to the grid, if appropriate, taking into account current
2665  *  grid settings and also the state of any snap modifier keys that may be pressed.
2666  *  @param start Position to snap.
2667  *  @param event Event to get current key modifier information from, or 0.
2668  */
2669 void
2670 Editor::snap_to_with_modifier (nframes64_t& start, GdkEvent const * event, int32_t direction, bool for_mark)
2671 {
2672         if (!_session || !event) {
2673                 return;
2674         }
2675
2676         if (Keyboard::modifier_state_contains (event->button.state, Keyboard::snap_modifier())) {
2677                 if (_snap_mode == SnapOff) {
2678                         snap_to_internal (start, direction, for_mark);
2679                 }
2680         } else {
2681                 if (_snap_mode != SnapOff) {
2682                         snap_to_internal (start, direction, for_mark);
2683                 }
2684         }
2685 }
2686
2687 void
2688 Editor::snap_to (nframes64_t& start, int32_t direction, bool for_mark)
2689 {
2690         if (!_session || _snap_mode == SnapOff) {
2691                 return;
2692         }
2693
2694         snap_to_internal (start, direction, for_mark);
2695 }
2696
2697 void
2698 Editor::timecode_snap_to_internal (nframes64_t& start, int32_t direction, bool /*for_mark*/)
2699 {
2700         const nframes64_t one_timecode_second = (nframes64_t)(rint(_session->timecode_frames_per_second()) * _session->frames_per_timecode_frame());
2701         nframes64_t one_timecode_minute = (nframes64_t)(rint(_session->timecode_frames_per_second()) * _session->frames_per_timecode_frame() * 60);
2702
2703         switch (_snap_type) {
2704         case SnapToTimecodeFrame:
2705                 if (((direction == 0) && (fmod((double)start, (double)_session->frames_per_timecode_frame()) > (_session->frames_per_timecode_frame() / 2))) || (direction > 0)) {
2706                         start = (nframes64_t) (ceil ((double) start / _session->frames_per_timecode_frame()) * _session->frames_per_timecode_frame());
2707                 } else {
2708                         start = (nframes64_t) (floor ((double) start / _session->frames_per_timecode_frame()) *  _session->frames_per_timecode_frame());
2709                 }
2710                 break;
2711
2712         case SnapToTimecodeSeconds:
2713                 if (_session->timecode_offset_negative())
2714                 {
2715                         start += _session->timecode_offset ();
2716                 } else {
2717                         start -= _session->timecode_offset ();
2718                 }
2719                 if (((direction == 0) && (start % one_timecode_second > one_timecode_second / 2)) || direction > 0) {
2720                         start = (nframes64_t) ceil ((double) start / one_timecode_second) * one_timecode_second;
2721                 } else {
2722                         start = (nframes64_t) floor ((double) start / one_timecode_second) * one_timecode_second;
2723                 }
2724
2725                 if (_session->timecode_offset_negative())
2726                 {
2727                         start -= _session->timecode_offset ();
2728                 } else {
2729                         start += _session->timecode_offset ();
2730                 }
2731                 break;
2732
2733         case SnapToTimecodeMinutes:
2734                 if (_session->timecode_offset_negative())
2735                 {
2736                         start += _session->timecode_offset ();
2737                 } else {
2738                         start -= _session->timecode_offset ();
2739                 }
2740                 if (((direction == 0) && (start % one_timecode_minute > one_timecode_minute / 2)) || direction > 0) {
2741                         start = (nframes64_t) ceil ((double) start / one_timecode_minute) * one_timecode_minute;
2742                 } else {
2743                         start = (nframes64_t) floor ((double) start / one_timecode_minute) * one_timecode_minute;
2744                 }
2745                 if (_session->timecode_offset_negative())
2746                 {
2747                         start -= _session->timecode_offset ();
2748                 } else {
2749                         start += _session->timecode_offset ();
2750                 }
2751                 break;
2752         default:
2753                 fatal << "Editor::smpte_snap_to_internal() called with non-timecode snap type!" << endmsg;
2754                 /*NOTREACHED*/
2755         }
2756 }
2757
2758 void
2759 Editor::snap_to_internal (nframes64_t& start, int32_t direction, bool for_mark)
2760 {
2761         const nframes64_t one_second = _session->frame_rate();
2762         const nframes64_t one_minute = _session->frame_rate() * 60;
2763         nframes64_t presnap = start;
2764         nframes64_t before;
2765         nframes64_t after;
2766
2767         switch (_snap_type) {
2768         case SnapToTimecodeFrame:
2769         case SnapToTimecodeSeconds:
2770         case SnapToTimecodeMinutes:
2771                 return timecode_snap_to_internal (start, direction, for_mark);
2772
2773         case SnapToCDFrame:
2774                 if (((direction == 0) && (start % (one_second/75) > (one_second/75) / 2)) || (direction > 0)) {
2775                         start = (nframes64_t) ceil ((double) start / (one_second / 75)) * (one_second / 75);
2776                 } else {
2777                         start = (nframes64_t) floor ((double) start / (one_second / 75)) * (one_second / 75);
2778                 }
2779                 break;
2780
2781         case SnapToSeconds:
2782                 if (((direction == 0) && (start % one_second > one_second / 2)) || (direction > 0)) {
2783                         start = (nframes64_t) ceil ((double) start / one_second) * one_second;
2784                 } else {
2785                         start = (nframes64_t) floor ((double) start / one_second) * one_second;
2786                 }
2787                 break;
2788
2789         case SnapToMinutes:
2790                 if (((direction == 0) && (start % one_minute > one_minute / 2)) || (direction > 0)) {
2791                         start = (nframes64_t) ceil ((double) start / one_minute) * one_minute;
2792                 } else {
2793                         start = (nframes64_t) floor ((double) start / one_minute) * one_minute;
2794                 }
2795                 break;
2796
2797         case SnapToBar:
2798                 start = _session->tempo_map().round_to_bar (start, direction);
2799                 break;
2800
2801         case SnapToBeat:
2802                 start = _session->tempo_map().round_to_beat (start, direction);
2803                 break;
2804
2805         case SnapToBeatDiv32:
2806                 start = _session->tempo_map().round_to_beat_subdivision (start, 32, direction);
2807                 break;
2808         case SnapToBeatDiv28:
2809                 start = _session->tempo_map().round_to_beat_subdivision (start, 28, direction);
2810                 break;
2811         case SnapToBeatDiv24:
2812                 start = _session->tempo_map().round_to_beat_subdivision (start, 24, direction);
2813                 break;
2814         case SnapToBeatDiv20:
2815                 start = _session->tempo_map().round_to_beat_subdivision (start, 20, direction);
2816                 break;
2817         case SnapToBeatDiv16:
2818                 start = _session->tempo_map().round_to_beat_subdivision (start, 16, direction);
2819                 break;
2820         case SnapToBeatDiv14:
2821                 start = _session->tempo_map().round_to_beat_subdivision (start, 14, direction);
2822                 break;
2823         case SnapToBeatDiv12:
2824                 start = _session->tempo_map().round_to_beat_subdivision (start, 12, direction);
2825                 break;
2826         case SnapToBeatDiv10:
2827                 start = _session->tempo_map().round_to_beat_subdivision (start, 10, direction);
2828                 break;
2829         case SnapToBeatDiv8:
2830                 start = _session->tempo_map().round_to_beat_subdivision (start, 8, direction);
2831                 break;
2832         case SnapToBeatDiv7:
2833                 start = _session->tempo_map().round_to_beat_subdivision (start, 7, direction);
2834                 break;
2835         case SnapToBeatDiv6:
2836                 start = _session->tempo_map().round_to_beat_subdivision (start, 6, direction);
2837                 break;
2838         case SnapToBeatDiv5:
2839                 start = _session->tempo_map().round_to_beat_subdivision (start, 5, direction);
2840                 break;
2841         case SnapToBeatDiv4:
2842                 start = _session->tempo_map().round_to_beat_subdivision (start, 4, direction);
2843                 break;
2844         case SnapToBeatDiv3:
2845                 start = _session->tempo_map().round_to_beat_subdivision (start, 3, direction);
2846                 break;
2847         case SnapToBeatDiv2:
2848                 start = _session->tempo_map().round_to_beat_subdivision (start, 2, direction);
2849                 break;
2850
2851         case SnapToMark:
2852                 if (for_mark) {
2853                         return;
2854                 }
2855
2856                 _session->locations()->marks_either_side (start, before, after);
2857
2858                 if (before == max_frames) {
2859                         start = after;
2860                 } else if (after == max_frames) {
2861                         start = before;
2862                 } else if (before != max_frames && after != max_frames) {
2863                         /* have before and after */
2864                         if ((start - before) < (after - start)) {
2865                                 start = before;
2866                         } else {
2867                                 start = after;
2868                         }
2869                 }
2870
2871                 break;
2872
2873         case SnapToRegionStart:
2874         case SnapToRegionEnd:
2875         case SnapToRegionSync:
2876         case SnapToRegionBoundary:
2877                 if (!region_boundary_cache.empty()) {
2878
2879                         vector<nframes64_t>::iterator prev = region_boundary_cache.end ();
2880                         vector<nframes64_t>::iterator next = region_boundary_cache.end ();
2881
2882                         if (direction > 0) {
2883                                 next = std::upper_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2884                         } else {
2885                                 next = std::lower_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2886                         }
2887
2888                         if (next != region_boundary_cache.begin ()) {
2889                                 prev = next;
2890                                 prev--;
2891                         }
2892
2893                         nframes64_t const p = (prev == region_boundary_cache.end()) ? region_boundary_cache.front () : *prev;
2894                         nframes64_t const n = (next == region_boundary_cache.end()) ? region_boundary_cache.back () : *next;
2895
2896                         if (start > (p + n) / 2) {
2897                                 start = n;
2898                         } else {
2899                                 start = p;
2900                         }
2901                 }
2902                 break;
2903         }
2904
2905         switch (_snap_mode) {
2906         case SnapNormal:
2907                 return;
2908
2909         case SnapMagnetic:
2910
2911                 if (presnap > start) {
2912                         if (presnap > (start + unit_to_frame(snap_threshold))) {
2913                                 start = presnap;
2914                         }
2915
2916                 } else if (presnap < start) {
2917                         if (presnap < (start - unit_to_frame(snap_threshold))) {
2918                                 start = presnap;
2919                         }
2920                 }
2921
2922         default:
2923                 /* handled at entry */
2924                 return;
2925
2926         }
2927 }
2928
2929
2930 void
2931 Editor::setup_toolbar ()
2932 {
2933         string pixmap_path;
2934
2935         /* Mode Buttons (tool selection) */
2936
2937         mouse_move_button.set_relief(Gtk::RELIEF_NONE);
2938         mouse_select_button.set_relief(Gtk::RELIEF_NONE);
2939         mouse_gain_button.set_relief(Gtk::RELIEF_NONE);
2940         mouse_zoom_button.set_relief(Gtk::RELIEF_NONE);
2941         mouse_timefx_button.set_relief(Gtk::RELIEF_NONE);
2942         mouse_audition_button.set_relief(Gtk::RELIEF_NONE);
2943         // internal_edit_button.set_relief(Gtk::RELIEF_NONE);
2944         join_object_range_button.set_relief(Gtk::RELIEF_NONE);
2945
2946         HBox* mode_box = manage(new HBox);
2947         mode_box->set_border_width (2);
2948         mode_box->set_spacing(4);
2949
2950         /* table containing mode buttons */
2951
2952         HBox* mouse_mode_button_box = manage (new HBox ());
2953
2954         if (Profile->get_sae()) {
2955                 mouse_mode_button_box->pack_start (mouse_move_button);
2956         } else {
2957                 mouse_mode_button_box->pack_start (mouse_move_button);
2958                 mouse_mode_button_box->pack_start (join_object_range_button);
2959                 mouse_mode_button_box->pack_start (mouse_select_button);
2960         }
2961
2962         mouse_mode_button_box->pack_start (mouse_zoom_button);
2963
2964         if (!Profile->get_sae()) {
2965                 mouse_mode_button_box->pack_start (mouse_gain_button);
2966         }
2967
2968         mouse_mode_button_box->pack_start (mouse_timefx_button);
2969         mouse_mode_button_box->pack_start (mouse_audition_button);
2970         mouse_mode_button_box->pack_start (internal_edit_button);
2971
2972         vector<string> edit_mode_strings;
2973         edit_mode_strings.push_back (edit_mode_to_string (Slide));
2974         if (!Profile->get_sae()) {
2975                 edit_mode_strings.push_back (edit_mode_to_string (Splice));
2976         }
2977         edit_mode_strings.push_back (edit_mode_to_string (Lock));
2978
2979         edit_mode_selector.set_name ("EditModeSelector");
2980         set_popdown_strings (edit_mode_selector, edit_mode_strings, true);
2981         edit_mode_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::edit_mode_selection_done));
2982
2983         mode_box->pack_start (edit_mode_selector);
2984         mode_box->pack_start (*mouse_mode_button_box);
2985
2986         _mouse_mode_tearoff = manage (new TearOff (*mode_box));
2987         _mouse_mode_tearoff->set_name ("MouseModeBase");
2988         _mouse_mode_tearoff->tearoff_window().signal_key_press_event().connect (sigc::bind (sigc::ptr_fun (relay_key_press), &_mouse_mode_tearoff->tearoff_window()), false);
2989
2990         if (Profile->get_sae()) {
2991                 _mouse_mode_tearoff->set_can_be_torn_off (false);
2992         }
2993
2994         _mouse_mode_tearoff->Detach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
2995                                                          &_mouse_mode_tearoff->tearoff_window()));
2996         _mouse_mode_tearoff->Attach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
2997                                                          &_mouse_mode_tearoff->tearoff_window(), 1));
2998         _mouse_mode_tearoff->Hidden.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
2999                                                          &_mouse_mode_tearoff->tearoff_window()));
3000         _mouse_mode_tearoff->Visible.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3001                                                           &_mouse_mode_tearoff->tearoff_window(), 1));
3002
3003         mouse_move_button.set_mode (false);
3004         mouse_select_button.set_mode (false);
3005         mouse_gain_button.set_mode (false);
3006         mouse_zoom_button.set_mode (false);
3007         mouse_timefx_button.set_mode (false);
3008         mouse_audition_button.set_mode (false);
3009         join_object_range_button.set_mode (false);
3010
3011         mouse_move_button.set_name ("MouseModeButton");
3012         mouse_select_button.set_name ("MouseModeButton");
3013         mouse_gain_button.set_name ("MouseModeButton");
3014         mouse_zoom_button.set_name ("MouseModeButton");
3015         mouse_timefx_button.set_name ("MouseModeButton");
3016         mouse_audition_button.set_name ("MouseModeButton");
3017         internal_edit_button.set_name ("MouseModeButton");
3018         join_object_range_button.set_name ("MouseModeButton");
3019
3020         mouse_move_button.unset_flags (CAN_FOCUS);
3021         mouse_select_button.unset_flags (CAN_FOCUS);
3022         mouse_gain_button.unset_flags (CAN_FOCUS);
3023         mouse_zoom_button.unset_flags (CAN_FOCUS);
3024         mouse_timefx_button.unset_flags (CAN_FOCUS);
3025         mouse_audition_button.unset_flags (CAN_FOCUS);
3026         internal_edit_button.unset_flags (CAN_FOCUS);
3027         join_object_range_button.unset_flags (CAN_FOCUS);
3028
3029         /* Zoom */
3030
3031         _zoom_box.set_spacing (1);
3032         _zoom_box.set_border_width (0);
3033
3034         zoom_in_button.set_name ("EditorTimeButton");
3035         zoom_in_button.set_image (*(manage (new Image (Stock::ZOOM_IN, Gtk::ICON_SIZE_MENU))));
3036         zoom_in_button.signal_clicked().connect (sigc::bind (sigc::mem_fun(*this, &Editor::temporal_zoom_step), false));
3037
3038         zoom_out_button.set_name ("EditorTimeButton");
3039         zoom_out_button.set_image (*(manage (new Image (Stock::ZOOM_OUT, Gtk::ICON_SIZE_MENU))));
3040         zoom_out_button.signal_clicked().connect (sigc::bind (sigc::mem_fun(*this, &Editor::temporal_zoom_step), true));
3041
3042         zoom_out_full_button.set_name ("EditorTimeButton");
3043         zoom_out_full_button.set_image (*(manage (new Image (Stock::ZOOM_100, Gtk::ICON_SIZE_MENU))));
3044         zoom_out_full_button.signal_clicked().connect (sigc::mem_fun(*this, &Editor::temporal_zoom_session));
3045
3046         zoom_focus_selector.set_name ("ZoomFocusSelector");
3047         set_popdown_strings (zoom_focus_selector, zoom_focus_strings, true);
3048         zoom_focus_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::zoom_focus_selection_done));
3049
3050         _zoom_box.pack_start (zoom_out_button, false, false);
3051         _zoom_box.pack_start (zoom_in_button, false, false);
3052         _zoom_box.pack_start (zoom_out_full_button, false, false);
3053
3054         _zoom_box.pack_start (zoom_focus_selector);
3055         
3056         /* Track zoom buttons */
3057         tav_expand_button.set_name ("TrackHeightButton");
3058         tav_expand_button.set_size_request(-1,20);
3059         tav_expand_button.add (*(manage (new Image (::get_icon("tav_exp")))));
3060         tav_expand_button.signal_clicked().connect (sigc::bind (sigc::mem_fun(*this, &Editor::tav_zoom_step), true));
3061
3062         tav_shrink_button.set_name ("TrackHeightButton");
3063         tav_shrink_button.set_size_request(-1,20);
3064         tav_shrink_button.add (*(manage (new Image (::get_icon("tav_shrink")))));
3065         tav_shrink_button.signal_clicked().connect (sigc::bind (sigc::mem_fun(*this, &Editor::tav_zoom_step), false));
3066
3067         _zoom_box.pack_start (tav_shrink_button);
3068         _zoom_box.pack_start (tav_expand_button);
3069         
3070         _zoom_tearoff = manage (new TearOff (_zoom_box));
3071
3072         _zoom_tearoff->Detach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
3073                                                    &_zoom_tearoff->tearoff_window()));
3074         _zoom_tearoff->Attach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3075                                                    &_zoom_tearoff->tearoff_window(), 0));
3076         _zoom_tearoff->Hidden.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
3077                                                    &_zoom_tearoff->tearoff_window()));
3078         _zoom_tearoff->Visible.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3079                                                     &_zoom_tearoff->tearoff_window(), 0));
3080         
3081         snap_box.set_spacing (1);
3082         snap_box.set_border_width (2);
3083
3084         snap_type_selector.set_name ("SnapTypeSelector");
3085         set_popdown_strings (snap_type_selector, snap_type_strings, true);
3086         snap_type_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::snap_type_selection_done));
3087
3088         snap_mode_selector.set_name ("SnapModeSelector");
3089         set_popdown_strings (snap_mode_selector, snap_mode_strings, true);
3090         snap_mode_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::snap_mode_selection_done));
3091
3092         edit_point_selector.set_name ("EditPointSelector");
3093         set_popdown_strings (edit_point_selector, edit_point_strings, true);
3094         edit_point_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::edit_point_selection_done));
3095
3096         snap_box.pack_start (snap_mode_selector, false, false);
3097         snap_box.pack_start (snap_type_selector, false, false);
3098         snap_box.pack_start (edit_point_selector, false, false);
3099
3100         /* Nudge */
3101
3102         HBox *nudge_box = manage (new HBox);
3103         nudge_box->set_spacing(1);
3104         nudge_box->set_border_width (2);
3105
3106         nudge_forward_button.signal_button_release_event().connect (sigc::mem_fun(*this, &Editor::nudge_forward_release), false);
3107         nudge_backward_button.signal_button_release_event().connect (sigc::mem_fun(*this, &Editor::nudge_backward_release), false);
3108
3109         nudge_box->pack_start (nudge_backward_button, false, false);
3110         nudge_box->pack_start (nudge_forward_button, false, false);
3111         nudge_box->pack_start (nudge_clock, false, false);
3112
3113
3114         /* Pack everything in... */
3115
3116         HBox* hbox = manage (new HBox);
3117         hbox->set_spacing(10);
3118
3119         _tools_tearoff = manage (new TearOff (*hbox));
3120         _tools_tearoff->set_name ("MouseModeBase");
3121         _tools_tearoff->tearoff_window().signal_key_press_event().connect (sigc::bind (sigc::ptr_fun (relay_key_press), &_tools_tearoff->tearoff_window()), false);
3122         
3123         if (Profile->get_sae()) {
3124                 _tools_tearoff->set_can_be_torn_off (false);
3125         }
3126
3127         _tools_tearoff->Detach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
3128                                                     &_tools_tearoff->tearoff_window()));
3129         _tools_tearoff->Attach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3130                                                     &_tools_tearoff->tearoff_window(), 0));
3131         _tools_tearoff->Hidden.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
3132                                                     &_tools_tearoff->tearoff_window()));
3133         _tools_tearoff->Visible.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3134                                                      &_tools_tearoff->tearoff_window(), 0));
3135
3136         toolbar_hbox.set_spacing (10);
3137         toolbar_hbox.set_border_width (1);
3138
3139         toolbar_hbox.pack_start (*_mouse_mode_tearoff, false, false);
3140         toolbar_hbox.pack_start (*_zoom_tearoff, false, false);
3141         toolbar_hbox.pack_start (*_tools_tearoff, false, false);
3142
3143         hbox->pack_start (snap_box, false, false);
3144         hbox->pack_start (*nudge_box, false, false);
3145         hbox->pack_start (panic_box, false, false);
3146
3147         hbox->show_all ();
3148
3149         toolbar_base.set_name ("ToolBarBase");
3150         toolbar_base.add (toolbar_hbox);
3151
3152         toolbar_frame.set_shadow_type (SHADOW_OUT);
3153         toolbar_frame.set_name ("BaseFrame");
3154         toolbar_frame.add (toolbar_base);
3155 }
3156
3157 void
3158 Editor::setup_tooltips ()
3159 {
3160         ARDOUR_UI::instance()->set_tip (mouse_move_button, _("Select/Move Objects"));
3161         ARDOUR_UI::instance()->set_tip (mouse_gain_button, _("Draw Gain Automation"));
3162         ARDOUR_UI::instance()->set_tip (mouse_zoom_button, _("Select Zoom Range"));
3163         ARDOUR_UI::instance()->set_tip (mouse_timefx_button, _("Stretch/Shrink Regions and MIDI Notes"));
3164         ARDOUR_UI::instance()->set_tip (mouse_audition_button, _("Listen to Specific Regions"));
3165         ARDOUR_UI::instance()->set_tip (join_object_range_button, _("Select/Move Objects or Ranges"));
3166         ARDOUR_UI::instance()->set_tip (internal_edit_button, _("Edit Region Contents (e.g. notes)"));
3167         ARDOUR_UI::instance()->set_tip (*_group_tabs, _("Groups: context-click for possible operations"));
3168         ARDOUR_UI::instance()->set_tip (nudge_forward_button, _("Nudge Region/Selection Forwards"));
3169         ARDOUR_UI::instance()->set_tip (nudge_backward_button, _("Nudge Region/Selection Backwards"));
3170         ARDOUR_UI::instance()->set_tip (zoom_in_button, _("Zoom In"));
3171         ARDOUR_UI::instance()->set_tip (zoom_out_button, _("Zoom Out"));
3172         ARDOUR_UI::instance()->set_tip (zoom_out_full_button, _("Zoom to Session"));
3173         ARDOUR_UI::instance()->set_tip (zoom_focus_selector, _("Zoom focus"));
3174         ARDOUR_UI::instance()->set_tip (tav_expand_button, _("Expand Tracks"));
3175         ARDOUR_UI::instance()->set_tip (tav_shrink_button, _("Shrink Tracks"));
3176         ARDOUR_UI::instance()->set_tip (snap_type_selector, _("Snap/Grid Units"));
3177         ARDOUR_UI::instance()->set_tip (snap_mode_selector, _("Snap/Grid Mode"));
3178         ARDOUR_UI::instance()->set_tip (edit_point_selector, _("Edit point"));
3179         ARDOUR_UI::instance()->set_tip (midi_sound_notes, _("Sound Notes"));
3180         ARDOUR_UI::instance()->set_tip (midi_panic_button, _("Send note off and reset controller messages on all MIDI channels"));
3181         ARDOUR_UI::instance()->set_tip (edit_mode_selector, _("Edit Mode"));
3182 }
3183
3184 void
3185 Editor::midi_panic ()
3186 {
3187         cerr << "MIDI panic\n";
3188
3189         if (_session) {
3190                 _session->midi_panic();
3191         }
3192 }
3193
3194 void
3195 Editor::setup_midi_toolbar ()
3196 {
3197         RefPtr<Action> act;
3198
3199         /* Midi sound notes */
3200         midi_sound_notes.add (*(manage (new Image (::get_icon("midi_sound_notes")))));
3201         midi_sound_notes.set_relief(Gtk::RELIEF_NONE);
3202         midi_sound_notes.unset_flags (CAN_FOCUS);
3203
3204         /* Panic */
3205
3206         act = ActionManager::get_action (X_("MIDI"), X_("panic"));
3207         midi_panic_button.set_name("MidiPanicButton");
3208         act->connect_proxy (midi_panic_button);
3209
3210         panic_box.pack_start (midi_sound_notes , true, true);
3211         panic_box.pack_start (midi_panic_button, true, true);
3212 }
3213
3214 int
3215 Editor::convert_drop_to_paths (
3216                 vector<ustring>&                paths,
3217                 const RefPtr<Gdk::DragContext>& /*context*/,
3218                 gint                            /*x*/,
3219                 gint                            /*y*/,
3220                 const SelectionData&            data,
3221                 guint                           /*info*/,
3222                 guint                           /*time*/)
3223 {
3224         if (_session == 0) {
3225                 return -1;
3226         }
3227
3228         vector<ustring> uris = data.get_uris();
3229
3230         if (uris.empty()) {
3231
3232                 /* This is seriously fucked up. Nautilus doesn't say that its URI lists
3233                    are actually URI lists. So do it by hand.
3234                 */
3235
3236                 if (data.get_target() != "text/plain") {
3237                         return -1;
3238                 }
3239
3240                 /* Parse the "uri-list" format that Nautilus provides,
3241                    where each pathname is delimited by \r\n.
3242
3243                    THERE MAY BE NO NULL TERMINATING CHAR!!!
3244                 */
3245
3246                 ustring txt = data.get_text();
3247                 const char* p;
3248                 const char* q;
3249
3250                 p = (const char *) malloc (txt.length() + 1);
3251                 txt.copy ((char *) p, txt.length(), 0);
3252                 ((char*)p)[txt.length()] = '\0';
3253
3254                 while (p)
3255                 {
3256                         if (*p != '#')
3257                         {
3258                                 while (g_ascii_isspace (*p))
3259                                         p++;
3260
3261                                 q = p;
3262                                 while (*q && (*q != '\n') && (*q != '\r')) {
3263                                         q++;
3264                                 }
3265
3266                                 if (q > p)
3267                                 {
3268                                         q--;
3269                                         while (q > p && g_ascii_isspace (*q))
3270                                                 q--;
3271
3272                                         if (q > p)
3273                                         {
3274                                                 uris.push_back (ustring (p, q - p + 1));
3275                                         }
3276                                 }
3277                         }
3278                         p = strchr (p, '\n');
3279                         if (p)
3280                                 p++;
3281                 }
3282
3283                 free ((void*)p);
3284
3285                 if (uris.empty()) {
3286                         return -1;
3287                 }
3288         }
3289
3290         for (vector<ustring>::iterator i = uris.begin(); i != uris.end(); ++i) {
3291
3292                 if ((*i).substr (0,7) == "file://") {
3293
3294                         ustring p = *i;
3295                         PBD::url_decode (p);
3296
3297                         // scan forward past three slashes
3298
3299                         ustring::size_type slashcnt = 0;
3300                         ustring::size_type n = 0;
3301                         ustring::iterator x = p.begin();
3302
3303                         while (slashcnt < 3 && x != p.end()) {
3304                                 if ((*x) == '/') {
3305                                         slashcnt++;
3306                                 } else if (slashcnt == 3) {
3307                                         break;
3308                                 }
3309                                 ++n;
3310                                 ++x;
3311                         }
3312
3313                         if (slashcnt != 3 || x == p.end()) {
3314                                 error << _("malformed URL passed to drag-n-drop code") << endmsg;
3315                                 continue;
3316                         }
3317
3318                         paths.push_back (p.substr (n - 1));
3319                 }
3320         }
3321
3322         return 0;
3323 }
3324
3325 void
3326 Editor::new_tempo_section ()
3327
3328 {
3329 }
3330
3331 void
3332 Editor::map_transport_state ()
3333 {
3334         ENSURE_GUI_THREAD (*this, &Editor::map_transport_state)
3335
3336         if (_session && _session->transport_stopped()) {
3337                 have_pending_keyboard_selection = false;
3338         }
3339
3340         update_loop_range_view (true);
3341 }
3342
3343 /* UNDO/REDO */
3344
3345 Editor::State::State (PublicEditor const * e)
3346 {
3347         selection = new Selection (e);
3348 }
3349
3350 Editor::State::~State ()
3351 {
3352         delete selection;
3353 }
3354
3355 void
3356 Editor::begin_reversible_command (string name)
3357 {
3358         if (_session) {
3359                 _session->begin_reversible_command (name);
3360         }
3361 }
3362
3363 void
3364 Editor::commit_reversible_command ()
3365 {
3366         if (_session) {
3367                 _session->commit_reversible_command ();
3368         }
3369 }
3370
3371 void
3372 Editor::set_route_group_solo (Route& route, bool yn)
3373 {
3374         RouteGroup *route_group;
3375
3376         if ((route_group = route.route_group()) != 0) {
3377                 route_group->apply (&Route::set_solo, yn, this);
3378         } else {
3379                 route.set_solo (yn, this);
3380         }
3381 }
3382
3383 void
3384 Editor::set_route_group_mute (Route& route, bool yn)
3385 {
3386         RouteGroup *route_group = 0;
3387
3388         if ((route_group = route.route_group()) != 0) {
3389                 route_group->apply (&Route::set_mute, yn, this);
3390         } else {
3391                 route.set_mute (yn, this);
3392         }
3393 }
3394
3395 void
3396 Editor::history_changed ()
3397 {
3398         string label;
3399
3400         if (undo_action && _session) {
3401                 if (_session->undo_depth() == 0) {
3402                         label = _("Undo");
3403                 } else {
3404                         label = string_compose(_("Undo (%1)"), _session->next_undo());
3405                 }
3406                 undo_action->property_label() = label;
3407         }
3408
3409         if (redo_action && _session) {
3410                 if (_session->redo_depth() == 0) {
3411                         label = _("Redo");
3412                 } else {
3413                         label = string_compose(_("Redo (%1)"), _session->next_redo());
3414                 }
3415                 redo_action->property_label() = label;
3416         }
3417 }
3418
3419 void
3420 Editor::duplicate_dialog (bool with_dialog)
3421 {
3422         float times = 1.0f;
3423
3424         if (mouse_mode == MouseRange) {
3425                 if (selection->time.length() == 0) {
3426                         return;
3427                 }
3428         }
3429
3430         RegionSelection rs;
3431         get_regions_for_action (rs);
3432
3433         if (mouse_mode != MouseRange) {
3434
3435                 if (rs.empty()) {
3436                         return;
3437                 }
3438         }
3439
3440         if (with_dialog) {
3441
3442                 ArdourDialog win (_("Duplicate"));
3443                 Label label (_("Number of duplications:"));
3444                 Adjustment adjustment (1.0, 1.0, 1000000.0, 1.0, 5.0);
3445                 SpinButton spinner (adjustment, 0.0, 1);
3446                 HBox hbox;
3447
3448                 win.get_vbox()->set_spacing (12);
3449                 win.get_vbox()->pack_start (hbox);
3450                 hbox.set_border_width (6);
3451                 hbox.pack_start (label, PACK_EXPAND_PADDING, 12);
3452
3453                 /* dialogs have ::add_action_widget() but that puts the spinner in the wrong
3454                    place, visually. so do this by hand.
3455                 */
3456
3457                 hbox.pack_start (spinner, PACK_EXPAND_PADDING, 12);
3458                 spinner.signal_activate().connect (sigc::bind (sigc::mem_fun (win, &ArdourDialog::response), RESPONSE_ACCEPT));
3459                 spinner.grab_focus();
3460
3461                 hbox.show ();
3462                 label.show ();
3463                 spinner.show ();
3464
3465                 win.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3466                 win.add_button (_("Duplicate"), RESPONSE_ACCEPT);
3467                 win.set_default_response (RESPONSE_ACCEPT);
3468
3469                 win.set_position (WIN_POS_MOUSE);
3470
3471                 spinner.grab_focus ();
3472
3473                 switch (win.run ()) {
3474                 case RESPONSE_ACCEPT:
3475                         break;
3476                 default:
3477                         return;
3478                 }
3479
3480                 times = adjustment.get_value();
3481         }
3482
3483         if (mouse_mode == MouseRange) {
3484                 duplicate_selection (times);
3485         } else {
3486                 duplicate_some_regions (rs, times);
3487         }
3488 }
3489
3490 void
3491 Editor::show_verbose_canvas_cursor ()
3492 {
3493         verbose_canvas_cursor->raise_to_top();
3494         verbose_canvas_cursor->show();
3495         verbose_cursor_visible = true;
3496 }
3497
3498 void
3499 Editor::hide_verbose_canvas_cursor ()
3500 {
3501         verbose_canvas_cursor->hide();
3502         verbose_cursor_visible = false;
3503 }
3504
3505 double
3506 Editor::clamp_verbose_cursor_x (double x)
3507 {
3508         if (x < 0) {
3509                 x = 0;
3510         } else {
3511                 x = min (_canvas_width - 200.0, x);
3512         }
3513         return x;
3514 }
3515
3516 double
3517 Editor::clamp_verbose_cursor_y (double y)
3518 {
3519         if (y < canvas_timebars_vsize) {
3520                 y = canvas_timebars_vsize;
3521         } else {
3522                 y = min (_canvas_height - 50, y);
3523         }
3524         return y;
3525 }
3526
3527 void
3528 Editor::show_verbose_canvas_cursor_with (const string & txt)
3529 {
3530         verbose_canvas_cursor->property_text() = txt.c_str();
3531
3532         int x, y;
3533         double wx, wy;
3534
3535         track_canvas->get_pointer (x, y);
3536         track_canvas->window_to_world (x, y, wx, wy);
3537
3538         /* don't get too close to the edge */
3539         verbose_canvas_cursor->property_x() = clamp_verbose_cursor_x (wx);
3540         verbose_canvas_cursor->property_y() = clamp_verbose_cursor_y (wy);
3541
3542         show_verbose_canvas_cursor ();
3543 }
3544
3545 void
3546 Editor::set_verbose_canvas_cursor (const string & txt, double x, double y)
3547 {
3548         verbose_canvas_cursor->property_text() = txt.c_str();
3549         /* don't get too close to the edge */
3550         verbose_canvas_cursor->property_x() = clamp_verbose_cursor_x (x);
3551         verbose_canvas_cursor->property_y() = clamp_verbose_cursor_y (y);
3552 }
3553
3554 void
3555 Editor::set_verbose_canvas_cursor_text (const string & txt)
3556 {
3557         verbose_canvas_cursor->property_text() = txt.c_str();
3558 }
3559
3560 void
3561 Editor::set_edit_mode (EditMode m)
3562 {
3563         Config->set_edit_mode (m);
3564 }
3565
3566 void
3567 Editor::cycle_edit_mode ()
3568 {
3569         switch (Config->get_edit_mode()) {
3570         case Slide:
3571                 if (Profile->get_sae()) {
3572                         Config->set_edit_mode (Lock);
3573                 } else {
3574                         Config->set_edit_mode (Splice);
3575                 }
3576                 break;
3577         case Splice:
3578                 Config->set_edit_mode (Lock);
3579                 break;
3580         case Lock:
3581                 Config->set_edit_mode (Slide);
3582                 break;
3583         }
3584 }
3585
3586 void
3587 Editor::edit_mode_selection_done ()
3588 {
3589         Config->set_edit_mode (string_to_edit_mode (edit_mode_selector.get_active_text ()));
3590 }
3591
3592 void
3593 Editor::snap_type_selection_done ()
3594 {
3595         string choice = snap_type_selector.get_active_text();
3596         SnapType snaptype = SnapToBeat;
3597
3598         if (choice == _("Beats/2")) {
3599                 snaptype = SnapToBeatDiv2;
3600         } else if (choice == _("Beats/3")) {
3601                 snaptype = SnapToBeatDiv3;
3602         } else if (choice == _("Beats/4")) {
3603                 snaptype = SnapToBeatDiv4;
3604         } else if (choice == _("Beats/5")) {
3605                 snaptype = SnapToBeatDiv5;
3606         } else if (choice == _("Beats/6")) {
3607                 snaptype = SnapToBeatDiv6;
3608         } else if (choice == _("Beats/7")) {
3609                 snaptype = SnapToBeatDiv7;
3610         } else if (choice == _("Beats/8")) {
3611                 snaptype = SnapToBeatDiv8;
3612         } else if (choice == _("Beats/10")) {
3613                 snaptype = SnapToBeatDiv10;
3614         } else if (choice == _("Beats/12")) {
3615                 snaptype = SnapToBeatDiv12;
3616         } else if (choice == _("Beats/14")) {
3617                 snaptype = SnapToBeatDiv14;
3618         } else if (choice == _("Beats/16")) {
3619                 snaptype = SnapToBeatDiv16;
3620         } else if (choice == _("Beats/20")) {
3621                 snaptype = SnapToBeatDiv20;
3622         } else if (choice == _("Beats/24")) {
3623                 snaptype = SnapToBeatDiv24;
3624         } else if (choice == _("Beats/28")) {
3625                 snaptype = SnapToBeatDiv28;
3626         } else if (choice == _("Beats/32")) {
3627                 snaptype = SnapToBeatDiv32;
3628         } else if (choice == _("Beats")) {
3629                 snaptype = SnapToBeat;
3630         } else if (choice == _("Bars")) {
3631                 snaptype = SnapToBar;
3632         } else if (choice == _("Marks")) {
3633                 snaptype = SnapToMark;
3634         } else if (choice == _("Region starts")) {
3635                 snaptype = SnapToRegionStart;
3636         } else if (choice == _("Region ends")) {
3637                 snaptype = SnapToRegionEnd;
3638         } else if (choice == _("Region bounds")) {
3639                 snaptype = SnapToRegionBoundary;
3640         } else if (choice == _("Region syncs")) {
3641                 snaptype = SnapToRegionSync;
3642         } else if (choice == _("CD Frames")) {
3643                 snaptype = SnapToCDFrame;
3644         } else if (choice == _("Timecode Frames")) {
3645                 snaptype = SnapToTimecodeFrame;
3646         } else if (choice == _("Timecode Seconds")) {
3647                 snaptype = SnapToTimecodeSeconds;
3648         } else if (choice == _("Timecode Minutes")) {
3649                 snaptype = SnapToTimecodeMinutes;
3650         } else if (choice == _("Seconds")) {
3651                 snaptype = SnapToSeconds;
3652         } else if (choice == _("Minutes")) {
3653                 snaptype = SnapToMinutes;
3654         }
3655
3656         RefPtr<RadioAction> ract = snap_type_action (snaptype);
3657         if (ract) {
3658                 ract->set_active ();
3659         }
3660 }
3661
3662 void
3663 Editor::snap_mode_selection_done ()
3664 {
3665         string choice = snap_mode_selector.get_active_text();
3666         SnapMode mode = SnapNormal;
3667
3668         if (choice == _("No Grid")) {
3669                 mode = SnapOff;
3670         } else if (choice == _("Grid")) {
3671                 mode = SnapNormal;
3672         } else if (choice == _("Magnetic")) {
3673                 mode = SnapMagnetic;
3674         }
3675
3676         RefPtr<RadioAction> ract = snap_mode_action (mode);
3677
3678         if (ract) {
3679                 ract->set_active (true);
3680         }
3681 }
3682
3683 void
3684 Editor::cycle_edit_point (bool with_marker)
3685 {
3686         switch (_edit_point) {
3687         case EditAtMouse:
3688                 set_edit_point_preference (EditAtPlayhead);
3689                 break;
3690         case EditAtPlayhead:
3691                 if (with_marker) {
3692                         set_edit_point_preference (EditAtSelectedMarker);
3693                 } else {
3694                         set_edit_point_preference (EditAtMouse);
3695                 }
3696                 break;
3697         case EditAtSelectedMarker:
3698                 set_edit_point_preference (EditAtMouse);
3699                 break;
3700         }
3701 }
3702
3703 void
3704 Editor::edit_point_selection_done ()
3705 {
3706         string choice = edit_point_selector.get_active_text();
3707         EditPoint ep = EditAtSelectedMarker;
3708
3709         if (choice == _("Marker")) {
3710                 set_edit_point_preference (EditAtSelectedMarker);
3711         } else if (choice == _("Playhead")) {
3712                 set_edit_point_preference (EditAtPlayhead);
3713         } else {
3714                 set_edit_point_preference (EditAtMouse);
3715         }
3716
3717         RefPtr<RadioAction> ract = edit_point_action (ep);
3718
3719         if (ract) {
3720                 ract->set_active (true);
3721         }
3722 }
3723
3724 void
3725 Editor::zoom_focus_selection_done ()
3726 {
3727         string choice = zoom_focus_selector.get_active_text();
3728         ZoomFocus focus_type = ZoomFocusLeft;
3729
3730         if (choice == _("Left")) {
3731                 focus_type = ZoomFocusLeft;
3732         } else if (choice == _("Right")) {
3733                 focus_type = ZoomFocusRight;
3734         } else if (choice == _("Center")) {
3735                 focus_type = ZoomFocusCenter;
3736         } else if (choice == _("Playhead")) {
3737                 focus_type = ZoomFocusPlayhead;
3738         } else if (choice == _("Mouse")) {
3739                 focus_type = ZoomFocusMouse;
3740         } else if (choice == _("Edit point")) {
3741                 focus_type = ZoomFocusEdit;
3742         }
3743
3744         RefPtr<RadioAction> ract = zoom_focus_action (focus_type);
3745
3746         if (ract) {
3747                 ract->set_active ();
3748         }
3749 }
3750
3751 gint
3752 Editor::edit_controls_button_release (GdkEventButton* ev)
3753 {
3754         if (Keyboard::is_context_menu_event (ev)) {
3755                 ARDOUR_UI::instance()->add_route (this);
3756         }
3757         return TRUE;
3758 }
3759
3760 gint
3761 Editor::mouse_select_button_release (GdkEventButton* ev)
3762 {
3763         /* this handles just right-clicks */
3764
3765         if (ev->button != 3) {
3766                 return false;
3767         }
3768
3769         return true;
3770 }
3771
3772 void
3773 Editor::set_zoom_focus (ZoomFocus f)
3774 {
3775         string str = zoom_focus_strings[(int)f];
3776
3777         if (str != zoom_focus_selector.get_active_text()) {
3778                 zoom_focus_selector.set_active_text (str);
3779         }
3780
3781         if (zoom_focus != f) {
3782                 zoom_focus = f;
3783
3784                 ZoomFocusChanged (); /* EMIT_SIGNAL */
3785
3786                 instant_save ();
3787         }
3788 }
3789
3790 void
3791 Editor::ensure_float (Window& win)
3792 {
3793         win.set_transient_for (*this);
3794 }
3795
3796 void
3797 Editor::pane_allocation_handler (Allocation &alloc, Paned* which)
3798 {
3799         /* recover or initialize pane positions. do this here rather than earlier because
3800            we don't want the positions to change the child allocations, which they seem to do.
3801          */
3802
3803         int pos;
3804         XMLProperty* prop;
3805         char buf[32];
3806         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
3807         int width, height;
3808
3809         enum Pane {
3810                 Horizontal = 0x1,
3811                 Vertical = 0x2
3812         };
3813
3814         static Pane done;
3815         
3816         XMLNode* geometry;
3817
3818         width = default_width;
3819         height = default_height;
3820
3821         if ((geometry = find_named_node (*node, "geometry")) != 0) {
3822
3823                 prop = geometry->property ("x-size");
3824                 if (prop) {
3825                         width = atoi (prop->value());
3826                 }
3827                 prop = geometry->property ("y-size");
3828                 if (prop) {
3829                         height = atoi (prop->value());
3830                 }
3831         }
3832
3833         if (which == static_cast<Paned*> (&edit_pane)) {
3834
3835                 if (done & Horizontal) {
3836                         return;
3837                 }
3838
3839                 if (!geometry || (prop = geometry->property ("edit-horizontal-pane-pos")) == 0) {
3840                         /* initial allocation is 90% to canvas, 10% to notebook */
3841                         pos = (int) floor (alloc.get_width() * 0.90f);
3842                         snprintf (buf, sizeof(buf), "%d", pos);
3843                 } else {
3844                         pos = atoi (prop->value());
3845                 }
3846
3847                 if (GTK_WIDGET(edit_pane.gobj())->allocation.width > pos) {
3848                         edit_pane.set_position (pos);
3849                         pre_maximal_horizontal_pane_position = pos;
3850                 }
3851
3852                 done = (Pane) (done | Horizontal);
3853                 
3854         } else if (which == static_cast<Paned*> (&editor_summary_pane)) {
3855
3856                 if (done & Vertical) {
3857                         return;
3858                 }
3859
3860                 if (!geometry || (prop = geometry->property ("edit-vertical-pane-pos")) == 0) {
3861                         /* initial allocation is 90% to canvas, 10% to summary */
3862                         pos = (int) floor (alloc.get_height() * 0.90f);
3863                         snprintf (buf, sizeof(buf), "%d", pos);
3864                 } else {
3865                         pos = atoi (prop->value());
3866                 }
3867
3868                 if (GTK_WIDGET(editor_summary_pane.gobj())->allocation.height > pos) {
3869                         editor_summary_pane.set_position (pos);
3870                         pre_maximal_vertical_pane_position = pos;
3871                 }
3872
3873                 done = (Pane) (done | Vertical);
3874         }
3875 }
3876
3877 void
3878 Editor::detach_tearoff (Box* /*b*/, Window* /*w*/)
3879 {
3880         if (_tools_tearoff->torn_off() && _mouse_mode_tearoff->torn_off()) {
3881                 top_hbox.remove (toolbar_frame);
3882         }
3883 }
3884
3885 void
3886 Editor::reattach_tearoff (Box* /*b*/, Window* /*w*/, int32_t /*n*/)
3887 {
3888         if (toolbar_frame.get_parent() == 0) {
3889                 top_hbox.pack_end (toolbar_frame);
3890         }
3891 }
3892
3893 void
3894 Editor::set_show_measures (bool yn)
3895 {
3896         if (_show_measures != yn) {
3897                 hide_measures ();
3898
3899                 if ((_show_measures = yn) == true) {
3900                         if (tempo_lines)
3901                                 tempo_lines->show();
3902                         draw_measures ();
3903                 }
3904                 instant_save ();
3905         }
3906 }
3907
3908 void
3909 Editor::toggle_follow_playhead ()
3910 {
3911         RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
3912         if (act) {
3913                 RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
3914                 set_follow_playhead (tact->get_active());
3915         }
3916 }
3917
3918 void
3919 Editor::set_follow_playhead (bool yn)
3920 {
3921         if (_follow_playhead != yn) {
3922                 if ((_follow_playhead = yn) == true) {
3923                         /* catch up */
3924                         reset_x_origin_to_follow_playhead ();
3925                 }
3926                 instant_save ();
3927         }
3928 }
3929
3930 void
3931 Editor::toggle_stationary_playhead ()
3932 {
3933        RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-stationary-playhead"));
3934        if (act) {
3935                RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
3936                set_stationary_playhead (tact->get_active());
3937        }
3938 }
3939
3940 void
3941 Editor::set_stationary_playhead (bool yn)
3942 {
3943        if (_stationary_playhead != yn) {
3944                if ((_stationary_playhead = yn) == true) {
3945                        /* catch up */
3946                        // FIXME need a 3.0 equivalent of this 2.X call
3947                        // update_current_screen ();
3948                }
3949                instant_save ();
3950        }
3951 }
3952
3953 void
3954 Editor::toggle_xfade_active (boost::weak_ptr<Crossfade> wxfade)
3955 {
3956         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3957         if (xfade) {
3958                 xfade->set_active (!xfade->active());
3959         }
3960 }
3961
3962 void
3963 Editor::toggle_xfade_length (boost::weak_ptr<Crossfade> wxfade)
3964 {
3965         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3966         if (xfade) {
3967                 xfade->set_follow_overlap (!xfade->following_overlap());
3968         }
3969 }
3970
3971 void
3972 Editor::edit_xfade (boost::weak_ptr<Crossfade> wxfade)
3973 {
3974         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3975
3976         if (!xfade) {
3977                 return;
3978         }
3979
3980         CrossfadeEditor cew (_session, xfade, xfade->fade_in().get_min_y(), 1.0);
3981
3982         ensure_float (cew);
3983
3984         switch (cew.run ()) {
3985         case RESPONSE_ACCEPT:
3986                 break;
3987         default:
3988                 return;
3989         }
3990
3991         cew.apply ();
3992         PropertyChange all_crossfade_properties;
3993         all_crossfade_properties.add (ARDOUR::Properties::active);
3994         all_crossfade_properties.add (ARDOUR::Properties::follow_overlap);
3995         xfade->PropertyChanged (all_crossfade_properties);
3996 }
3997
3998 PlaylistSelector&
3999 Editor::playlist_selector () const
4000 {
4001         return *_playlist_selector;
4002 }
4003
4004 Evoral::MusicalTime
4005 Editor::get_grid_type_as_beats (bool& success, nframes64_t position)
4006 {
4007         success = true;
4008
4009         switch (_snap_type) {
4010         case SnapToBeat:
4011                 return 1.0;
4012                 break;
4013
4014         case SnapToBeatDiv32:
4015                 return 1.0/32.0;
4016                 break;
4017         case SnapToBeatDiv28:
4018                 return 1.0/28.0;
4019                 break;
4020         case SnapToBeatDiv24:
4021                 return 1.0/24.0;
4022                 break;
4023         case SnapToBeatDiv20:
4024                 return 1.0/20.0;
4025                 break;
4026         case SnapToBeatDiv16:
4027                 return 1.0/16.0;
4028                 break;
4029         case SnapToBeatDiv14:
4030                 return 1.0/14.0;
4031                 break;
4032         case SnapToBeatDiv12:
4033                 return 1.0/12.0;
4034                 break;
4035         case SnapToBeatDiv10:
4036                 return 1.0/10.0;
4037                 break;
4038         case SnapToBeatDiv8:
4039                 return 1.0/8.0;
4040                 break;
4041         case SnapToBeatDiv7:
4042                 return 1.0/7.0;
4043                 break;
4044         case SnapToBeatDiv6:
4045                 return 1.0/6.0;
4046                 break;
4047         case SnapToBeatDiv5:
4048                 return 1.0/5.0;
4049                 break;
4050         case SnapToBeatDiv4:
4051                 return 1.0/4.0;
4052                 break;
4053         case SnapToBeatDiv3:
4054                 return 1.0/3.0;
4055                 break;
4056         case SnapToBeatDiv2:
4057                 return 1.0/2.0;
4058                 break;
4059
4060         case SnapToBar:
4061                 if (_session) {
4062                         return _session->tempo_map().meter_at (position).beats_per_bar();
4063                 }
4064                 break;
4065
4066         case SnapToCDFrame:
4067         case SnapToTimecodeFrame:
4068         case SnapToTimecodeSeconds:
4069         case SnapToTimecodeMinutes:
4070         case SnapToSeconds:
4071         case SnapToMinutes:
4072         case SnapToRegionStart:
4073         case SnapToRegionEnd:
4074         case SnapToRegionSync:
4075         case SnapToRegionBoundary:
4076         default:
4077                 success = false;
4078                 break;
4079         }
4080
4081         return 0.0;
4082 }
4083
4084 nframes64_t
4085 Editor::get_nudge_distance (nframes64_t pos, nframes64_t& next)
4086 {
4087         nframes64_t ret;
4088
4089         ret = nudge_clock.current_duration (pos);
4090         next = ret + 1; /* XXXX fix me */
4091
4092         return ret;
4093 }
4094
4095 int
4096 Editor::playlist_deletion_dialog (boost::shared_ptr<Playlist> pl)
4097 {
4098         ArdourDialog dialog (_("Playlist Deletion"));
4099         Label  label (string_compose (_("Playlist %1 is currently unused.\n"
4100                                         "If left alone, no audio files used by it will be cleaned.\n"
4101                                         "If deleted, audio files used by it alone by will cleaned."),
4102                                       pl->name()));
4103
4104         dialog.set_position (WIN_POS_CENTER);
4105         dialog.get_vbox()->pack_start (label);
4106
4107         label.show ();
4108
4109         dialog.add_button (_("Delete playlist"), RESPONSE_ACCEPT);
4110         dialog.add_button (_("Keep playlist"), RESPONSE_REJECT);
4111         dialog.add_button (_("Cancel"), RESPONSE_CANCEL);
4112
4113         switch (dialog.run ()) {
4114         case RESPONSE_ACCEPT:
4115                 /* delete the playlist */
4116                 return 0;
4117                 break;
4118
4119         case RESPONSE_REJECT:
4120                 /* keep the playlist */
4121                 return 1;
4122                 break;
4123
4124         default:
4125                 break;
4126         }
4127
4128         return -1;
4129 }
4130
4131 bool
4132 Editor::audio_region_selection_covers (nframes64_t where)
4133 {
4134         for (RegionSelection::iterator a = selection->regions.begin(); a != selection->regions.end(); ++a) {
4135                 if ((*a)->region()->covers (where)) {
4136                         return true;
4137                 }
4138         }
4139
4140         return false;
4141 }
4142
4143 void
4144 Editor::prepare_for_cleanup ()
4145 {
4146         cut_buffer->clear_regions ();
4147         cut_buffer->clear_playlists ();
4148
4149         selection->clear_regions ();
4150         selection->clear_playlists ();
4151
4152         _regions->suspend_redisplay ();
4153 }
4154
4155 void
4156 Editor::finish_cleanup ()
4157 {
4158         _regions->resume_redisplay ();
4159 }
4160
4161 Location*
4162 Editor::transport_loop_location()
4163 {
4164         if (_session) {
4165                 return _session->locations()->auto_loop_location();
4166         } else {
4167                 return 0;
4168         }
4169 }
4170
4171 Location*
4172 Editor::transport_punch_location()
4173 {
4174         if (_session) {
4175                 return _session->locations()->auto_punch_location();
4176         } else {
4177                 return 0;
4178         }
4179 }
4180
4181 bool
4182 Editor::control_layout_scroll (GdkEventScroll* ev)
4183 {
4184         if (Keyboard::some_magic_widget_has_focus()) {
4185                 return false;
4186         }
4187
4188         switch (ev->direction) {
4189         case GDK_SCROLL_UP:
4190                 scroll_tracks_up_line ();
4191                 return true;
4192                 break;
4193
4194         case GDK_SCROLL_DOWN:
4195                 scroll_tracks_down_line ();
4196                 return true;
4197
4198         default:
4199                 /* no left/right handling yet */
4200                 break;
4201         }
4202
4203         return false;
4204 }
4205
4206 void
4207 Editor::session_state_saved (string snap_name)
4208 {
4209         ENSURE_GUI_THREAD (*this, &Editor::session_state_saved, snap_name);
4210         
4211         update_title ();        
4212         _snapshots->redisplay ();
4213 }
4214
4215 void
4216 Editor::maximise_editing_space ()
4217 {
4218         _mouse_mode_tearoff->set_visible (false);
4219         _tools_tearoff->set_visible (false);
4220         _zoom_tearoff->set_visible (false);
4221
4222         pre_maximal_horizontal_pane_position = edit_pane.get_position ();
4223         pre_maximal_vertical_pane_position = editor_summary_pane.get_position ();
4224         pre_maximal_editor_width = this->get_width ();
4225         pre_maximal_editor_height = this->get_height ();
4226
4227         if (post_maximal_horizontal_pane_position == 0) {
4228                 post_maximal_horizontal_pane_position = edit_pane.get_width();
4229         }
4230
4231         if (post_maximal_vertical_pane_position == 0) {
4232                 post_maximal_vertical_pane_position = editor_summary_pane.get_height();
4233         }
4234         
4235         fullscreen ();
4236
4237         if (post_maximal_editor_width) {
4238                 edit_pane.set_position (post_maximal_horizontal_pane_position -
4239                         abs(post_maximal_editor_width - pre_maximal_editor_width));
4240         } else {
4241                 edit_pane.set_position (post_maximal_horizontal_pane_position);
4242         }
4243
4244         if (post_maximal_editor_height) {
4245                 editor_summary_pane.set_position (post_maximal_vertical_pane_position -
4246                         abs(post_maximal_editor_height - pre_maximal_editor_height));
4247         } else {
4248                 editor_summary_pane.set_position (post_maximal_vertical_pane_position);
4249         }
4250
4251         if (Config->get_keep_tearoffs()) {
4252                 _mouse_mode_tearoff->set_visible (true);
4253                 _tools_tearoff->set_visible (true);
4254                 _zoom_tearoff->set_visible (true);
4255         }
4256 }
4257
4258 void
4259 Editor::restore_editing_space ()
4260 {
4261         // user changed width/height of panes during fullscreen
4262
4263         if (post_maximal_horizontal_pane_position != edit_pane.get_position()) {
4264                 post_maximal_horizontal_pane_position = edit_pane.get_position();
4265         }
4266
4267         if (post_maximal_vertical_pane_position != editor_summary_pane.get_position()) {
4268                 post_maximal_vertical_pane_position = editor_summary_pane.get_position();
4269         }
4270         
4271         unfullscreen();
4272
4273         _mouse_mode_tearoff->set_visible (true);
4274         _tools_tearoff->set_visible (true);
4275         _zoom_tearoff->set_visible (true);
4276         post_maximal_editor_width = this->get_width();
4277         post_maximal_editor_height = this->get_height();
4278
4279         edit_pane.set_position (pre_maximal_horizontal_pane_position + abs(this->get_width() - pre_maximal_editor_width));
4280         editor_summary_pane.set_position (pre_maximal_vertical_pane_position + abs(this->get_height() - pre_maximal_editor_height));
4281 }
4282
4283 /**
4284  *  Make new playlists for a given track and also any others that belong
4285  *  to the same active route group with the `edit' property.
4286  *  @param v Track.
4287  */
4288
4289 void
4290 Editor::new_playlists (TimeAxisView* v)
4291 {
4292         begin_reversible_command (_("new playlists"));
4293         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4294         _session->playlists->get (playlists);
4295         mapover_tracks (sigc::bind (sigc::mem_fun (*this, &Editor::mapped_use_new_playlist), playlists), v, ARDOUR::Properties::edit.property_id);
4296         commit_reversible_command ();
4297 }
4298
4299 /**
4300  *  Use a copy of the current playlist for a given track and also any others that belong
4301  *  to the same active route group with the `edit' property.
4302  *  @param v Track.
4303  */
4304
4305 void
4306 Editor::copy_playlists (TimeAxisView* v)
4307 {
4308         begin_reversible_command (_("copy playlists"));
4309         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4310         _session->playlists->get (playlists);
4311         mapover_tracks (sigc::bind (sigc::mem_fun (*this, &Editor::mapped_use_copy_playlist), playlists), v, ARDOUR::Properties::edit.property_id);
4312         commit_reversible_command ();
4313 }
4314
4315 /** Clear the current playlist for a given track and also any others that belong
4316  *  to the same active route group with the `edit' property.
4317  *  @param v Track.
4318  */
4319
4320 void
4321 Editor::clear_playlists (TimeAxisView* v)
4322 {
4323         begin_reversible_command (_("clear playlists"));
4324         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4325         _session->playlists->get (playlists);
4326         mapover_tracks (sigc::mem_fun (*this, &Editor::mapped_clear_playlist), v, ARDOUR::Properties::edit.property_id);
4327         commit_reversible_command ();
4328 }
4329
4330 void
4331 Editor::mapped_use_new_playlist (RouteTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4332 {
4333         atv.use_new_playlist (sz > 1 ? false : true, playlists);
4334 }
4335
4336 void
4337 Editor::mapped_use_copy_playlist (RouteTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4338 {
4339         atv.use_copy_playlist (sz > 1 ? false : true, playlists);
4340 }
4341
4342 void
4343 Editor::mapped_clear_playlist (RouteTimeAxisView& atv, uint32_t /*sz*/)
4344 {
4345         atv.clear_playlist ();
4346 }
4347
4348 bool
4349 Editor::on_key_press_event (GdkEventKey* ev)
4350 {
4351         return key_press_focus_accelerator_handler (*this, ev);
4352 }
4353
4354 bool
4355 Editor::on_key_release_event (GdkEventKey* ev)
4356 {
4357         return Gtk::Window::on_key_release_event (ev);
4358         // return key_press_focus_accelerator_handler (*this, ev);
4359 }
4360
4361 /** Queue up a change to the viewport x origin.
4362  *  @param frame New x origin.
4363  */
4364 void
4365 Editor::reset_x_origin (nframes64_t frame)
4366 {
4367         queue_visual_change (frame);
4368 }
4369
4370 void
4371 Editor::reset_y_origin (double y)
4372 {
4373         queue_visual_change_y (y);
4374 }
4375
4376 void
4377 Editor::reset_zoom (double fpu)
4378 {
4379         queue_visual_change (fpu);
4380 }
4381
4382 void
4383 Editor::reposition_and_zoom (nframes64_t frame, double fpu)
4384 {
4385         reset_x_origin (frame);
4386         reset_zoom (fpu);
4387
4388         if (!no_save_visual) {
4389                 undo_visual_stack.push_back (current_visual_state(false));
4390         }
4391 }
4392
4393 Editor::VisualState*
4394 Editor::current_visual_state (bool with_tracks)
4395 {
4396         VisualState* vs = new VisualState;
4397         vs->y_position = vertical_adjustment.get_value();
4398         vs->frames_per_unit = frames_per_unit;
4399         vs->leftmost_frame = leftmost_frame;
4400         vs->zoom_focus = zoom_focus;
4401
4402         if (with_tracks) {
4403                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4404                         vs->track_states.push_back (TAVState ((*i), &(*i)->get_state()));
4405                 }
4406         }
4407
4408         return vs;
4409 }
4410
4411 void
4412 Editor::undo_visual_state ()
4413 {
4414         if (undo_visual_stack.empty()) {
4415                 return;
4416         }
4417
4418         redo_visual_stack.push_back (current_visual_state());
4419
4420         VisualState* vs = undo_visual_stack.back();
4421         undo_visual_stack.pop_back();
4422         use_visual_state (*vs);
4423 }
4424
4425 void
4426 Editor::redo_visual_state ()
4427 {
4428         if (redo_visual_stack.empty()) {
4429                 return;
4430         }
4431
4432         undo_visual_stack.push_back (current_visual_state());
4433
4434         VisualState* vs = redo_visual_stack.back();
4435         redo_visual_stack.pop_back();
4436         use_visual_state (*vs);
4437 }
4438
4439 void
4440 Editor::swap_visual_state ()
4441 {
4442         if (undo_visual_stack.empty()) {
4443                 redo_visual_state ();
4444         } else {
4445                 undo_visual_state ();
4446         }
4447 }
4448
4449 void
4450 Editor::use_visual_state (VisualState& vs)
4451 {
4452         no_save_visual = true;
4453
4454         _routes->suspend_redisplay ();
4455
4456         vertical_adjustment.set_value (vs.y_position);
4457
4458         set_zoom_focus (vs.zoom_focus);
4459         reposition_and_zoom (vs.leftmost_frame, vs.frames_per_unit);
4460
4461         for (list<TAVState>::iterator i = vs.track_states.begin(); i != vs.track_states.end(); ++i) {
4462                 TrackViewList::iterator t;
4463
4464                 /* check if the track still exists - it could have been deleted */
4465
4466                 if ((t = find (track_views.begin(), track_views.end(), i->first)) != track_views.end()) {
4467                         (*t)->set_state (*(i->second), Stateful::loading_state_version);
4468                 }
4469         }
4470
4471
4472         if (!vs.track_states.empty()) {
4473                 _routes->update_visibility ();
4474         }
4475
4476         _routes->resume_redisplay ();
4477
4478         no_save_visual = false;
4479 }
4480
4481 void
4482 Editor::set_frames_per_unit (double fpu)
4483 {
4484         /* this is the core function that controls the zoom level of the canvas. it is called
4485            whenever one or more calls are made to reset_zoom(). it executes in an idle handler.
4486         */
4487
4488         if (fpu == frames_per_unit) {
4489                 return;
4490         }
4491
4492         if (fpu < 2.0) {
4493                 fpu = 2.0;
4494         }
4495
4496
4497         /* don't allow zooms that fit more than the maximum number
4498            of frames into an 800 pixel wide space.
4499         */
4500
4501         if (max_frames / fpu < 800.0) {
4502                 return;
4503         }
4504
4505         if (tempo_lines)
4506                 tempo_lines->tempo_map_changed();
4507
4508         frames_per_unit = fpu;
4509         post_zoom ();
4510 }
4511
4512 void
4513 Editor::post_zoom ()
4514 {
4515         // convert fpu to frame count
4516
4517         nframes64_t frames = (nframes64_t) floor (frames_per_unit * _canvas_width);
4518
4519         if (frames_per_unit != zoom_range_clock.current_duration()) {
4520                 zoom_range_clock.set (frames);
4521         }
4522
4523         if (mouse_mode == MouseRange && selection->time.start () != selection->time.end_frame ()) {
4524                 for (TrackViewList::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4525                         (*i)->reshow_selection (selection->time);
4526                 }
4527         }
4528
4529         ZoomChanged (); /* EMIT_SIGNAL */
4530
4531         //reset_scrolling_region ();
4532
4533         if (playhead_cursor) {
4534                 playhead_cursor->set_position (playhead_cursor->current_frame);
4535         }
4536
4537         refresh_location_display();
4538         _summary->set_overlays_dirty ();
4539
4540         instant_save ();
4541 }
4542
4543 void
4544 Editor::queue_visual_change (nframes64_t where)
4545 {
4546         pending_visual_change.add (VisualChange::TimeOrigin);
4547         pending_visual_change.time_origin = where;
4548         ensure_visual_change_idle_handler ();
4549 }
4550
4551 void
4552 Editor::queue_visual_change (double fpu)
4553 {
4554         pending_visual_change.add (VisualChange::ZoomLevel);
4555         pending_visual_change.frames_per_unit = fpu;
4556
4557         ensure_visual_change_idle_handler ();
4558 }
4559
4560 void
4561 Editor::queue_visual_change_y (double y)
4562 {
4563         pending_visual_change.add (VisualChange::YOrigin);
4564         pending_visual_change.y_origin = y;
4565
4566         ensure_visual_change_idle_handler ();
4567 }
4568
4569 void
4570 Editor::ensure_visual_change_idle_handler ()
4571 {
4572         if (pending_visual_change.idle_handler_id < 0) {
4573                 pending_visual_change.idle_handler_id = g_idle_add (_idle_visual_changer, this);
4574         }
4575 }
4576
4577 int
4578 Editor::_idle_visual_changer (void* arg)
4579 {
4580         return static_cast<Editor*>(arg)->idle_visual_changer ();
4581 }
4582
4583 int
4584 Editor::idle_visual_changer ()
4585 {
4586         VisualChange::Type p = pending_visual_change.pending;
4587         pending_visual_change.pending = (VisualChange::Type) 0;
4588
4589         double last_time_origin = horizontal_position ();
4590
4591         if (p & VisualChange::ZoomLevel) {
4592                 set_frames_per_unit (pending_visual_change.frames_per_unit);
4593
4594                 compute_fixed_ruler_scale ();
4595                 compute_current_bbt_points(pending_visual_change.time_origin, pending_visual_change.time_origin + current_page_frames());
4596                 compute_bbt_ruler_scale (pending_visual_change.time_origin, pending_visual_change.time_origin + current_page_frames());
4597                 update_tempo_based_rulers ();
4598         }
4599         if (p & VisualChange::TimeOrigin) {
4600                 set_horizontal_position (pending_visual_change.time_origin / frames_per_unit);
4601         }
4602         if (p & VisualChange::YOrigin) {
4603                 vertical_adjustment.set_value (pending_visual_change.y_origin);
4604         }
4605
4606         if (last_time_origin == horizontal_position ()) {
4607                 /* changed signal not emitted */
4608                 update_fixed_rulers ();
4609                 redisplay_tempo (true);
4610         }
4611
4612         _summary->set_overlays_dirty ();
4613
4614         pending_visual_change.idle_handler_id = -1;
4615         return 0; /* this is always a one-shot call */
4616 }
4617
4618 struct EditorOrderTimeAxisSorter {
4619     bool operator() (const TimeAxisView* a, const TimeAxisView* b) const {
4620             return a->order () < b->order ();
4621     }
4622 };
4623
4624 void
4625 Editor::sort_track_selection (TrackViewList* sel)
4626 {
4627         EditorOrderTimeAxisSorter cmp;
4628
4629         if (sel) {
4630                 sel->sort (cmp);
4631         } else {
4632                 selection->tracks.sort (cmp);
4633         }
4634 }
4635
4636 nframes64_t
4637 Editor::get_preferred_edit_position (bool ignore_playhead)
4638 {
4639         bool ignored;
4640         nframes64_t where = 0;
4641         EditPoint ep = _edit_point;
4642
4643         if (entered_marker) {
4644                 return entered_marker->position();
4645         }
4646
4647         if (ignore_playhead && ep == EditAtPlayhead) {
4648                 ep = EditAtSelectedMarker;
4649         }
4650
4651         switch (ep) {
4652         case EditAtPlayhead:
4653                 where = _session->audible_frame();
4654                 break;
4655
4656         case EditAtSelectedMarker:
4657                 if (!selection->markers.empty()) {
4658                         bool is_start;
4659                         Location* loc = find_location_from_marker (selection->markers.front(), is_start);
4660                         if (loc) {
4661                                 if (is_start) {
4662                                         where =  loc->start();
4663                                 } else {
4664                                         where = loc->end();
4665                                 }
4666                                 break;
4667                         }
4668                 }
4669                 /* fallthru */
4670
4671         default:
4672         case EditAtMouse:
4673                 if (!mouse_frame (where, ignored)) {
4674                         /* XXX not right but what can we do ? */
4675                         return 0;
4676                 }
4677                 snap_to (where);
4678                 break;
4679         }
4680
4681         return where;
4682 }
4683
4684 void
4685 Editor::set_loop_range (nframes64_t start, nframes64_t end, string cmd)
4686 {
4687         if (!_session) return;
4688
4689         begin_reversible_command (cmd);
4690
4691         Location* tll;
4692
4693         if ((tll = transport_loop_location()) == 0) {
4694                 Location* loc = new Location (*_session, start, end, _("Loop"),  Location::IsAutoLoop);
4695                 XMLNode &before = _session->locations()->get_state();
4696                 _session->locations()->add (loc, true);
4697                 _session->set_auto_loop_location (loc);
4698                 XMLNode &after = _session->locations()->get_state();
4699                 _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
4700         } else {
4701                 XMLNode &before = tll->get_state();
4702                 tll->set_hidden (false, this);
4703                 tll->set (start, end);
4704                 XMLNode &after = tll->get_state();
4705                 _session->add_command (new MementoCommand<Location>(*tll, &before, &after));
4706         }
4707
4708         commit_reversible_command ();
4709 }
4710
4711 void
4712 Editor::set_punch_range (nframes64_t start, nframes64_t end, string cmd)
4713 {
4714         if (!_session) return;
4715
4716         begin_reversible_command (cmd);
4717
4718         Location* tpl;
4719
4720         if ((tpl = transport_punch_location()) == 0) {
4721                 Location* loc = new Location (*_session, start, end, _("Loop"),  Location::IsAutoPunch);
4722                 XMLNode &before = _session->locations()->get_state();
4723                 _session->locations()->add (loc, true);
4724                 _session->set_auto_loop_location (loc);
4725                 XMLNode &after = _session->locations()->get_state();
4726                 _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
4727         }
4728         else {
4729                 XMLNode &before = tpl->get_state();
4730                 tpl->set_hidden (false, this);
4731                 tpl->set (start, end);
4732                 XMLNode &after = tpl->get_state();
4733                 _session->add_command (new MementoCommand<Location>(*tpl, &before, &after));
4734         }
4735
4736         commit_reversible_command ();
4737 }
4738
4739 /** Find regions which exist at a given time, and optionally on a given list of tracks.
4740  *  @param rs List to which found regions are added.
4741  *  @param where Time to look at.
4742  *  @param ts Tracks to look on; if this is empty, all tracks are examined.
4743  */
4744 void
4745 Editor::get_regions_at (RegionSelection& rs, nframes64_t where, const TrackViewList& ts) const
4746 {
4747         const TrackViewList* tracks;
4748
4749         if (ts.empty()) {
4750                 tracks = &track_views;
4751         } else {
4752                 tracks = &ts;
4753         }
4754
4755         for (TrackViewList::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
4756                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*t);
4757                 if (rtv) {
4758                         boost::shared_ptr<Track> tr;
4759                         boost::shared_ptr<Playlist> pl;
4760
4761                         if ((tr = rtv->track()) && ((pl = tr->playlist()))) {
4762
4763                                 Playlist::RegionList* regions = pl->regions_at (
4764                                                 (nframes64_t) floor ( (double)where * tr->speed()));
4765
4766                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
4767                                         RegionView* rv = rtv->view()->find_view (*i);
4768                                         if (rv) {
4769                                                 rs.add (rv);
4770                                         }
4771                                 }
4772
4773                                 delete regions;
4774                         }
4775                 }
4776         }
4777 }
4778
4779 void
4780 Editor::get_regions_after (RegionSelection& rs, nframes64_t where, const TrackViewList& ts) const
4781 {
4782         const TrackViewList* tracks;
4783
4784         if (ts.empty()) {
4785                 tracks = &track_views;
4786         } else {
4787                 tracks = &ts;
4788         }
4789
4790         for (TrackViewList::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
4791                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*t);
4792                 if (rtv) {
4793                         boost::shared_ptr<Track> tr;
4794                         boost::shared_ptr<Playlist> pl;
4795
4796                         if ((tr = rtv->track()) && ((pl = tr->playlist()))) {
4797
4798                                 Playlist::RegionList* regions = pl->regions_touched (
4799                                                 (nframes64_t) floor ( (double)where * tr->speed()), max_frames);
4800
4801                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
4802
4803                                         RegionView* rv = rtv->view()->find_view (*i);
4804
4805                                         if (rv) {
4806                                                 rs.push_back (rv);
4807                                         }
4808                                 }
4809
4810                                 delete regions;
4811                         }
4812                 }
4813         }
4814 }
4815
4816 /** Find all regions which are either:
4817  *      - selected or
4818  *      - the entered_regionview (if allow_entered == true) or
4819  *      - under the preferred edit position AND on a selected track, or on a track
4820  *        which is in the same active edit-enable route group as a selected region (if allow_edit_position == true)
4821  *  @param rs Returned region list.
4822  *  @param allow_entered true to include the entered_regionview in the list.
4823  */
4824 void
4825 Editor::get_regions_for_action (RegionSelection& rs, bool allow_entered, bool allow_edit_position)
4826 {
4827         /* Start with selected regions */
4828         rs = selection->regions;
4829
4830         /* Add the entered_regionview, if requested */
4831         if (allow_entered && entered_regionview) {
4832                 rs.add (entered_regionview);
4833         }
4834
4835         if (allow_edit_position) {
4836
4837                 TrackViewList tracks = selection->tracks;
4838
4839                 /* tracks is currently the set of selected tracks; add any other tracks that
4840                  * have regions that are in the same edit-activated route group as one of
4841                  * our regions */
4842                 for (RegionSelection::iterator i = rs.begin (); i != rs.end(); ++i) {
4843
4844                         RouteGroup* g = (*i)->get_time_axis_view().route_group ();
4845                         if (g && g->is_active() && g->is_edit()) {
4846                                 tracks.add (axis_views_from_routes (g->route_list()));
4847                         }
4848                         
4849                 }
4850
4851                 if (!tracks.empty()) {
4852                         /* now find regions that are at the edit position on those tracks */
4853                         nframes64_t const where = get_preferred_edit_position ();
4854                         get_regions_at (rs, where, tracks);
4855                 }
4856         }
4857 }
4858
4859 void
4860 Editor::get_regions_corresponding_to (boost::shared_ptr<Region> region, vector<RegionView*>& regions)
4861 {
4862         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4863
4864                 RouteTimeAxisView* tatv;
4865
4866                 if ((tatv = dynamic_cast<RouteTimeAxisView*> (*i)) != 0) {
4867
4868                         boost::shared_ptr<Playlist> pl;
4869                         vector<boost::shared_ptr<Region> > results;
4870                         RegionView* marv;
4871                         boost::shared_ptr<Track> tr;
4872
4873                         if ((tr = tatv->track()) == 0) {
4874                                 /* bus */
4875                                 continue;
4876                         }
4877
4878                         if ((pl = (tr->playlist())) != 0) {
4879                                 pl->get_region_list_equivalent_regions (region, results);
4880                         }
4881
4882                         for (vector<boost::shared_ptr<Region> >::iterator ir = results.begin(); ir != results.end(); ++ir) {
4883                                 if ((marv = tatv->view()->find_view (*ir)) != 0) {
4884                                         regions.push_back (marv);
4885                                 }
4886                         }
4887
4888                 }
4889         }
4890 }
4891
4892 void
4893 Editor::show_rhythm_ferret ()
4894 {
4895         if (rhythm_ferret == 0) {
4896                 rhythm_ferret = new RhythmFerret(*this);
4897         }
4898
4899         rhythm_ferret->set_session (_session);
4900         rhythm_ferret->show ();
4901         rhythm_ferret->present ();
4902 }
4903
4904 void
4905 Editor::first_idle ()
4906 {
4907         MessageDialog* dialog = 0;
4908
4909         if (track_views.size() > 1) {
4910                 dialog = new MessageDialog (*this,
4911                                             string_compose (_("Please wait while %1 loads visual data"), PROGRAM_NAME),
4912                                             true,
4913                                             Gtk::MESSAGE_INFO,
4914                                             Gtk::BUTTONS_NONE);
4915                 dialog->present ();
4916                 ARDOUR_UI::instance()->flush_pending ();
4917         }
4918
4919         for (TrackViewList::iterator t = track_views.begin(); t != track_views.end(); ++t) {
4920                 (*t)->first_idle();
4921         }
4922
4923         // first idle adds route children (automation tracks), so we need to redisplay here
4924         _routes->redisplay ();
4925
4926         delete dialog;
4927
4928         _have_idled = true;
4929 }
4930
4931 gboolean
4932 Editor::_idle_resize (gpointer arg)
4933 {
4934         return ((Editor*)arg)->idle_resize ();
4935 }
4936
4937 void
4938 Editor::add_to_idle_resize (TimeAxisView* view, int32_t h)
4939 {
4940         if (resize_idle_id < 0) {
4941                 resize_idle_id = g_idle_add (_idle_resize, this);
4942                 _pending_resize_amount = 0;
4943         }
4944
4945         /* make a note of the smallest resulting height, so that we can clamp the
4946            lower limit at TimeAxisView::hSmall */
4947
4948         int32_t min_resulting = INT32_MAX;
4949
4950         _pending_resize_amount += h;
4951         _pending_resize_view = view;
4952
4953         min_resulting = min (min_resulting, int32_t (_pending_resize_view->current_height()) + _pending_resize_amount);
4954
4955         if (selection->tracks.contains (_pending_resize_view)) {
4956                 for (TrackViewList::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4957                         min_resulting = min (min_resulting, int32_t ((*i)->current_height()) + _pending_resize_amount);
4958                 }
4959         }
4960
4961         if (min_resulting < 0) {
4962                 min_resulting = 0;
4963         }
4964
4965         /* clamp */
4966         if (uint32_t (min_resulting) < TimeAxisView::preset_height (HeightSmall)) {
4967                 _pending_resize_amount += TimeAxisView::preset_height (HeightSmall) - min_resulting;
4968         }
4969 }
4970
4971 /** Handle pending resizing of tracks */
4972 bool
4973 Editor::idle_resize ()
4974 {
4975         _pending_resize_view->idle_resize (_pending_resize_view->current_height() + _pending_resize_amount);
4976
4977         if (dynamic_cast<AutomationTimeAxisView*> (_pending_resize_view) == 0 &&
4978             selection->tracks.contains (_pending_resize_view)) {
4979
4980                 for (TrackViewList::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4981                         if (*i != _pending_resize_view) {
4982                                 (*i)->idle_resize ((*i)->current_height() + _pending_resize_amount);
4983                         }
4984                 }
4985         }
4986
4987         _pending_resize_amount = 0;
4988         flush_canvas ();
4989         _group_tabs->set_dirty ();
4990         resize_idle_id = -1;
4991
4992         return false;
4993 }
4994
4995 void
4996 Editor::located ()
4997 {
4998         ENSURE_GUI_THREAD (*this, &Editor::located);
4999
5000         playhead_cursor->set_position (_session->audible_frame ());
5001         if (_follow_playhead && !_pending_initial_locate) {
5002                 reset_x_origin_to_follow_playhead ();
5003         }
5004
5005         _pending_locate_request = false;
5006         _pending_initial_locate = false;
5007 }
5008
5009 void
5010 Editor::region_view_added (RegionView *)
5011 {
5012         _summary->set_dirty ();
5013 }
5014
5015 TimeAxisView*
5016 Editor::axis_view_from_route (boost::shared_ptr<Route> r) const
5017 {
5018         TrackViewList::const_iterator j = track_views.begin ();
5019         while (j != track_views.end()) {
5020                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*j);
5021                 if (rtv && rtv->route() == r) {
5022                         return rtv;
5023                 }
5024                 ++j;
5025         }
5026
5027         return 0;
5028 }
5029
5030
5031 TrackViewList
5032 Editor::axis_views_from_routes (boost::shared_ptr<RouteList> r) const
5033 {
5034         TrackViewList t;
5035
5036         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5037                 TimeAxisView* tv = axis_view_from_route (*i);
5038                 if (tv) {
5039                         t.push_back (tv);
5040                 }
5041         }
5042
5043         return t;
5044 }
5045
5046
5047 void
5048 Editor::handle_new_route (RouteList& routes)
5049 {
5050         ENSURE_GUI_THREAD (*this, &Editor::handle_new_route, routes)
5051
5052         RouteTimeAxisView *rtv;
5053         list<RouteTimeAxisView*> new_views;
5054
5055         for (RouteList::iterator x = routes.begin(); x != routes.end(); ++x) {
5056                 boost::shared_ptr<Route> route = (*x);
5057
5058                 if (route->is_hidden() || route->is_monitor()) {
5059                         continue;
5060                 }
5061
5062                 DataType dt = route->input()->default_type();
5063
5064                 if (dt == ARDOUR::DataType::AUDIO) {
5065                         rtv = new AudioTimeAxisView (*this, _session, route, *track_canvas);
5066                 } else if (dt == ARDOUR::DataType::MIDI) {
5067                         rtv = new MidiTimeAxisView (*this, _session, route, *track_canvas);
5068                 } else {
5069                         throw unknown_type();
5070                 }
5071
5072                 new_views.push_back (rtv);
5073                 track_views.push_back (rtv);
5074
5075                 rtv->effective_gain_display ();
5076
5077                 rtv->view()->RegionViewAdded.connect (sigc::mem_fun (*this, &Editor::region_view_added));
5078         }
5079
5080         _routes->routes_added (new_views);
5081
5082         if (show_editor_mixer_when_tracks_arrive) {
5083                 show_editor_mixer (true);
5084         }
5085
5086         editor_list_button.set_sensitive (true);
5087
5088         _summary->set_dirty ();
5089 }
5090
5091 void
5092 Editor::timeaxisview_deleted (TimeAxisView *tv)
5093 {
5094         if (_session && _session->deletion_in_progress()) {
5095                 /* the situation is under control */
5096                 return;
5097         }
5098
5099         ENSURE_GUI_THREAD (*this, &Editor::timeaxisview_deleted, tv);
5100
5101         RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (tv);
5102         
5103         _routes->route_removed (tv);
5104
5105         if (tv == entered_track) {
5106                 entered_track = 0;
5107         }
5108
5109         TimeAxisView::Children c = tv->get_child_list ();
5110         for (TimeAxisView::Children::const_iterator i = c.begin(); i != c.end(); ++i) {
5111                 if (entered_track == i->get()) {
5112                         entered_track = 0;
5113                 }
5114         }
5115
5116         /* remove it from the list of track views */
5117
5118         TrackViewList::iterator i;
5119
5120         if ((i = find (track_views.begin(), track_views.end(), tv)) != track_views.end()) {
5121                 i = track_views.erase (i);
5122         }
5123
5124         /* update whatever the current mixer strip is displaying, if revelant */
5125
5126         boost::shared_ptr<Route> route;
5127
5128         if (rtav) {
5129                 route = rtav->route ();
5130         } 
5131
5132         if (current_mixer_strip && current_mixer_strip->route() == route) {
5133
5134                 TimeAxisView* next_tv;
5135
5136                 if (track_views.empty()) {
5137                         next_tv = 0;
5138                 } else if (i == track_views.end()) {
5139                         next_tv = track_views.front();
5140                 } else {
5141                         next_tv = (*i);
5142                 }
5143                 
5144                 
5145                 if (next_tv) {
5146                         set_selected_mixer_strip (*next_tv);
5147                 } else {
5148                         /* make the editor mixer strip go away setting the
5149                          * button to inactive (which also unticks the menu option)
5150                          */
5151                         
5152                         ActionManager::uncheck_toggleaction ("<Actions>/Editor/show-editor-mixer");
5153                 }
5154         } 
5155 }
5156
5157 void
5158 Editor::hide_track_in_display (TimeAxisView* tv, bool /*temponly*/)
5159 {
5160         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (tv);
5161
5162         if (rtv && current_mixer_strip && (rtv->route() == current_mixer_strip->route())) {
5163                 // this will hide the mixer strip
5164                 set_selected_mixer_strip (*tv);
5165         }
5166
5167         _routes->hide_track_in_display (*tv);
5168 }
5169
5170 bool
5171 Editor::sync_track_view_list_and_routes ()
5172 {
5173         track_views = TrackViewList (_routes->views ());
5174
5175         _summary->set_dirty ();
5176         _group_tabs->set_dirty ();
5177
5178         return false; // do not call again (until needed)
5179 }
5180
5181 void
5182 Editor::foreach_time_axis_view (sigc::slot<void,TimeAxisView&> theslot)
5183 {
5184         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5185                 theslot (**i);
5186         }
5187 }
5188
5189 /** Find a RouteTimeAxisView by the ID of its route */
5190 RouteTimeAxisView*
5191 Editor::get_route_view_by_route_id (PBD::ID& id) const
5192 {
5193         RouteTimeAxisView* v;
5194
5195         for (TrackViewList::const_iterator i = track_views.begin(); i != track_views.end(); ++i) {
5196                 if((v = dynamic_cast<RouteTimeAxisView*>(*i)) != 0) {
5197                         if(v->route()->id() == id) {
5198                                 return v;
5199                         }
5200                 }
5201         }
5202
5203         return 0;
5204 }
5205
5206 void
5207 Editor::fit_route_group (RouteGroup *g)
5208 {
5209         TrackViewList ts = axis_views_from_routes (g->route_list ());
5210         fit_tracks (ts);
5211 }
5212
5213 void
5214 Editor::consider_auditioning (boost::shared_ptr<Region> region)
5215 {
5216         boost::shared_ptr<AudioRegion> r = boost::dynamic_pointer_cast<AudioRegion> (region);
5217
5218         if (r == 0) {
5219                 _session->cancel_audition ();
5220                 return;
5221         }
5222
5223         if (_session->is_auditioning()) {
5224                 _session->cancel_audition ();
5225                 if (r == last_audition_region) {
5226                         return;
5227                 }
5228         }
5229
5230         _session->audition_region (r);
5231         last_audition_region = r;
5232 }
5233
5234
5235 void
5236 Editor::hide_a_region (boost::shared_ptr<Region> r)
5237 {
5238         r->set_hidden (true);
5239 }
5240
5241 void
5242 Editor::show_a_region (boost::shared_ptr<Region> r)
5243 {
5244         r->set_hidden (false);
5245 }
5246
5247 void
5248 Editor::audition_region_from_region_list ()
5249 {
5250         _regions->selection_mapover (sigc::mem_fun (*this, &Editor::consider_auditioning));
5251 }
5252
5253 void
5254 Editor::hide_region_from_region_list ()
5255 {
5256         _regions->selection_mapover (sigc::mem_fun (*this, &Editor::hide_a_region));
5257 }
5258
5259 void
5260 Editor::show_region_in_region_list ()
5261 {
5262         _regions->selection_mapover (sigc::mem_fun (*this, &Editor::show_a_region));
5263 }
5264
5265 void
5266 Editor::step_edit_status_change (bool yn)
5267 {
5268         if (yn) {
5269                 start_step_editing ();
5270         } else {
5271                 stop_step_editing ();
5272         }
5273 }
5274
5275 void
5276 Editor::start_step_editing ()
5277 {
5278         step_edit_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &Editor::check_step_edit), 20);
5279 }
5280
5281 void
5282 Editor::stop_step_editing ()
5283 {
5284         step_edit_connection.disconnect ();
5285 }
5286
5287 bool
5288 Editor::check_step_edit ()
5289 {
5290         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5291                 MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*> (*i);
5292                 if (mtv) {
5293                         mtv->check_step_edit ();
5294                 }
5295         }
5296
5297         return true; // do it again, till we stop
5298 }
5299
5300 bool
5301 Editor::horizontal_scroll_left_press ()
5302 {
5303         ++_scroll_callbacks;
5304         
5305         if (_scroll_connection.connected() && _scroll_callbacks < 5) {
5306                 /* delay the first auto-repeat */
5307                 return true;
5308         }
5309                 
5310         double x = leftmost_position() - current_page_frames() / 5;
5311         if (x < 0) {
5312                 x = 0;
5313         }
5314         
5315         reset_x_origin (x);
5316
5317         /* do hacky auto-repeat */
5318         if (!_scroll_connection.connected ()) {
5319                 _scroll_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_left_press), 100);
5320                 _scroll_callbacks = 0;
5321         }
5322
5323         return true;
5324 }
5325
5326 void
5327 Editor::horizontal_scroll_left_release ()
5328 {
5329         _scroll_connection.disconnect ();
5330 }
5331
5332 bool
5333 Editor::horizontal_scroll_right_press ()
5334 {
5335         ++_scroll_callbacks;
5336         
5337         if (_scroll_connection.connected() && _scroll_callbacks < 5) {
5338                 /* delay the first auto-repeat */
5339                 return true;
5340         }
5341
5342         reset_x_origin (leftmost_position() + current_page_frames() / 5);
5343
5344         /* do hacky auto-repeat */
5345         if (!_scroll_connection.connected ()) {
5346                 _scroll_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_right_press), 100);
5347                 _scroll_callbacks = 0;
5348         }
5349
5350         return true;
5351 }
5352
5353 void
5354 Editor::horizontal_scroll_right_release ()
5355 {
5356         _scroll_connection.disconnect ();
5357 }
5358
5359 /** Queue a change for the Editor viewport x origin to follow the playhead */
5360 void
5361 Editor::reset_x_origin_to_follow_playhead ()
5362 {
5363         nframes64_t const frame = playhead_cursor->current_frame;
5364
5365         if (frame < leftmost_frame || frame > leftmost_frame + current_page_frames()) {
5366
5367                 if (_session->transport_speed() < 0) {
5368                         
5369                         if (frame > (current_page_frames() / 2)) {
5370                                 center_screen (frame-(current_page_frames()/2));
5371                         } else {
5372                                 center_screen (current_page_frames()/2);
5373                         }
5374                         
5375                 } else {
5376                                                 
5377                         if (frame < leftmost_frame) {
5378                                 /* moving left */
5379                                 nframes64_t l = 0;
5380                                 if (_session->transport_rolling()) {
5381                                         /* rolling; end up with the playhead at the right of the page */
5382                                         l = frame - current_page_frames ();
5383                                 } else {
5384                                         /* not rolling: end up with the playhead 3/4 of the way along the page */
5385                                         l = frame - (3 * current_page_frames() / 4);
5386                                 }
5387                                 
5388                                 if (l < 0) {
5389                                         l = 0;
5390                                 }
5391                                 
5392                                 center_screen_internal (l + (current_page_frames() / 2), current_page_frames ());
5393                         } else {
5394                                 /* moving right */
5395                                 if (_session->transport_rolling()) {
5396                                         /* rolling: end up with the playhead on the left of the page */
5397                                         center_screen_internal (frame + (current_page_frames() / 2), current_page_frames ());
5398                                 } else {
5399                                         /* not rolling: end up with the playhead 1/4 of the way along the page */
5400                                         center_screen_internal (frame + (current_page_frames() / 4), current_page_frames ());
5401                                 }
5402                         }
5403                 }
5404         }
5405 }
5406
5407 void
5408 Editor::super_rapid_screen_update ()
5409 {
5410         if (!_session || !_session->engine().running()) {
5411                 return;
5412         }
5413
5414         /* METERING / MIXER STRIPS */
5415
5416         /* update track meters, if required */
5417         if (is_mapped() && meters_running) {
5418                 RouteTimeAxisView* rtv;
5419                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5420                         if ((rtv = dynamic_cast<RouteTimeAxisView*>(*i)) != 0) {
5421                                 rtv->fast_update ();
5422                         }
5423                 }
5424         }
5425
5426         /* and any current mixer strip */
5427         if (current_mixer_strip) {
5428                 current_mixer_strip->fast_update ();
5429         }
5430
5431         /* PLAYHEAD AND VIEWPORT */
5432
5433         nframes64_t const frame = _session->audible_frame();
5434
5435         /* There are a few reasons why we might not update the playhead / viewport stuff:
5436          *
5437          * 1.  we don't update things when there's a pending locate request, otherwise
5438          *     when the editor requests a locate there is a chance that this method
5439          *     will move the playhead before the locate request is processed, causing
5440          *     a visual glitch.
5441          * 2.  if we're not rolling, there's nothing to do here (locates are handled elsewhere).
5442          * 3.  if we're still at the same frame that we were last time, there's nothing to do.
5443          */
5444
5445         if (!_pending_locate_request && _session->transport_speed() != 0 && frame != last_update_frame) {
5446
5447                 last_update_frame = frame;
5448
5449                 if (!_dragging_playhead) {
5450                         playhead_cursor->set_position (frame);
5451                 }
5452
5453                 if (!_stationary_playhead) {
5454
5455                         if (!_dragging_playhead && _follow_playhead && _session->requested_return_frame() < 0) {
5456                                 reset_x_origin_to_follow_playhead ();
5457                         }
5458
5459                 } else {
5460                         
5461                         /* don't do continuous scroll till the new position is in the rightmost quarter of the
5462                            editor canvas
5463                         */
5464 #if 0                        
5465                         // FIXME DO SOMETHING THAT WORKS HERE - this is 2.X code                         
5466                         double target = ((double)frame - (double)current_page_frames()/2.0) / frames_per_unit;
5467                         if (target <= 0.0) {
5468                                 target = 0.0;
5469                         }
5470                         if (fabs(target - current) < current_page_frames() / frames_per_unit) {
5471                                 target = (target * 0.15) + (current * 0.85);
5472                         } else {
5473                                 /* relax */
5474                         }
5475                         
5476                         current = target;
5477                         set_horizontal_position (current);
5478 #endif
5479                 }
5480                 
5481         }
5482 }
5483
5484
5485 void
5486 Editor::session_going_away ()
5487 {
5488         _have_idled = false;
5489
5490         _session_connections.drop_connections ();
5491
5492         super_rapid_screen_update_connection.disconnect ();
5493         
5494         selection->clear ();
5495         cut_buffer->clear ();
5496
5497         clicked_regionview = 0;
5498         clicked_axisview = 0;
5499         clicked_routeview = 0;
5500         clicked_crossfadeview = 0;
5501         entered_regionview = 0;
5502         entered_track = 0;
5503         last_update_frame = 0;
5504         _drags->abort ();
5505
5506         playhead_cursor->canvas_item.hide ();
5507
5508         /* rip everything out of the list displays */
5509
5510         _regions->clear ();
5511         _routes->clear ();
5512         _route_groups->clear ();
5513
5514         /* do this first so that deleting a track doesn't reset cms to null
5515            and thus cause a leak.
5516         */
5517
5518         if (current_mixer_strip) {
5519                 if (current_mixer_strip->get_parent() != 0) {
5520                         global_hpacker.remove (*current_mixer_strip);
5521                 }
5522                 delete current_mixer_strip;
5523                 current_mixer_strip = 0;
5524         }
5525
5526         /* delete all trackviews */
5527
5528         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5529                 delete *i;
5530         }
5531         track_views.clear ();
5532
5533         zoom_range_clock.set_session (0);
5534         nudge_clock.set_session (0);
5535
5536         editor_list_button.set_active(false);
5537         editor_list_button.set_sensitive(false);
5538
5539         /* clear tempo/meter rulers */
5540         remove_metric_marks ();
5541         hide_measures ();
5542         clear_marker_display ();
5543
5544         delete current_bbt_points;
5545         current_bbt_points = 0;
5546
5547         /* get rid of any existing editor mixer strip */
5548
5549         WindowTitle title(Glib::get_application_name());
5550         title += _("Editor");
5551
5552         set_title (title.get_string());
5553
5554         SessionHandlePtr::session_going_away ();
5555 }
5556
5557
5558 void
5559 Editor::show_editor_list (bool yn)
5560 {
5561         if (yn) {
5562                 the_notebook.show();
5563         } else {
5564                 the_notebook.hide();
5565         }
5566 }
5567