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