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