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