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