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