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