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