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