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