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