Set up rulers to prevent access to uninitialized variables later.
[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         compute_fixed_ruler_scale ();
1245
1246         /* there are never any selected regions at startup */
1247
1248         sensitize_the_right_region_actions (false);
1249
1250         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
1251         set_state (*node);
1252
1253         /* catch up with the playhead */
1254
1255         session->request_locate (playhead_cursor->current_frame);
1256
1257         if (first_action_message) {
1258                 first_action_message->hide();
1259         }
1260
1261         update_title ();
1262
1263         session->GoingAway.connect (mem_fun(*this, &Editor::session_going_away));
1264         session->history().Changed.connect (mem_fun (*this, &Editor::history_changed));
1265
1266         /* These signals can all be emitted by a non-GUI thread. Therefore the
1267            handlers for them must not attempt to directly interact with the GUI,
1268            but use Gtkmm2ext::UI::instance()->call_slot();
1269         */
1270
1271         session_connections.push_back (session->TransportStateChange.connect (mem_fun(*this, &Editor::map_transport_state)));
1272         session_connections.push_back (session->PositionChanged.connect (mem_fun(*this, &Editor::map_position_change)));
1273         session_connections.push_back (session->RouteAdded.connect (mem_fun(*this, &Editor::handle_new_route)));
1274         session_connections.push_back (session->RegionsAdded.connect (mem_fun(*this, &Editor::handle_new_regions)));
1275         session_connections.push_back (session->RegionRemoved.connect (mem_fun(*this, &Editor::handle_region_removed)));
1276         session_connections.push_back (session->DurationChanged.connect (mem_fun(*this, &Editor::handle_new_duration)));
1277         session_connections.push_back (session->edit_group_added.connect (mem_fun(*this, &Editor::add_edit_group)));
1278         session_connections.push_back (session->edit_group_removed.connect (mem_fun(*this, &Editor::edit_groups_changed)));
1279         session_connections.push_back (session->NamedSelectionAdded.connect (mem_fun(*this, &Editor::handle_new_named_selection)));
1280         session_connections.push_back (session->NamedSelectionRemoved.connect (mem_fun(*this, &Editor::handle_new_named_selection)));
1281         session_connections.push_back (session->DirtyChanged.connect (mem_fun(*this, &Editor::update_title)));
1282         session_connections.push_back (session->StateSaved.connect (mem_fun(*this, &Editor::update_title_s)));
1283         session_connections.push_back (session->AskAboutPlaylistDeletion.connect (mem_fun(*this, &Editor::playlist_deletion_dialog)));
1284         session_connections.push_back (session->RegionHiddenChange.connect (mem_fun(*this, &Editor::region_hidden)));
1285
1286         session_connections.push_back (session->SMPTEOffsetChanged.connect (mem_fun(*this, &Editor::update_just_smpte)));
1287
1288         session_connections.push_back (session->tempo_map().StateChanged.connect (mem_fun(*this, &Editor::tempo_map_changed)));
1289
1290         session_connections.push_back (session->Located.connect (mem_fun (*this, &Editor::located)));
1291
1292         edit_groups_changed ();
1293
1294         edit_point_clock.set_mode(AudioClock::BBT);
1295         edit_point_clock.set_session (session);
1296         zoom_range_clock.set_session (session);
1297         _playlist_selector->set_session (session);
1298         nudge_clock.set_session (session);
1299         if (Profile->get_sae()) {
1300                 BBT_Time bbt;
1301                 bbt.bars = 0;
1302                 bbt.beats = 0;
1303                 bbt.ticks = 120;
1304                 nframes_t pos = session->tempo_map().bbt_duration_at (0, bbt, 1);
1305                 nudge_clock.set_mode(AudioClock::BBT);
1306                 nudge_clock.set (pos, true, 0, AudioClock::BBT);
1307                 
1308         } else {
1309                 nudge_clock.set (session->frame_rate() * 5, true, 0, AudioClock::SMPTE); // default of 5 seconds
1310         }
1311
1312         playhead_cursor->canvas_item.show ();
1313
1314         if (rhythm_ferret) {
1315                 rhythm_ferret->set_session (session);
1316         }
1317
1318         if (analysis_window != 0)
1319                 analysis_window->set_session (session);
1320
1321         Location* loc = session->locations()->auto_loop_location();
1322         if (loc == 0) {
1323                 loc = new Location (0, session->current_end_frame(), _("Loop"),(Location::Flags) (Location::IsAutoLoop | Location::IsHidden));
1324                 if (loc->start() == loc->end()) {
1325                         loc->set_end (loc->start() + 1);
1326                 }
1327                 session->locations()->add (loc, false);
1328                 session->set_auto_loop_location (loc);
1329         } else {
1330                 // force name
1331                 loc->set_name (_("Loop"));
1332         }
1333         
1334         loc = session->locations()->auto_punch_location();
1335         if (loc == 0) {
1336                 loc = new Location (0, session->current_end_frame(), _("Punch"), (Location::Flags) (Location::IsAutoPunch | Location::IsHidden));
1337                 if (loc->start() == loc->end()) {
1338                         loc->set_end (loc->start() + 1);
1339                 }
1340                 session->locations()->add (loc, false);
1341                 session->set_auto_punch_location (loc);
1342         } else {
1343                 // force name
1344                 loc->set_name (_("Punch"));
1345         }
1346
1347         Config->map_parameters (mem_fun (*this, &Editor::parameter_changed));
1348         
1349         session->StateSaved.connect (mem_fun(*this, &Editor::session_state_saved));
1350         
1351         refresh_location_display ();
1352         session->locations()->added.connect (mem_fun(*this, &Editor::add_new_location));
1353         session->locations()->removed.connect (mem_fun(*this, &Editor::location_gone));
1354         session->locations()->changed.connect (mem_fun(*this, &Editor::refresh_location_display));
1355         session->locations()->StateChanged.connect (mem_fun(*this, &Editor::refresh_location_display_s));
1356         session->locations()->end_location()->changed.connect (mem_fun(*this, &Editor::end_location_changed));
1357
1358         if (sfbrowser) {
1359                 sfbrowser->set_session (session);
1360         }
1361
1362         handle_new_duration ();
1363
1364         redisplay_regions ();
1365         redisplay_named_selections ();
1366         redisplay_snapshots ();
1367
1368         restore_ruler_visibility ();
1369         //tempo_map_changed (Change (0));
1370         session->tempo_map().apply_with_metrics (*this, &Editor::draw_metric_marks);
1371
1372         initial_route_list_display ();
1373
1374         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
1375                 (static_cast<TimeAxisView*>(*i))->set_samples_per_unit (frames_per_unit);
1376         }
1377
1378         start_scrolling ();
1379
1380         /* don't show master bus in a new session */
1381
1382         if (ARDOUR_UI::instance()->session_is_new ()) {
1383
1384                 TreeModel::Children rows = route_display_model->children();
1385                 TreeModel::Children::iterator i;
1386         
1387                 no_route_list_redisplay = true;
1388                 
1389                 for (i = rows.begin(); i != rows.end(); ++i) {
1390                         TimeAxisView *tv =  (*i)[route_display_columns.tv];
1391                         RouteTimeAxisView *rtv;
1392                         
1393                         if ((rtv = dynamic_cast<RouteTimeAxisView*>(tv)) != 0) {
1394                                 if (rtv->route()->is_master()) {
1395                                         route_list_display.get_selection()->unselect (i);
1396                                 }
1397                         }
1398                 }
1399                 
1400                 no_route_list_redisplay = false;
1401                 redisplay_route_list ();
1402         }
1403         
1404         switch (snap_type) {
1405         case SnapToRegionStart:
1406         case SnapToRegionEnd:
1407         case SnapToRegionSync:
1408         case SnapToRegionBoundary:
1409                 build_region_boundary_cache ();
1410                 break;
1411
1412         default:
1413                 break;
1414         }
1415
1416         /* register for undo history */
1417         session->register_with_memento_command_factory(_id, this);
1418
1419         start_updating ();
1420 }
1421
1422 void
1423 Editor::build_cursors ()
1424 {
1425         using namespace Gdk;
1426         
1427         Gdk::Color mbg ("#000000" ); /* Black */
1428         Gdk::Color mfg ("#0000ff" ); /* Blue. */
1429
1430         {
1431                 RefPtr<Bitmap> source, mask;
1432                 source = Bitmap::create (mag_bits, mag_width, mag_height);
1433                 mask = Bitmap::create (magmask_bits, mag_width, mag_height);
1434                 zoom_cursor = new Gdk::Cursor (source, mask, mfg, mbg, mag_x_hot, mag_y_hot);
1435         }
1436
1437         Gdk::Color fbg ("#ffffff" );
1438         Gdk::Color ffg  ("#000000" );
1439         
1440         {
1441                 RefPtr<Bitmap> source, mask;
1442                 
1443                 source = Bitmap::create (fader_cursor_bits, fader_cursor_width, fader_cursor_height);
1444                 mask = Bitmap::create (fader_cursor_mask_bits, fader_cursor_width, fader_cursor_height);
1445                 fader_cursor = new Gdk::Cursor (source, mask, ffg, fbg, fader_cursor_x_hot, fader_cursor_y_hot);
1446         }
1447         
1448         { 
1449                 RefPtr<Bitmap> source, mask;
1450                 source = Bitmap::create (speaker_cursor_bits, speaker_cursor_width, speaker_cursor_height);
1451                 mask = Bitmap::create (speaker_cursor_mask_bits, speaker_cursor_width, speaker_cursor_height);
1452                 speaker_cursor = new Gdk::Cursor (source, mask, ffg, fbg, speaker_cursor_x_hot, speaker_cursor_y_hot);
1453         }
1454         
1455         { 
1456                 RefPtr<Bitmap> bits;
1457                 char pix[4] = { 0, 0, 0, 0 };
1458                 bits = Bitmap::create (pix, 2, 2);
1459                 Gdk::Color c;
1460                 transparent_cursor = new Gdk::Cursor (bits, bits, c, c, 0, 0);
1461         }
1462
1463         { 
1464                 RefPtr<Bitmap> bits;
1465                 char pix[4] = { 0, 0, 0, 0 };
1466                 bits = Bitmap::create (pix, 2, 2);
1467                 Gdk::Color c;
1468                 transparent_cursor = new Gdk::Cursor (bits, bits, c, c, 0, 0);
1469         }
1470         
1471
1472         grabber_cursor = new Gdk::Cursor (HAND2);
1473         
1474         {
1475                 Glib::RefPtr<Gdk::Pixbuf> grabber_edit_point_pixbuf (::get_icon ("grabber_edit_point"));
1476                 grabber_edit_point_cursor = new Gdk::Cursor (Gdk::Display::get_default(), grabber_edit_point_pixbuf, 5, 17);
1477         }
1478
1479         cross_hair_cursor = new Gdk::Cursor (CROSSHAIR);
1480         trimmer_cursor =  new Gdk::Cursor (SB_H_DOUBLE_ARROW);
1481         selector_cursor = new Gdk::Cursor (XTERM);
1482         time_fx_cursor = new Gdk::Cursor (SIZING);
1483         wait_cursor = new Gdk::Cursor  (WATCH);
1484         timebar_cursor = new Gdk::Cursor(LEFT_PTR);
1485         midi_pencil_cursor = new Gdk::Cursor (PENCIL);
1486         midi_select_cursor = new Gdk::Cursor (CENTER_PTR);
1487         midi_resize_cursor = new Gdk::Cursor (SIZING);
1488         midi_erase_cursor = new Gdk::Cursor (DRAPED_BOX);
1489 }
1490
1491 /** Pop up a context menu for when the user clicks on a fade in or fade out */
1492 void
1493 Editor::popup_fade_context_menu (int button, int32_t time, ArdourCanvas::Item* item, ItemType item_type)
1494 {
1495         using namespace Menu_Helpers;
1496         AudioRegionView* arv = static_cast<AudioRegionView*> (item->get_data ("regionview"));
1497
1498         if (arv == 0) {
1499                 fatal << _("programming error: fade in canvas item has no regionview data pointer!") << endmsg;
1500                 /*NOTREACHED*/
1501         }
1502
1503         MenuList& items (fade_context_menu.items());
1504
1505         items.clear ();
1506
1507         switch (item_type) {
1508         case FadeInItem:
1509         case FadeInHandleItem:
1510                 if (arv->audio_region()->fade_in_active()) {
1511                         items.push_back (MenuElem (_("Deactivate"), bind (mem_fun (*this, &Editor::set_fade_in_active), false)));
1512                 } else {
1513                         items.push_back (MenuElem (_("Activate"), bind (mem_fun (*this, &Editor::set_fade_in_active), true)));
1514                 }
1515                 
1516                 items.push_back (SeparatorElem());
1517
1518                 if (Profile->get_sae()) {
1519                         items.push_back (MenuElem (_("Linear"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Linear)));
1520                         items.push_back (MenuElem (_("Slowest"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Fast)));
1521                 } else {
1522                         items.push_back (MenuElem (_("Linear"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Linear)));
1523                         items.push_back (MenuElem (_("Slowest"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Fast)));
1524                         items.push_back (MenuElem (_("Slow"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::LogB)));
1525                         items.push_back (MenuElem (_("Fast"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::LogA)));
1526                         items.push_back (MenuElem (_("Fastest"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Slow)));
1527                 }
1528
1529                 break;
1530
1531         case FadeOutItem:
1532         case FadeOutHandleItem:
1533                 if (arv->audio_region()->fade_out_active()) {
1534                         items.push_back (MenuElem (_("Deactivate"), bind (mem_fun (*this, &Editor::set_fade_out_active), false)));
1535                 } else {
1536                         items.push_back (MenuElem (_("Activate"), bind (mem_fun (*this, &Editor::set_fade_out_active), true)));
1537                 }
1538                 
1539                 items.push_back (SeparatorElem());
1540                 
1541                 if (Profile->get_sae()) {
1542                         items.push_back (MenuElem (_("Linear"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Linear)));
1543                         items.push_back (MenuElem (_("Slowest"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Slow)));
1544                 } else {
1545                         items.push_back (MenuElem (_("Linear"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Linear)));
1546                         items.push_back (MenuElem (_("Slowest"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Slow)));
1547                         items.push_back (MenuElem (_("Slow"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::LogA)));
1548                         items.push_back (MenuElem (_("Fast"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::LogB)));
1549                         items.push_back (MenuElem (_("Fastest"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Fast)));
1550                 }
1551
1552                 break;
1553
1554         default:
1555                 fatal << _("programming error: ")
1556                       << X_("non-fade canvas item passed to popup_fade_context_menu()")
1557                       << endmsg;
1558                 /*NOTREACHED*/
1559         }
1560
1561         fade_context_menu.popup (button, time);
1562 }
1563
1564 void
1565 Editor::popup_track_context_menu (int button, int32_t time, ItemType item_type, bool with_selection, nframes64_t frame)
1566 {
1567         using namespace Menu_Helpers;
1568         Menu* (Editor::*build_menu_function)(nframes64_t);
1569         Menu *menu;
1570
1571         switch (item_type) {
1572         case RegionItem:
1573         case RegionViewName:
1574         case RegionViewNameHighlight:
1575                 if (with_selection) {
1576                         build_menu_function = &Editor::build_track_selection_context_menu;
1577                 } else {
1578                         build_menu_function = &Editor::build_track_region_context_menu;
1579                 }
1580                 break;
1581
1582         case SelectionItem:
1583                 if (with_selection) {
1584                         build_menu_function = &Editor::build_track_selection_context_menu;
1585                 } else {
1586                         build_menu_function = &Editor::build_track_context_menu;
1587                 }
1588                 break;
1589
1590         case CrossfadeViewItem:
1591                 build_menu_function = &Editor::build_track_crossfade_context_menu;
1592                 break;
1593
1594         case StreamItem:
1595                 if (clicked_routeview->get_diskstream()) {
1596                         build_menu_function = &Editor::build_track_context_menu;
1597                 } else {
1598                         build_menu_function = &Editor::build_track_bus_context_menu;
1599                 }
1600                 break;
1601
1602         default:
1603                 /* probably shouldn't happen but if it does, we don't care */
1604                 return;
1605         }
1606
1607         menu = (this->*build_menu_function)(frame);
1608         menu->set_name ("ArdourContextMenu");
1609         
1610         /* now handle specific situations */
1611
1612         switch (item_type) {
1613         case RegionItem:
1614         case RegionViewName:
1615         case RegionViewNameHighlight:
1616                 if (!with_selection) {
1617                         if (region_edit_menu_split_item) {
1618                                 if (clicked_regionview && clicked_regionview->region()->covers (get_preferred_edit_position())) {
1619                                         ActionManager::set_sensitive (ActionManager::edit_point_in_region_sensitive_actions, true);
1620                                 } else {
1621                                         ActionManager::set_sensitive (ActionManager::edit_point_in_region_sensitive_actions, false);
1622                                 }
1623                         }
1624                         /*
1625                         if (region_edit_menu_split_multichannel_item) {
1626                                 if (clicked_regionview && clicked_regionview->region().n_channels() > 1) {
1627                                         // GTK2FIX find the action, change its sensitivity
1628                                         // region_edit_menu_split_multichannel_item->set_sensitive (true);
1629                                 } else {
1630                                         // GTK2FIX see above
1631                                         // region_edit_menu_split_multichannel_item->set_sensitive (false);
1632                                 }
1633                         }*/
1634                 }
1635                 break;
1636
1637         case SelectionItem:
1638                 break;
1639
1640         case CrossfadeViewItem:
1641                 break;
1642
1643         case StreamItem:
1644                 break;
1645
1646         default:
1647                 /* probably shouldn't happen but if it does, we don't care */
1648                 return;
1649         }
1650
1651         if (item_type != SelectionItem && clicked_routeview && clicked_routeview->audio_track()) {
1652
1653                 /* Bounce to disk */
1654                 
1655                 using namespace Menu_Helpers;
1656                 MenuList& edit_items  = menu->items();
1657                 
1658                 edit_items.push_back (SeparatorElem());
1659
1660                 switch (clicked_routeview->audio_track()->freeze_state()) {
1661                 case AudioTrack::NoFreeze:
1662                         edit_items.push_back (MenuElem (_("Freeze"), mem_fun(*this, &Editor::freeze_route)));
1663                         break;
1664
1665                 case AudioTrack::Frozen:
1666                         edit_items.push_back (MenuElem (_("Unfreeze"), mem_fun(*this, &Editor::unfreeze_route)));
1667                         break;
1668                         
1669                 case AudioTrack::UnFrozen:
1670                         edit_items.push_back (MenuElem (_("Freeze"), mem_fun(*this, &Editor::freeze_route)));
1671                         break;
1672                 }
1673
1674         }
1675
1676         if (item_type == StreamItem && clicked_routeview) {
1677                 clicked_routeview->build_underlay_menu(menu);
1678         }
1679
1680         menu->popup (button, time);
1681 }
1682
1683 Menu*
1684 Editor::build_track_context_menu (nframes64_t ignored)
1685 {
1686         using namespace Menu_Helpers;
1687
1688         MenuList& edit_items = track_context_menu.items();
1689         edit_items.clear();
1690
1691         add_dstream_context_items (edit_items);
1692         return &track_context_menu;
1693 }
1694
1695 Menu*
1696 Editor::build_track_bus_context_menu (nframes64_t ignored)
1697 {
1698         using namespace Menu_Helpers;
1699
1700         MenuList& edit_items = track_context_menu.items();
1701         edit_items.clear();
1702
1703         add_bus_context_items (edit_items);
1704         return &track_context_menu;
1705 }
1706
1707 Menu*
1708 Editor::build_track_region_context_menu (nframes64_t frame)
1709 {
1710         using namespace Menu_Helpers;
1711         MenuList& edit_items  = track_region_context_menu.items();
1712         edit_items.clear();
1713
1714         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (clicked_axisview);
1715
1716         if (rtv) {
1717                 boost::shared_ptr<Diskstream> ds;
1718                 boost::shared_ptr<Playlist> pl;
1719                 
1720                 if ((ds = rtv->get_diskstream()) && ((pl = ds->playlist()))) {
1721                         Playlist::RegionList* regions = pl->regions_at ((nframes64_t) floor ( (double)frame * ds->speed()));
1722
1723                         if (selection->regions.size() > 1) {
1724                                 // there's already a multiple selection: just add a 
1725                                 // single region context menu that will act on all 
1726                                 // selected regions
1727                                 boost::shared_ptr<Region> dummy_region; // = NULL               
1728                                 add_region_context_items (rtv->view(), dummy_region, edit_items);                       
1729                         } else {
1730                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
1731                                         add_region_context_items (rtv->view(), (*i), edit_items);
1732                                 }
1733                         }
1734
1735                         delete regions;
1736                 }
1737         }
1738
1739         add_dstream_context_items (edit_items);
1740
1741         return &track_region_context_menu;
1742 }
1743
1744 Menu*
1745 Editor::build_track_crossfade_context_menu (nframes64_t frame)
1746 {
1747         using namespace Menu_Helpers;
1748         MenuList& edit_items  = track_crossfade_context_menu.items();
1749         edit_items.clear ();
1750
1751         AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*> (clicked_axisview);
1752
1753         if (atv) {
1754                 boost::shared_ptr<Diskstream> ds;
1755                 boost::shared_ptr<Playlist> pl;
1756                 boost::shared_ptr<AudioPlaylist> apl;
1757
1758                 if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()) != 0) && ((apl = boost::dynamic_pointer_cast<AudioPlaylist> (pl)) != 0)) {
1759
1760                         Playlist::RegionList* regions = pl->regions_at (frame);
1761                         AudioPlaylist::Crossfades xfades;
1762
1763                         apl->crossfades_at (frame, xfades);
1764
1765                         bool many = xfades.size() > 1;
1766
1767                         for (AudioPlaylist::Crossfades::iterator i = xfades.begin(); i != xfades.end(); ++i) {
1768                                 add_crossfade_context_items (atv->audio_view(), (*i), edit_items, many);
1769                         }
1770
1771                         if (selection->regions.size() > 1) {
1772                                 // there's already a multiple selection: just add a 
1773                                 // single region context menu that will act on all 
1774                                 // selected regions
1775                                 boost::shared_ptr<Region> dummy_region; // = NULL               
1776                                 add_region_context_items (atv->audio_view(), dummy_region, edit_items);                 
1777                         } else {
1778                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
1779                                         add_region_context_items (atv->audio_view(), (*i), edit_items);
1780                                 }
1781                         }
1782                         delete regions;
1783                 }
1784         }
1785
1786         add_dstream_context_items (edit_items);
1787
1788         return &track_crossfade_context_menu;
1789 }
1790
1791 void
1792 Editor::analyze_region_selection()
1793 {
1794         if (analysis_window == 0) {
1795                 analysis_window = new AnalysisWindow();
1796
1797                 if (session != 0)
1798                         analysis_window->set_session(session);
1799
1800                 analysis_window->show_all();
1801         }
1802
1803         analysis_window->set_regionmode();
1804         analysis_window->analyze();
1805         
1806         analysis_window->present();
1807 }
1808
1809 void
1810 Editor::analyze_range_selection()
1811 {
1812         if (analysis_window == 0) {
1813                 analysis_window = new AnalysisWindow();
1814
1815                 if (session != 0)
1816                         analysis_window->set_session(session);
1817
1818                 analysis_window->show_all();
1819         }
1820
1821         analysis_window->set_rangemode();
1822         analysis_window->analyze();
1823         
1824         analysis_window->present();
1825 }
1826
1827 Menu*
1828 Editor::build_track_selection_context_menu (nframes64_t ignored)
1829 {
1830         using namespace Menu_Helpers;
1831         MenuList& edit_items  = track_selection_context_menu.items();
1832         edit_items.clear ();
1833
1834         add_selection_context_items (edit_items);
1835         // edit_items.push_back (SeparatorElem());
1836         // add_dstream_context_items (edit_items);
1837
1838         return &track_selection_context_menu;
1839 }
1840
1841 /** Add context menu items relevant to crossfades.
1842  * @param edit_items List to add the items to.
1843  */
1844 void
1845 Editor::add_crossfade_context_items (AudioStreamView* view, boost::shared_ptr<Crossfade> xfade, Menu_Helpers::MenuList& edit_items, bool many)
1846 {
1847         using namespace Menu_Helpers;
1848         Menu     *xfade_menu = manage (new Menu);
1849         MenuList& items       = xfade_menu->items();
1850         xfade_menu->set_name ("ArdourContextMenu");
1851         string str;
1852
1853         if (xfade->active()) {
1854                 str = _("Mute");
1855         } else { 
1856                 str = _("Unmute");
1857         }
1858
1859         items.push_back (MenuElem (str, bind (mem_fun(*this, &Editor::toggle_xfade_active), boost::weak_ptr<Crossfade> (xfade))));
1860         items.push_back (MenuElem (_("Edit"), bind (mem_fun(*this, &Editor::edit_xfade), boost::weak_ptr<Crossfade> (xfade))));
1861
1862         if (xfade->can_follow_overlap()) {
1863
1864                 if (xfade->following_overlap()) {
1865                         str = _("Convert to short");
1866                 } else {
1867                         str = _("Convert to full");
1868                 }
1869
1870                 items.push_back (MenuElem (str, bind (mem_fun(*this, &Editor::toggle_xfade_length), xfade)));
1871         }
1872
1873         if (many) {
1874                 str = xfade->out()->name();
1875                 str += "->";
1876                 str += xfade->in()->name();
1877         } else {
1878                 str = _("Crossfade");
1879         }
1880
1881         edit_items.push_back (MenuElem (str, *xfade_menu));
1882         edit_items.push_back (SeparatorElem());
1883 }
1884
1885 void
1886 Editor::xfade_edit_left_region ()
1887 {
1888         if (clicked_crossfadeview) {
1889                 clicked_crossfadeview->left_view.show_region_editor ();
1890         }
1891 }
1892
1893 void
1894 Editor::xfade_edit_right_region ()
1895 {
1896         if (clicked_crossfadeview) {
1897                 clicked_crossfadeview->right_view.show_region_editor ();
1898         }
1899 }
1900
1901 /** Add an element to a menu, settings its sensitivity.
1902  * @param m Menu to add to.
1903  * @param e Element to add.
1904  * @param s true to make sensitive, false to make insensitive
1905  */
1906 void
1907 Editor::add_item_with_sensitivity (Menu_Helpers::MenuList& m, Menu_Helpers::MenuElem e, bool s) const
1908 {
1909         m.push_back (e);
1910         if (!s) {
1911                 m.back().set_sensitive (false);
1912         }
1913 }
1914
1915 void
1916 Editor::add_region_context_items (StreamView* sv, boost::shared_ptr<Region> region, Menu_Helpers::MenuList& edit_items)
1917 {
1918         using namespace Menu_Helpers;
1919         Gtk::MenuItem* foo_item;
1920         Menu     *region_menu = manage (new Menu);
1921         MenuList& items       = region_menu->items();
1922         region_menu->set_name ("ArdourContextMenu");
1923
1924         boost::shared_ptr<AudioRegion> ar;
1925         boost::shared_ptr<MidiRegion>  mr;
1926
1927         if (region) {
1928                 ar = boost::dynamic_pointer_cast<AudioRegion> (region);
1929                 mr = boost::dynamic_pointer_cast<MidiRegion> (region);
1930
1931                 /* when this particular menu pops up, make the relevant region 
1932                    become selected.
1933                 */
1934
1935                 region_menu->signal_map_event().connect (
1936                         bind (mem_fun(*this, &Editor::set_selected_regionview_from_map_event), sv, boost::weak_ptr<Region>(region)));
1937                 
1938                 items.push_back (MenuElem (_("Rename"), mem_fun(*this, &Editor::rename_region)));
1939                 items.push_back (MenuElem (_("Popup region editor"), mem_fun(*this, &Editor::edit_region)));
1940         }
1941
1942         items.push_back (MenuElem (_("Raise to top layer"), mem_fun(*this, &Editor::raise_region_to_top)));
1943         items.push_back (MenuElem (_("Lower to bottom layer"), mem_fun  (*this, &Editor::lower_region_to_bottom)));
1944         items.push_back (SeparatorElem());
1945         items.push_back (MenuElem (_("Define sync point"), mem_fun(*this, &Editor::set_region_sync_from_edit_point)));
1946         items.push_back (MenuElem (_("Remove sync point"), mem_fun(*this, &Editor::remove_region_sync)));
1947         items.push_back (SeparatorElem());
1948
1949         items.push_back (MenuElem (_("Audition"), mem_fun(*this, &Editor::play_selected_region)));
1950         items.push_back (MenuElem (_("Export"), mem_fun(*this, &Editor::export_region)));
1951         items.push_back (MenuElem (_("Bounce"), mem_fun(*this, &Editor::bounce_region_selection)));
1952
1953         if (ar) {
1954                 items.push_back (MenuElem (_("Spectral Analysis"), mem_fun(*this, &Editor::analyze_region_selection)));
1955         }
1956
1957         items.push_back (SeparatorElem());
1958
1959         sigc::connection fooc;
1960         boost::shared_ptr<Region> region_to_check;
1961
1962         if (region) {
1963                 region_to_check = region;
1964         } else {
1965                 region_to_check = selection->regions.front()->region();
1966         }
1967
1968         items.push_back (CheckMenuElem (_("Lock")));
1969         CheckMenuItem* region_lock_item = static_cast<CheckMenuItem*>(&items.back());
1970         if (region_to_check->locked()) {
1971                 region_lock_item->set_active();
1972         }
1973         region_lock_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_region_lock));
1974         
1975         items.push_back (CheckMenuElem (_("Glue to Bars&Beats")));
1976         CheckMenuItem* bbt_glue_item = static_cast<CheckMenuItem*>(&items.back());
1977         
1978         switch (region_to_check->positional_lock_style()) {
1979         case Region::MusicTime:
1980                 bbt_glue_item->set_active (true);
1981                 break;
1982         default:
1983                 bbt_glue_item->set_active (false);
1984                 break;
1985         }
1986         
1987         bbt_glue_item->signal_activate().connect (bind (mem_fun (*this, &Editor::set_region_lock_style), Region::MusicTime));
1988         
1989         items.push_back (CheckMenuElem (_("Mute")));
1990         CheckMenuItem* region_mute_item = static_cast<CheckMenuItem*>(&items.back());
1991         fooc = region_mute_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_region_mute));
1992         if (region_to_check->muted()) {
1993                 fooc.block (true);
1994                 region_mute_item->set_active();
1995                 fooc.block (false);
1996         }
1997         
1998         if (!Profile->get_sae()) {
1999                 items.push_back (CheckMenuElem (_("Opaque")));
2000                 CheckMenuItem* region_opaque_item = static_cast<CheckMenuItem*>(&items.back());
2001                 fooc = region_opaque_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_region_opaque));
2002                 if (region_to_check->opaque()) {
2003                         fooc.block (true);
2004                         region_opaque_item->set_active();
2005                         fooc.block (false);
2006                 }
2007         }
2008         
2009         items.push_back (CheckMenuElem (_("Original position"), mem_fun(*this, &Editor::naturalize)));
2010         if (region_to_check->at_natural_position()) {
2011                 items.back().set_sensitive (false);
2012         }
2013         
2014         items.push_back (SeparatorElem());
2015         
2016         if (ar) {
2017                 
2018                 RegionView* rv = sv->find_view (ar);
2019                 AudioRegionView* arv = dynamic_cast<AudioRegionView*>(rv);
2020                 
2021                 if (!Profile->get_sae()) {
2022                         items.push_back (MenuElem (_("Reset Envelope"), mem_fun(*this, &Editor::reset_region_gain_envelopes)));
2023
2024                         items.push_back (CheckMenuElem (_("Envelope Visible")));
2025                         CheckMenuItem* region_envelope_visible_item = static_cast<CheckMenuItem*> (&items.back());
2026                         fooc = region_envelope_visible_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_gain_envelope_visibility));
2027                         if (arv->envelope_visible()) {
2028                                 fooc.block (true);
2029                                 region_envelope_visible_item->set_active (true);
2030                                 fooc.block (false);
2031                         }
2032                 
2033                         items.push_back (CheckMenuElem (_("Envelope Active")));
2034                         CheckMenuItem* region_envelope_active_item = static_cast<CheckMenuItem*> (&items.back());
2035                         fooc = region_envelope_active_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_gain_envelope_active));
2036                         
2037                         if (ar->envelope_active()) {
2038                                 fooc.block (true);
2039                                 region_envelope_active_item->set_active (true);
2040                                 fooc.block (false);
2041                         }
2042
2043                         items.push_back (SeparatorElem());
2044                 }
2045
2046                 if (ar->scale_amplitude() != 1.0f) {
2047                         items.push_back (MenuElem (_("DeNormalize"), mem_fun(*this, &Editor::denormalize_region)));
2048                 } else {
2049                         items.push_back (MenuElem (_("Normalize"), mem_fun(*this, &Editor::normalize_region)));
2050                 }
2051
2052         } else if (mr) {
2053                 items.push_back (MenuElem (_("Quantize"), mem_fun(*this, &Editor::quantize_region)));
2054                 items.push_back (SeparatorElem());
2055         }
2056
2057         items.push_back (MenuElem (_("Strip silence..."), mem_fun (*this, &Editor::strip_region_silence)));
2058         items.push_back (MenuElem (_("Reverse"), mem_fun(*this, &Editor::reverse_region)));
2059         items.push_back (SeparatorElem());
2060
2061         /* range related stuff */
2062
2063         items.push_back (MenuElem (_("Add Single Range"), mem_fun (*this, &Editor::add_location_from_audio_region)));
2064         items.push_back (MenuElem (_("Add Range Markers"), mem_fun (*this, &Editor::add_locations_from_audio_region)));
2065         if (selection->regions.size() < 2) {
2066                 items.back().set_sensitive (false);
2067         }
2068
2069         items.push_back (MenuElem (_("Set Range Selection"), mem_fun (*this, &Editor::set_selection_from_region)));
2070         items.push_back (SeparatorElem());
2071                          
2072         /* Nudge region */
2073
2074         Menu *nudge_menu = manage (new Menu());
2075         MenuList& nudge_items = nudge_menu->items();
2076         nudge_menu->set_name ("ArdourContextMenu");
2077         
2078         nudge_items.push_back (MenuElem (_("Nudge fwd"), (bind (mem_fun(*this, &Editor::nudge_forward), false, false))));
2079         nudge_items.push_back (MenuElem (_("Nudge bwd"), (bind (mem_fun(*this, &Editor::nudge_backward), false, false))));
2080         nudge_items.push_back (MenuElem (_("Nudge fwd by capture offset"), (mem_fun(*this, &Editor::nudge_forward_capture_offset))));
2081         nudge_items.push_back (MenuElem (_("Nudge bwd by capture offset"), (mem_fun(*this, &Editor::nudge_backward_capture_offset))));
2082
2083         items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2084         items.push_back (SeparatorElem());
2085
2086         Menu *trim_menu = manage (new Menu);
2087         MenuList& trim_items = trim_menu->items();
2088         trim_menu->set_name ("ArdourContextMenu");
2089         
2090         trim_items.push_back (MenuElem (_("Start to edit point"), mem_fun(*this, &Editor::trim_region_from_edit_point)));
2091         foo_item = &trim_items.back();
2092         if (_edit_point == EditAtMouse) {
2093                 foo_item->set_sensitive (false);
2094         }
2095         trim_items.push_back (MenuElem (_("Edit point to end"), mem_fun(*this, &Editor::trim_region_to_edit_point)));
2096         foo_item = &trim_items.back();
2097         if (_edit_point == EditAtMouse) {
2098                 foo_item->set_sensitive (false);
2099         }
2100         trim_items.push_back (MenuElem (_("Trim To Loop"), mem_fun(*this, &Editor::trim_region_to_loop)));
2101         trim_items.push_back (MenuElem (_("Trim To Punch"), mem_fun(*this, &Editor::trim_region_to_punch)));
2102                              
2103         items.push_back (MenuElem (_("Trim"), *trim_menu));
2104         items.push_back (SeparatorElem());
2105
2106         items.push_back (MenuElem (_("Split"), (mem_fun(*this, &Editor::split_region))));
2107         region_edit_menu_split_item = &items.back();
2108         
2109         if (_edit_point == EditAtMouse) {
2110                 region_edit_menu_split_item->set_sensitive (false);
2111         }
2112
2113         items.push_back (MenuElem (_("Make mono regions"), (mem_fun(*this, &Editor::split_multichannel_region))));
2114         region_edit_menu_split_multichannel_item = &items.back();
2115
2116         items.push_back (MenuElem (_("Duplicate"), (bind (mem_fun(*this, &Editor::duplicate_dialog), false))));
2117         items.push_back (MenuElem (_("Multi-Duplicate"), (bind (mem_fun(*this, &Editor::duplicate_dialog), true))));
2118         items.push_back (MenuElem (_("Fill Track"), (mem_fun(*this, &Editor::region_fill_track))));
2119         items.push_back (SeparatorElem());
2120         items.push_back (MenuElem (_("Remove"), mem_fun(*this, &Editor::remove_selected_regions)));
2121
2122         /* OK, stick the region submenu at the top of the list, and then add
2123            the standard items.
2124         */
2125
2126         /* we have to hack up the region name because "_" has a special
2127            meaning for menu titles.
2128         */
2129
2130         string::size_type pos = 0;
2131         string menu_item_name = (region) ? region->name() : _("Selected regions");
2132
2133         while ((pos = menu_item_name.find ("_", pos)) != string::npos) {
2134                 menu_item_name.replace (pos, 1, "__");
2135                 pos += 2;
2136         }
2137         
2138         edit_items.push_back (MenuElem (menu_item_name, *region_menu));
2139         edit_items.push_back (SeparatorElem());
2140 }
2141
2142 /** Add context menu items relevant to selection ranges.
2143  * @param edit_items List to add the items to.
2144  */
2145 void
2146 Editor::add_selection_context_items (Menu_Helpers::MenuList& edit_items)
2147 {
2148         using namespace Menu_Helpers;
2149
2150         edit_items.push_back (MenuElem (_("Play range"), mem_fun(*this, &Editor::play_selection)));
2151         edit_items.push_back (MenuElem (_("Loop range"), bind (mem_fun(*this, &Editor::set_loop_from_selection), true)));
2152
2153         edit_items.push_back (SeparatorElem());
2154         edit_items.push_back (MenuElem (_("Spectral Analysis"), mem_fun(*this, &Editor::analyze_range_selection)));
2155         
2156         edit_items.push_back (SeparatorElem());
2157         edit_items.push_back (MenuElem (_("Extend Range to End of Region"), bind (mem_fun(*this, &Editor::extend_selection_to_end_of_region), false)));
2158         edit_items.push_back (MenuElem (_("Extend Range to Start of Region"), bind (mem_fun(*this, &Editor::extend_selection_to_start_of_region), false)));
2159
2160         edit_items.push_back (SeparatorElem());
2161         edit_items.push_back (MenuElem (_("Convert to region in-place"), mem_fun(*this, &Editor::separate_region_from_selection)));
2162         edit_items.push_back (MenuElem (_("Convert to region in region list"), mem_fun(*this, &Editor::new_region_from_selection)));
2163         
2164         edit_items.push_back (SeparatorElem());
2165         edit_items.push_back (MenuElem (_("Select all in range"), mem_fun(*this, &Editor::select_all_selectables_using_time_selection)));
2166
2167         edit_items.push_back (SeparatorElem());
2168         edit_items.push_back (MenuElem (_("Set loop from selection"), bind (mem_fun(*this, &Editor::set_loop_from_selection), false)));
2169         edit_items.push_back (MenuElem (_("Set punch from selection"), mem_fun(*this, &Editor::set_punch_from_selection)));
2170         
2171         edit_items.push_back (SeparatorElem());
2172         edit_items.push_back (MenuElem (_("Add Range Markers"), mem_fun (*this, &Editor::add_location_from_selection)));
2173         edit_items.push_back (SeparatorElem());
2174         edit_items.push_back (MenuElem (_("Crop region to range"), mem_fun(*this, &Editor::crop_region_to_selection)));
2175         edit_items.push_back (MenuElem (_("Fill range with region"), mem_fun(*this, &Editor::region_fill_selection)));
2176         edit_items.push_back (MenuElem (_("Duplicate range"), bind (mem_fun(*this, &Editor::duplicate_dialog), false)));
2177         edit_items.push_back (MenuElem (_("Create chunk from range"), mem_fun(*this, &Editor::create_named_selection)));
2178         edit_items.push_back (SeparatorElem());
2179         edit_items.push_back (MenuElem (_("Consolidate range"), bind (mem_fun(*this, &Editor::bounce_range_selection), true, false)));
2180         edit_items.push_back (MenuElem (_("Consolidate range with processing"), bind (mem_fun(*this, &Editor::bounce_range_selection), true, true)));
2181         edit_items.push_back (MenuElem (_("Bounce range to region list"), bind (mem_fun(*this, &Editor::bounce_range_selection), false, false)));
2182         edit_items.push_back (MenuElem (_("Bounce range to region list with processing"), bind (mem_fun(*this, &Editor::bounce_range_selection), false, true)));
2183         edit_items.push_back (MenuElem (_("Export range"), mem_fun(*this, &Editor::export_range)));
2184 }
2185
2186         
2187 void
2188 Editor::add_dstream_context_items (Menu_Helpers::MenuList& edit_items)
2189 {
2190         using namespace Menu_Helpers;
2191
2192         /* Playback */
2193
2194         Menu *play_menu = manage (new Menu);
2195         MenuList& play_items = play_menu->items();
2196         play_menu->set_name ("ArdourContextMenu");
2197         
2198         play_items.push_back (MenuElem (_("Play from edit point"), mem_fun(*this, &Editor::play_from_edit_point)));
2199         play_items.push_back (MenuElem (_("Play from start"), mem_fun(*this, &Editor::play_from_start)));
2200         play_items.push_back (MenuElem (_("Play region"), mem_fun(*this, &Editor::play_selected_region)));
2201         play_items.push_back (SeparatorElem());
2202         play_items.push_back (MenuElem (_("Loop Region"), mem_fun(*this, &Editor::loop_selected_region)));
2203         
2204         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2205
2206         /* Selection */
2207
2208         Menu *select_menu = manage (new Menu);
2209         MenuList& select_items = select_menu->items();
2210         select_menu->set_name ("ArdourContextMenu");
2211         
2212         select_items.push_back (MenuElem (_("Select All in track"), bind (mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2213         select_items.push_back (MenuElem (_("Select All"), bind (mem_fun(*this, &Editor::select_all), Selection::Set)));
2214         select_items.push_back (MenuElem (_("Invert selection in track"), mem_fun(*this, &Editor::invert_selection_in_track)));
2215         select_items.push_back (MenuElem (_("Invert selection"), mem_fun(*this, &Editor::invert_selection)));
2216         select_items.push_back (SeparatorElem());
2217         select_items.push_back (MenuElem (_("Set range to loop range"), mem_fun(*this, &Editor::set_selection_from_loop)));
2218         select_items.push_back (MenuElem (_("Set range to punch range"), mem_fun(*this, &Editor::set_selection_from_punch)));
2219         select_items.push_back (SeparatorElem());
2220         select_items.push_back (MenuElem (_("Select All After Edit Point"), bind (mem_fun(*this, &Editor::select_all_selectables_using_edit), true)));
2221         select_items.push_back (MenuElem (_("Select All Before Edit Point"), bind (mem_fun(*this, &Editor::select_all_selectables_using_edit), false)));
2222         select_items.push_back (MenuElem (_("Select All After Playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2223         select_items.push_back (MenuElem (_("Select All Before Playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2224         select_items.push_back (MenuElem (_("Select All Between Playhead & Edit Point"), bind (mem_fun(*this, &Editor::select_all_selectables_between), false)));
2225         select_items.push_back (MenuElem (_("Select All Within Playhead & Edit Point"), bind (mem_fun(*this, &Editor::select_all_selectables_between), true)));
2226         select_items.push_back (MenuElem (_("Select Range Between Playhead & Edit Point"), mem_fun(*this, &Editor::select_range_between)));
2227
2228         select_items.push_back (SeparatorElem());
2229
2230         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2231
2232         /* Cut-n-Paste */
2233
2234         Menu *cutnpaste_menu = manage (new Menu);
2235         MenuList& cutnpaste_items = cutnpaste_menu->items();
2236         cutnpaste_menu->set_name ("ArdourContextMenu");
2237         
2238         cutnpaste_items.push_back (MenuElem (_("Cut"), mem_fun(*this, &Editor::cut)));
2239         cutnpaste_items.push_back (MenuElem (_("Copy"), mem_fun(*this, &Editor::copy)));
2240         cutnpaste_items.push_back (MenuElem (_("Paste"), bind (mem_fun(*this, &Editor::paste), 1.0f)));
2241
2242         cutnpaste_items.push_back (SeparatorElem());
2243
2244         cutnpaste_items.push_back (MenuElem (_("Align"), bind (mem_fun(*this, &Editor::align), ARDOUR::SyncPoint)));
2245         cutnpaste_items.push_back (MenuElem (_("Align Relative"), bind (mem_fun(*this, &Editor::align_relative), ARDOUR::SyncPoint)));
2246
2247         cutnpaste_items.push_back (SeparatorElem());
2248
2249         cutnpaste_items.push_back (MenuElem (_("Insert chunk"), bind (mem_fun(*this, &Editor::paste_named_selection), 1.0f)));
2250
2251         edit_items.push_back (MenuElem (_("Edit"), *cutnpaste_menu));
2252
2253         /* Adding new material */
2254         
2255         edit_items.push_back (SeparatorElem());
2256         edit_items.push_back (MenuElem (_("Insert Selected Region"), bind (mem_fun(*this, &Editor::insert_region_list_selection), 1.0f)));
2257         edit_items.push_back (MenuElem (_("Insert Existing Media"), bind (mem_fun(*this, &Editor::add_external_audio_action), ImportToTrack)));
2258
2259         /* Nudge track */
2260
2261         Menu *nudge_menu = manage (new Menu());
2262         MenuList& nudge_items = nudge_menu->items();
2263         nudge_menu->set_name ("ArdourContextMenu");
2264         
2265         edit_items.push_back (SeparatorElem());
2266         nudge_items.push_back (MenuElem (_("Nudge entire track fwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, true))));
2267         nudge_items.push_back (MenuElem (_("Nudge track after edit point fwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, true))));
2268         nudge_items.push_back (MenuElem (_("Nudge entire track bwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, false))));
2269         nudge_items.push_back (MenuElem (_("Nudge track after edit point bwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, false))));
2270
2271         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2272 }
2273
2274 void
2275 Editor::add_bus_context_items (Menu_Helpers::MenuList& edit_items)
2276 {
2277         using namespace Menu_Helpers;
2278
2279         /* Playback */
2280
2281         Menu *play_menu = manage (new Menu);
2282         MenuList& play_items = play_menu->items();
2283         play_menu->set_name ("ArdourContextMenu");
2284         
2285         play_items.push_back (MenuElem (_("Play from edit point"), mem_fun(*this, &Editor::play_from_edit_point)));
2286         play_items.push_back (MenuElem (_("Play from start"), mem_fun(*this, &Editor::play_from_start)));
2287         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2288
2289         /* Selection */
2290
2291         Menu *select_menu = manage (new Menu);
2292         MenuList& select_items = select_menu->items();
2293         select_menu->set_name ("ArdourContextMenu");
2294         
2295         select_items.push_back (MenuElem (_("Select All in track"), bind (mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2296         select_items.push_back (MenuElem (_("Select All"), bind (mem_fun(*this, &Editor::select_all), Selection::Set)));
2297         select_items.push_back (MenuElem (_("Invert selection in track"), mem_fun(*this, &Editor::invert_selection_in_track)));
2298         select_items.push_back (MenuElem (_("Invert selection"), mem_fun(*this, &Editor::invert_selection)));
2299         select_items.push_back (SeparatorElem());
2300         select_items.push_back (MenuElem (_("Select all after edit point"), bind (mem_fun(*this, &Editor::select_all_selectables_using_edit), true)));
2301         select_items.push_back (MenuElem (_("Select all before edit point"), bind (mem_fun(*this, &Editor::select_all_selectables_using_edit), false)));
2302         select_items.push_back (MenuElem (_("Select all after playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2303         select_items.push_back (MenuElem (_("Select all before playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2304
2305         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2306
2307         /* Cut-n-Paste */
2308
2309         Menu *cutnpaste_menu = manage (new Menu);
2310         MenuList& cutnpaste_items = cutnpaste_menu->items();
2311         cutnpaste_menu->set_name ("ArdourContextMenu");
2312         
2313         cutnpaste_items.push_back (MenuElem (_("Cut"), mem_fun(*this, &Editor::cut)));
2314         cutnpaste_items.push_back (MenuElem (_("Copy"), mem_fun(*this, &Editor::copy)));
2315         cutnpaste_items.push_back (MenuElem (_("Paste"), bind (mem_fun(*this, &Editor::paste), 1.0f)));
2316
2317         Menu *nudge_menu = manage (new Menu());
2318         MenuList& nudge_items = nudge_menu->items();
2319         nudge_menu->set_name ("ArdourContextMenu");
2320         
2321         edit_items.push_back (SeparatorElem());
2322         nudge_items.push_back (MenuElem (_("Nudge entire track fwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, true))));
2323         nudge_items.push_back (MenuElem (_("Nudge track after edit point fwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, true))));
2324         nudge_items.push_back (MenuElem (_("Nudge entire track bwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, false))));
2325         nudge_items.push_back (MenuElem (_("Nudge track after edit point bwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, false))));
2326
2327         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2328 }
2329
2330 void
2331 Editor::set_snap_to (SnapType st)
2332 {
2333         unsigned int snap_ind = (unsigned int)st;
2334
2335         snap_type = st;
2336         
2337         if (snap_ind > snap_type_strings.size() - 1) {
2338                 snap_ind = 0;
2339                 snap_type = (SnapType)snap_ind;
2340         }
2341         
2342         string str = snap_type_strings[snap_ind];
2343
2344         if (str != snap_type_selector.get_active_text()) {
2345                 snap_type_selector.set_active_text (str);
2346         }
2347
2348         instant_save ();
2349
2350         switch (snap_type) {
2351         case SnapToAThirtysecondBeat:
2352         case SnapToASixteenthBeat:
2353         case SnapToAEighthBeat:
2354         case SnapToAQuarterBeat:
2355         case SnapToAThirdBeat:
2356                 compute_bbt_ruler_scale (leftmost_frame, leftmost_frame + current_page_frames());
2357                 update_tempo_based_rulers ();
2358                 break;
2359
2360         case SnapToRegionStart:
2361         case SnapToRegionEnd:
2362         case SnapToRegionSync:
2363         case SnapToRegionBoundary:
2364                 build_region_boundary_cache ();
2365                 break;
2366
2367         default:
2368                 /* relax */
2369                 break;
2370     }
2371 }
2372
2373 void
2374 Editor::set_snap_mode (SnapMode mode)
2375 {
2376         snap_mode = mode;
2377         string str = snap_mode_strings[(int)mode];
2378
2379         if (str != snap_mode_selector.get_active_text ()) {
2380                 snap_mode_selector.set_active_text (str);
2381         }
2382
2383         instant_save ();
2384 }
2385 void
2386 Editor::set_edit_point_preference (EditPoint ep, bool force)
2387 {
2388         bool changed = (_edit_point != ep);
2389
2390         _edit_point = ep;
2391         string str = edit_point_strings[(int)ep];
2392
2393         if (str != edit_point_selector.get_active_text ()) {
2394                 edit_point_selector.set_active_text (str);
2395         }
2396
2397         set_canvas_cursor ();
2398
2399         if (!force && !changed) {
2400                 return;
2401         }
2402
2403         switch (zoom_focus) {
2404         case ZoomFocusMouse:
2405         case ZoomFocusPlayhead:
2406         case ZoomFocusEdit:
2407                 switch (_edit_point) {
2408                 case EditAtMouse:
2409                         set_zoom_focus (ZoomFocusMouse);
2410                         break;
2411                 case EditAtPlayhead:
2412                         set_zoom_focus (ZoomFocusPlayhead);
2413                         break;
2414                 case EditAtSelectedMarker:
2415                         set_zoom_focus (ZoomFocusEdit);
2416                         break;
2417                 }
2418                 break;
2419         default:
2420                 break;
2421         }
2422
2423         const char* action=NULL;
2424
2425         switch (_edit_point) {
2426         case EditAtPlayhead:
2427                 action = "edit-at-playhead";
2428                 break;
2429         case EditAtSelectedMarker:
2430                 action = "edit-at-marker";
2431                 break;
2432         case EditAtMouse:
2433                 action = "edit-at-mouse";
2434                 break;
2435         }
2436
2437         Glib::RefPtr<Action> act = ActionManager::get_action ("Editor", action);
2438         if (act) {
2439                 Glib::RefPtr<RadioAction>::cast_dynamic(act)->set_active (true);
2440         }
2441
2442         nframes64_t foo;
2443         bool in_track_canvas;
2444
2445         if (!mouse_frame (foo, in_track_canvas)) {
2446                 in_track_canvas = false;
2447         }
2448
2449         reset_canvas_action_sensitivity (in_track_canvas);
2450
2451         instant_save ();
2452 }
2453
2454 int
2455 Editor::set_state (const XMLNode& node)
2456 {
2457         const XMLProperty* prop;
2458         XMLNode* geometry;
2459         int x, y, xoff, yoff;
2460         Gdk::Geometry g;
2461
2462         if ((prop = node.property ("id")) != 0) {
2463                 _id = prop->value ();
2464         }
2465
2466         g.base_width = default_width;
2467         g.base_height = default_height;
2468         x = 1;
2469         y = 1;
2470         xoff = 0;
2471         yoff = 21;
2472
2473         if ((geometry = find_named_node (node, "geometry")) != 0) {
2474
2475                 XMLProperty* prop;
2476
2477                 if ((prop = geometry->property("x_size")) == 0) {
2478                         prop = geometry->property ("x-size");
2479                 }
2480                 if (prop) {
2481                         g.base_width = atoi(prop->value());
2482                 }
2483                 if ((prop = geometry->property("y_size")) == 0) {
2484                         prop = geometry->property ("y-size");
2485                 }
2486                 if (prop) {
2487                         g.base_height = atoi(prop->value());
2488                 }
2489
2490                 if ((prop = geometry->property ("x_pos")) == 0) {
2491                         prop = geometry->property ("x-pos");
2492                 }
2493                 if (prop) {
2494                         x = atoi (prop->value());
2495
2496                 }
2497                 if ((prop = geometry->property ("y_pos")) == 0) {
2498                         prop = geometry->property ("y-pos");
2499                 }
2500                 if (prop) {
2501                         y = atoi (prop->value());
2502                 }
2503
2504                 if ((prop = geometry->property ("x_off")) == 0) {
2505                         prop = geometry->property ("x-off");
2506                 }
2507                 if (prop) {
2508                         xoff = atoi (prop->value());
2509                 }
2510                 if ((prop = geometry->property ("y_off")) == 0) {
2511                         prop = geometry->property ("y-off");
2512                 }
2513                 if (prop) {
2514                         yoff = atoi (prop->value());
2515                 }
2516         }
2517
2518         set_default_size (g.base_width, g.base_height);
2519         move (x, y);
2520
2521         if (session && (prop = node.property ("playhead"))) {
2522                 nframes64_t pos = atol (prop->value().c_str());
2523                 playhead_cursor->set_position (pos);
2524         } else {
2525                 playhead_cursor->set_position (0);
2526
2527                 /* reset_x_origin() doesn't work right here, since the old
2528                    position may be zero already, and it does nothing in such
2529                    circumstances.
2530                 */
2531                 
2532                 leftmost_frame = 0;
2533                 horizontal_adjustment.set_value (0);
2534         }
2535
2536         if ((prop = node.property ("mixer-width"))) {
2537                 editor_mixer_strip_width = Width (string_2_enum (prop->value(), editor_mixer_strip_width));
2538         }
2539
2540         if ((prop = node.property ("zoom-focus"))) {
2541                 set_zoom_focus ((ZoomFocus) atoi (prop->value()));
2542         }
2543
2544         if ((prop = node.property ("zoom"))) {
2545                 reset_zoom (PBD::atof (prop->value()));
2546         }
2547
2548         if ((prop = node.property ("snap-to"))) {
2549                 set_snap_to ((SnapType) atoi (prop->value()));
2550         }
2551
2552         if ((prop = node.property ("snap-mode"))) {
2553                 set_snap_mode ((SnapMode) atoi (prop->value()));
2554         }
2555
2556         if ((prop = node.property ("edit-point"))) {
2557                 set_edit_point_preference ((EditPoint) string_2_enum (prop->value(), _edit_point), true);
2558         }
2559
2560         if ((prop = node.property ("mouse-mode"))) {
2561                 MouseMode m = str2mousemode(prop->value());
2562                 mouse_mode = MouseMode ((int) m + 1); /* lie, force mode switch */
2563                 set_mouse_mode (m, true);
2564         } else {
2565                 mouse_mode = MouseGain; /* lie, to force the mode switch */
2566                 set_mouse_mode (MouseObject, true);
2567         }
2568
2569         if ((prop = node.property ("show-waveforms"))) {
2570                 bool yn = (prop->value() == "yes");
2571                 _show_waveforms = !yn;
2572                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-waveform-visible"));
2573                 if (act) {
2574                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2575                         /* do it twice to force the change */
2576                         tact->set_active (!yn);
2577                         tact->set_active (yn);
2578                 }
2579         }
2580
2581         if ((prop = node.property ("show-waveforms-recording"))) {
2582                 bool yn = (prop->value() == "yes");
2583                 _show_waveforms_recording = !yn;
2584                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleWaveformsWhileRecording"));
2585                 if (act) {
2586                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2587                         /* do it twice to force the change */
2588                         tact->set_active (!yn);
2589                         tact->set_active (yn);
2590                 }
2591         }
2592         
2593         if ((prop = node.property ("show-measures"))) {
2594                 bool yn = (prop->value() == "yes");
2595                 _show_measures = !yn;
2596                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleMeasureVisibility"));
2597                 if (act) {
2598                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2599                         /* do it twice to force the change */
2600                         tact->set_active (!yn);
2601                         tact->set_active (yn);
2602                 }
2603         }
2604
2605         if ((prop = node.property ("follow-playhead"))) {
2606                 bool yn = (prop->value() == "yes");
2607                 set_follow_playhead (yn);
2608                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
2609                 if (act) {
2610                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2611                         if (tact->get_active() != yn) {
2612                                 tact->set_active (yn);
2613                         }
2614                 }
2615         }
2616
2617         if ((prop = node.property ("region-list-sort-type"))) {
2618                 region_list_sort_type = (Editing::RegionListSortType) -1; // force change 
2619                 reset_region_list_sort_type(str2regionlistsorttype(prop->value()));
2620         }
2621
2622         if ((prop = node.property ("xfades-visible"))) {
2623                 bool yn = (prop->value() == "yes");
2624                 _xfade_visibility = !yn;
2625                 // set_xfade_visibility (yn);
2626         }
2627
2628         if ((prop = node.property ("show-editor-mixer"))) {
2629
2630                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2631                 if (act) {
2632
2633                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2634                         bool yn = (prop->value() == X_("yes"));
2635
2636                         /* do it twice to force the change */
2637                         
2638                         tact->set_active (!yn);
2639                         tact->set_active (yn);
2640                 }
2641         }
2642         
2643         if ((prop = node.property ("show-editor-list"))) {
2644
2645                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-list"));
2646                 assert(act);
2647                 if (act) {
2648
2649                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2650                         bool yn = (prop->value() == X_("yes"));
2651
2652                         /* do it twice to force the change */
2653                         
2654                         tact->set_active (!yn);
2655                         tact->set_active (yn);
2656                 }
2657         }
2658
2659
2660         return 0;
2661 }
2662
2663 XMLNode&
2664 Editor::get_state ()
2665 {
2666         XMLNode* node = new XMLNode ("Editor");
2667         char buf[32];
2668
2669         _id.print (buf, sizeof (buf));
2670         node->add_property ("id", buf);
2671         
2672         if (is_realized()) {
2673                 Glib::RefPtr<Gdk::Window> win = get_window();
2674                 
2675                 int x, y, xoff, yoff, width, height;
2676                 win->get_root_origin(x, y);
2677                 win->get_position(xoff, yoff);
2678                 win->get_size(width, height);
2679                 
2680                 XMLNode* geometry = new XMLNode ("geometry");
2681
2682                 snprintf(buf, sizeof(buf), "%d", width);
2683                 geometry->add_property("x-size", string(buf));
2684                 snprintf(buf, sizeof(buf), "%d", height);
2685                 geometry->add_property("y-size", string(buf));
2686                 snprintf(buf, sizeof(buf), "%d", x);
2687                 geometry->add_property("x-pos", string(buf));
2688                 snprintf(buf, sizeof(buf), "%d", y);
2689                 geometry->add_property("y-pos", string(buf));
2690                 snprintf(buf, sizeof(buf), "%d", xoff);
2691                 geometry->add_property("x-off", string(buf));
2692                 snprintf(buf, sizeof(buf), "%d", yoff);
2693                 geometry->add_property("y-off", string(buf));
2694                 snprintf(buf,sizeof(buf), "%d",gtk_paned_get_position (static_cast<Paned*>(&edit_pane)->gobj()));
2695                 geometry->add_property("edit_pane_pos", string(buf));
2696
2697                 node->add_child_nocopy (*geometry);
2698         }
2699
2700         maybe_add_mixer_strip_width (*node);
2701         
2702         snprintf (buf, sizeof(buf), "%d", (int) zoom_focus);
2703         node->add_property ("zoom-focus", buf);
2704         snprintf (buf, sizeof(buf), "%f", frames_per_unit);
2705         node->add_property ("zoom", buf);
2706         snprintf (buf, sizeof(buf), "%d", (int) snap_type);
2707         node->add_property ("snap-to", buf);
2708         snprintf (buf, sizeof(buf), "%d", (int) snap_mode);
2709         node->add_property ("snap-mode", buf);
2710
2711         node->add_property ("edit-point", enum_2_string (_edit_point));
2712
2713         snprintf (buf, sizeof (buf), "%" PRIi64, playhead_cursor->current_frame);
2714         node->add_property ("playhead", buf);
2715
2716         node->add_property ("show-waveforms", _show_waveforms ? "yes" : "no");
2717         node->add_property ("show-waveforms-recording", _show_waveforms_recording ? "yes" : "no");
2718         node->add_property ("show-measures", _show_measures ? "yes" : "no");
2719         node->add_property ("follow-playhead", _follow_playhead ? "yes" : "no");
2720         node->add_property ("xfades-visible", _xfade_visibility ? "yes" : "no");
2721         node->add_property ("region-list-sort-type", enum2str(region_list_sort_type));
2722         node->add_property ("mouse-mode", enum2str(mouse_mode));
2723         
2724         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2725         if (act) {
2726                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2727                 node->add_property (X_("show-editor-mixer"), tact->get_active() ? "yes" : "no");
2728         }
2729         
2730         act = ActionManager::get_action (X_("Editor"), X_("show-editor-list"));
2731         if (act) {
2732                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2733                 node->add_property (X_("show-editor-list"), tact->get_active() ? "yes" : "no");
2734         }
2735
2736         return *node;
2737 }
2738
2739
2740
2741 /** @param y y offset from the top of all trackviews.
2742  *  @return pair: TimeAxisView that y is over, layer index.
2743  *  TimeAxisView may be 0.  Layer index is the layer number if the TimeAxisView is valid and is
2744  *  in stacked region display mode, otherwise 0.
2745  */
2746 std::pair<TimeAxisView *, layer_t>
2747 Editor::trackview_by_y_position (double y)
2748 {
2749         for (TrackViewList::iterator iter = track_views.begin(); iter != track_views.end(); ++iter) {
2750
2751                 std::pair<TimeAxisView*, int> const r = (*iter)->covers_y_position (y);
2752                 if (r.first) {
2753                         return r;
2754                 }
2755         }
2756
2757         return std::make_pair ( (TimeAxisView *) 0, 0);
2758 }
2759
2760 void
2761 Editor::snap_to (nframes64_t& start, int32_t direction, bool for_mark)
2762 {
2763         if (!session || snap_mode == SnapOff) {
2764                 return;
2765         }
2766
2767         snap_to_internal (start, direction, for_mark);
2768 }
2769
2770 void
2771 Editor::snap_to_internal (nframes64_t& start, int32_t direction, bool for_mark)
2772 {
2773         Location* before = 0;
2774         Location* after = 0;
2775
2776         const nframes64_t one_second = session->frame_rate();
2777         const nframes64_t one_minute = session->frame_rate() * 60;
2778         const nframes64_t one_smpte_second = (nframes64_t)(rint(session->smpte_frames_per_second()) * session->frames_per_smpte_frame());
2779         nframes64_t one_smpte_minute = (nframes64_t)(rint(session->smpte_frames_per_second()) * session->frames_per_smpte_frame() * 60);
2780         nframes64_t presnap = start;
2781
2782         switch (snap_type) {
2783         case SnapToCDFrame:
2784                 if (((direction == 0) && (start % (one_second/75) > (one_second/75) / 2)) || (direction > 0)) {
2785                         start = (nframes64_t) ceil ((double) start / (one_second / 75)) * (one_second / 75);
2786                 } else {
2787                         start = (nframes64_t) floor ((double) start / (one_second / 75)) * (one_second / 75);
2788                 }
2789                 break;
2790
2791         case SnapToSMPTEFrame:
2792                 if (((direction == 0) && (fmod((double)start, (double)session->frames_per_smpte_frame()) > (session->frames_per_smpte_frame() / 2))) || (direction > 0)) {
2793                         start = (nframes64_t) (ceil ((double) start / session->frames_per_smpte_frame()) * session->frames_per_smpte_frame());
2794                 } else {
2795                         start = (nframes64_t) (floor ((double) start / session->frames_per_smpte_frame()) *  session->frames_per_smpte_frame());
2796                 }
2797                 break;
2798
2799         case SnapToSMPTESeconds:
2800                 if (session->smpte_offset_negative())
2801                 {
2802                         start += session->smpte_offset ();
2803                 } else {
2804                         start -= session->smpte_offset ();
2805                 }    
2806                 if (((direction == 0) && (start % one_smpte_second > one_smpte_second / 2)) || direction > 0) {
2807                         start = (nframes64_t) ceil ((double) start / one_smpte_second) * one_smpte_second;
2808                 } else {
2809                         start = (nframes64_t) floor ((double) start / one_smpte_second) * one_smpte_second;
2810                 }
2811                 
2812                 if (session->smpte_offset_negative())
2813                 {
2814                         start -= session->smpte_offset ();
2815                 } else {
2816                         start += session->smpte_offset ();
2817                 }
2818                 break;
2819                 
2820         case SnapToSMPTEMinutes:
2821                 if (session->smpte_offset_negative())
2822                 {
2823                         start += session->smpte_offset ();
2824                 } else {
2825                         start -= session->smpte_offset ();
2826                 }
2827                 if (((direction == 0) && (start % one_smpte_minute > one_smpte_minute / 2)) || direction > 0) {
2828                         start = (nframes64_t) ceil ((double) start / one_smpte_minute) * one_smpte_minute;
2829                 } else {
2830                         start = (nframes64_t) floor ((double) start / one_smpte_minute) * one_smpte_minute;
2831                 }
2832                 if (session->smpte_offset_negative())
2833                 {
2834                         start -= session->smpte_offset ();
2835                 } else {
2836                         start += session->smpte_offset ();
2837                 }
2838                 break;
2839                 
2840         case SnapToSeconds:
2841                 if (((direction == 0) && (start % one_second > one_second / 2)) || (direction > 0)) {
2842                         start = (nframes64_t) ceil ((double) start / one_second) * one_second;
2843                 } else {
2844                         start = (nframes64_t) floor ((double) start / one_second) * one_second;
2845                 }
2846                 break;
2847                 
2848         case SnapToMinutes:
2849                 if (((direction == 0) && (start % one_minute > one_minute / 2)) || (direction > 0)) {
2850                         start = (nframes64_t) ceil ((double) start / one_minute) * one_minute;
2851                 } else {
2852                         start = (nframes64_t) floor ((double) start / one_minute) * one_minute;
2853                 }
2854                 break;
2855
2856         case SnapToBar:
2857                 start = session->tempo_map().round_to_bar (start, direction);
2858                 break;
2859
2860         case SnapToBeat:
2861                 start = session->tempo_map().round_to_beat (start, direction);
2862                 break;
2863
2864         case SnapToAThirtysecondBeat:
2865                 start = session->tempo_map().round_to_beat_subdivision (start, 32);
2866                 break;
2867
2868         case SnapToASixteenthBeat:
2869                 start = session->tempo_map().round_to_beat_subdivision (start, 16);
2870                 break;
2871
2872         case SnapToAEighthBeat:
2873                 start = session->tempo_map().round_to_beat_subdivision (start, 8);
2874                 break;
2875
2876         case SnapToAQuarterBeat:
2877                 start = session->tempo_map().round_to_beat_subdivision (start, 4);
2878                 break;
2879
2880         case SnapToAThirdBeat:
2881                 start = session->tempo_map().round_to_beat_subdivision (start, 3);
2882                 break;
2883
2884         case SnapToMark:
2885                 if (for_mark) {
2886                         return;
2887                 }
2888
2889                 before = session->locations()->first_location_before (start);
2890                 after = session->locations()->first_location_after (start);
2891
2892                 if (direction < 0) {
2893                         if (before) {
2894                                 start = before->start();
2895                         } else {
2896                                 start = 0;
2897                         }
2898                 } else if (direction > 0) {
2899                         if (after) {
2900                                 start = after->start();
2901                         } else {
2902                                 start = session->current_end_frame();
2903                         }
2904                 } else {
2905                         if (before) {
2906                                 if (after) {
2907                                         /* find nearest of the two */
2908                                         if ((start - before->start()) < (after->start() - start)) {
2909                                                 start = before->start();
2910                                         } else {
2911                                                 start = after->start();
2912                                         }
2913                                 } else {
2914                                         start = before->start();
2915                                 }
2916                         } else if (after) {
2917                                 start = after->start();
2918                         } else {
2919                                 /* relax */
2920                         }
2921                 }
2922                 break;
2923
2924         case SnapToRegionStart:
2925         case SnapToRegionEnd:
2926         case SnapToRegionSync:
2927         case SnapToRegionBoundary:
2928                 if (!region_boundary_cache.empty()) {
2929                         vector<nframes64_t>::iterator i;
2930
2931                         if (direction > 0) {
2932                                 i = std::upper_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2933                         } else {
2934                                 i = std::lower_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2935                         }
2936                         
2937                         if (i != region_boundary_cache.end()) {
2938
2939                                 /* lower bound doesn't quite to the right thing for our purposes */
2940
2941                                 if (direction < 0 && i != region_boundary_cache.begin()) {
2942                                         --i;
2943                                 }
2944
2945                                 start = *i;
2946
2947                         } else {
2948                                 start = region_boundary_cache.back();
2949                         }
2950                 } 
2951                 break;
2952         }
2953
2954         switch (snap_mode) {
2955         case SnapNormal:
2956                 return;                 
2957                 
2958         case SnapMagnetic:
2959                 
2960                 if (presnap > start) {
2961                         if (presnap > (start + unit_to_frame(snap_threshold))) {
2962                                 start = presnap;
2963                         }
2964                         
2965                 } else if (presnap < start) {
2966                         if (presnap < (start - unit_to_frame(snap_threshold))) {
2967                                 start = presnap;
2968                         }
2969                 }
2970                 
2971         default:
2972                 /* handled at entry */
2973                 return;
2974                 
2975         }
2976 }
2977
2978 double
2979 Editor::snap_length_beats (nframes64_t start)
2980 {
2981         if (!session) {
2982                 return 1.0;
2983         }
2984
2985         /* FIXME: This could/should also work with non-tempo based snap settings (ie seconds) */
2986
2987         switch (snap_type) {
2988         case SnapToBar:
2989                 return session->tempo_map().meter_at(start).beats_per_bar();
2990
2991         case SnapToBeat:
2992                 return 1.0;
2993
2994         case SnapToAThirtysecondBeat:
2995                 return 1.0 / (double)32.0;
2996                 break;
2997
2998         case SnapToASixteenthBeat:
2999                 return 1.0 / (double)16.0;
3000                 break;
3001
3002         case SnapToAEighthBeat:
3003                 return 1.0 / (double)8.0;
3004                 break;
3005
3006         case SnapToAQuarterBeat:
3007                 return 1.0 / (double)4.0;
3008                 break;
3009
3010         case SnapToAThirdBeat:
3011                 return 1.0 / (double)3.0;
3012
3013         default:
3014                 return 1.0;
3015         }
3016 }
3017
3018 void
3019 Editor::setup_toolbar ()
3020 {
3021         string pixmap_path;
3022
3023         /* Mode Buttons (tool selection) */
3024
3025         vector<ToggleButton *> mouse_mode_buttons;
3026
3027         mouse_move_button.add (*(manage (new Image (::get_icon("tool_object")))));
3028         mouse_move_button.set_relief(Gtk::RELIEF_NONE);
3029         mouse_mode_buttons.push_back (&mouse_move_button);
3030
3031         if (!Profile->get_sae()) {
3032                 mouse_select_button.add (*(manage (new Image (get_xpm("tool_range.xpm")))));
3033                 mouse_select_button.set_relief(Gtk::RELIEF_NONE);
3034                 mouse_mode_buttons.push_back (&mouse_select_button);
3035
3036                 mouse_gain_button.add (*(manage (new Image (::get_icon("tool_gain")))));
3037                 mouse_gain_button.set_relief(Gtk::RELIEF_NONE);
3038                 mouse_mode_buttons.push_back (&mouse_gain_button);
3039         }
3040
3041         mouse_zoom_button.add (*(manage (new Image (::get_icon("tool_zoom")))));
3042         mouse_zoom_button.set_relief(Gtk::RELIEF_NONE);
3043         mouse_mode_buttons.push_back (&mouse_zoom_button);
3044         mouse_timefx_button.add (*(manage (new Image (::get_icon("tool_stretch")))));
3045         mouse_timefx_button.set_relief(Gtk::RELIEF_NONE);
3046         mouse_mode_buttons.push_back (&mouse_timefx_button);
3047         mouse_audition_button.add (*(manage (new Image (::get_icon("tool_audition")))));
3048         mouse_audition_button.set_relief(Gtk::RELIEF_NONE);
3049         mouse_note_button.add (*(manage (new Image (::get_icon("tool_note")))));
3050         mouse_note_button.set_relief(Gtk::RELIEF_NONE);
3051         mouse_mode_buttons.push_back (&mouse_note_button);
3052         mouse_mode_buttons.push_back (&mouse_audition_button);
3053         
3054         mouse_mode_button_set = new GroupedButtons (mouse_mode_buttons);
3055
3056         HBox* mode_box = manage(new HBox);
3057         mode_box->set_border_width (2);
3058         mode_box->set_spacing(4);
3059         mouse_mode_button_box.set_spacing(1);
3060         mouse_mode_button_box.pack_start(mouse_move_button, true, true);
3061         if (!Profile->get_sae()) {
3062                 mouse_mode_button_box.pack_start(mouse_select_button, true, true);
3063         }
3064         mouse_mode_button_box.pack_start(mouse_zoom_button, true, true);
3065         if (!Profile->get_sae()) {
3066                 mouse_mode_button_box.pack_start(mouse_gain_button, true, true);
3067         }
3068         mouse_mode_button_box.pack_start(mouse_timefx_button, true, true);
3069         mouse_mode_button_box.pack_start(mouse_audition_button, true, true);
3070         mouse_mode_button_box.pack_start(mouse_note_button, true, true);
3071         mouse_mode_button_box.set_homogeneous(true);
3072
3073         vector<string> edit_mode_strings;
3074         edit_mode_strings.push_back (edit_mode_to_string (Slide));
3075         if (!Profile->get_sae()) {
3076                 edit_mode_strings.push_back (edit_mode_to_string (Splice));
3077         }
3078         edit_mode_strings.push_back (edit_mode_to_string (Lock));
3079
3080         edit_mode_selector.set_name ("EditModeSelector");
3081         set_popdown_strings (edit_mode_selector, edit_mode_strings, true);
3082         edit_mode_selector.signal_changed().connect (mem_fun(*this, &Editor::edit_mode_selection_done));
3083
3084         mode_box->pack_start(edit_mode_selector);
3085         mode_box->pack_start(mouse_mode_button_box);
3086         
3087         mouse_mode_tearoff = manage (new TearOff (*mode_box));
3088         mouse_mode_tearoff->set_name ("MouseModeBase");
3089
3090         if (Profile->get_sae()) {
3091                 mouse_mode_tearoff->set_can_be_torn_off (false);
3092         }
3093
3094         mouse_mode_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
3095                                                   &mouse_mode_tearoff->tearoff_window()));
3096         mouse_mode_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
3097                                                   &mouse_mode_tearoff->tearoff_window(), 1));
3098         mouse_mode_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
3099                                                   &mouse_mode_tearoff->tearoff_window()));
3100         mouse_mode_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
3101                                                    &mouse_mode_tearoff->tearoff_window(), 1));
3102
3103         mouse_move_button.set_name ("MouseModeButton");
3104         mouse_select_button.set_name ("MouseModeButton");
3105         mouse_gain_button.set_name ("MouseModeButton");
3106         mouse_zoom_button.set_name ("MouseModeButton");
3107         mouse_timefx_button.set_name ("MouseModeButton");
3108         mouse_audition_button.set_name ("MouseModeButton");
3109         mouse_note_button.set_name ("MouseModeButton");
3110
3111         ARDOUR_UI::instance()->tooltips().set_tip (mouse_move_button, _("Select/Move Objects"));
3112         ARDOUR_UI::instance()->tooltips().set_tip (mouse_select_button, _("Select/Move Ranges"));
3113         ARDOUR_UI::instance()->tooltips().set_tip (mouse_gain_button, _("Draw Gain Automation"));
3114         ARDOUR_UI::instance()->tooltips().set_tip (mouse_zoom_button, _("Select Zoom Range"));
3115         ARDOUR_UI::instance()->tooltips().set_tip (mouse_timefx_button, _("Stretch/Shrink Regions"));
3116         ARDOUR_UI::instance()->tooltips().set_tip (mouse_audition_button, _("Listen to Specific Regions"));
3117         ARDOUR_UI::instance()->tooltips().set_tip (mouse_note_button, _("Edit MIDI Notes"));
3118
3119         mouse_move_button.unset_flags (CAN_FOCUS);
3120         mouse_select_button.unset_flags (CAN_FOCUS);
3121         mouse_gain_button.unset_flags (CAN_FOCUS);
3122         mouse_zoom_button.unset_flags (CAN_FOCUS);
3123         mouse_timefx_button.unset_flags (CAN_FOCUS);
3124         mouse_audition_button.unset_flags (CAN_FOCUS);
3125         mouse_note_button.unset_flags (CAN_FOCUS);
3126
3127         mouse_select_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseRange));
3128         mouse_select_button.signal_button_release_event().connect (mem_fun(*this, &Editor::mouse_select_button_release));
3129
3130         mouse_move_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseObject));
3131         mouse_gain_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseGain));
3132         mouse_zoom_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseZoom));
3133         mouse_timefx_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseTimeFX));
3134         mouse_audition_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseAudition));
3135         mouse_note_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseNote));
3136
3137         // mouse_move_button.set_active (true);
3138         
3139
3140         /* Zoom */
3141         
3142         zoom_box.set_spacing (1);
3143         zoom_box.set_border_width (0);
3144
3145         zoom_in_button.set_name ("EditorTimeButton");
3146         zoom_in_button.set_size_request(-1,16);
3147         zoom_in_button.add (*(manage (new Image (::get_icon("zoom_in")))));
3148         zoom_in_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::temporal_zoom_step), false));
3149         ARDOUR_UI::instance()->tooltips().set_tip (zoom_in_button, _("Zoom In"));
3150         
3151         zoom_out_button.set_name ("EditorTimeButton");
3152         zoom_out_button.set_size_request(-1,16);
3153         zoom_out_button.add (*(manage (new Image (::get_icon("zoom_out")))));
3154         zoom_out_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::temporal_zoom_step), true));
3155         ARDOUR_UI::instance()->tooltips().set_tip (zoom_out_button, _("Zoom Out"));
3156
3157         zoom_out_full_button.set_name ("EditorTimeButton");
3158         zoom_out_full_button.set_size_request(-1,16);
3159         zoom_out_full_button.add (*(manage (new Image (::get_icon("zoom_full")))));
3160         zoom_out_full_button.signal_clicked().connect (mem_fun(*this, &Editor::temporal_zoom_session));
3161         ARDOUR_UI::instance()->tooltips().set_tip (zoom_out_full_button, _("Zoom to Session"));
3162
3163         zoom_focus_selector.set_name ("ZoomFocusSelector");
3164         set_popdown_strings (zoom_focus_selector, zoom_focus_strings, true);
3165         zoom_focus_selector.signal_changed().connect (mem_fun(*this, &Editor::zoom_focus_selection_done));
3166         ARDOUR_UI::instance()->tooltips().set_tip (zoom_focus_selector, _("Zoom focus"));
3167
3168         zoom_box.pack_start (zoom_focus_selector, true, true);
3169         zoom_box.pack_start (zoom_out_button, false, false);
3170         zoom_box.pack_start (zoom_in_button, false, false);
3171         zoom_box.pack_start (zoom_out_full_button, false, false);
3172
3173         snap_box.set_spacing (1);
3174         snap_box.set_border_width (2);
3175
3176         snap_type_selector.set_name ("SnapTypeSelector");
3177         set_popdown_strings (snap_type_selector, snap_type_strings, true);
3178         snap_type_selector.signal_changed().connect (mem_fun(*this, &Editor::snap_type_selection_done));
3179         ARDOUR_UI::instance()->tooltips().set_tip (snap_type_selector, _("Snap/Grid Units"));
3180
3181         snap_mode_selector.set_name ("SnapModeSelector");
3182         set_popdown_strings (snap_mode_selector, snap_mode_strings, true);
3183         snap_mode_selector.signal_changed().connect (mem_fun(*this, &Editor::snap_mode_selection_done));
3184         ARDOUR_UI::instance()->tooltips().set_tip (snap_mode_selector, _("Snap/Grid Mode"));
3185
3186         edit_point_selector.set_name ("EditPointSelector");
3187         set_popdown_strings (edit_point_selector, edit_point_strings, true);
3188         edit_point_selector.signal_changed().connect (mem_fun(*this, &Editor::edit_point_selection_done));
3189         ARDOUR_UI::instance()->tooltips().set_tip (edit_point_selector, _("Edit point"));
3190
3191         snap_box.pack_start (edit_point_clock, false, false);
3192         snap_box.pack_start (snap_mode_selector, false, false);
3193         snap_box.pack_start (snap_type_selector, false, false);
3194         snap_box.pack_start (edit_point_selector, false, false);
3195
3196         /* Nudge */
3197
3198         HBox *nudge_box = manage (new HBox);
3199         nudge_box->set_spacing(1);
3200         nudge_box->set_border_width (2);
3201
3202         nudge_forward_button.signal_button_release_event().connect (mem_fun(*this, &Editor::nudge_forward_release), false);
3203         nudge_backward_button.signal_button_release_event().connect (mem_fun(*this, &Editor::nudge_backward_release), false);
3204
3205         nudge_box->pack_start (nudge_backward_button, false, false);
3206         nudge_box->pack_start (nudge_forward_button, false, false);
3207         nudge_box->pack_start (nudge_clock, false, false);
3208
3209
3210         /* Pack everything in... */
3211
3212         HBox* hbox = manage (new HBox);
3213         hbox->set_spacing(10);
3214
3215         tools_tearoff = manage (new TearOff (*hbox));
3216         tools_tearoff->set_name ("MouseModeBase");
3217
3218         if (Profile->get_sae()) {
3219                 tools_tearoff->set_can_be_torn_off (false);
3220         }
3221
3222         tools_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
3223                                              &tools_tearoff->tearoff_window()));
3224         tools_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
3225                                              &tools_tearoff->tearoff_window(), 0));
3226         tools_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
3227                                              &tools_tearoff->tearoff_window()));
3228         tools_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
3229                                               &tools_tearoff->tearoff_window(), 0));
3230
3231         toolbar_hbox.set_spacing (10);
3232         toolbar_hbox.set_border_width (1);
3233
3234         toolbar_hbox.pack_start (*mouse_mode_tearoff, false, false);
3235         toolbar_hbox.pack_start (*tools_tearoff, false, false);
3236
3237         
3238         hbox->pack_start (snap_box, false, false);
3239         // hbox->pack_start (zoom_box, false, false); 
3240         hbox->pack_start (*nudge_box, false, false);
3241
3242         hbox->show_all ();
3243         
3244         toolbar_base.set_name ("ToolBarBase");
3245         toolbar_base.add (toolbar_hbox);
3246
3247         toolbar_frame.set_shadow_type (SHADOW_OUT);
3248         toolbar_frame.set_name ("BaseFrame");
3249         toolbar_frame.add (toolbar_base);
3250 }
3251
3252 void
3253 Editor::midi_panic_button_pressed ()
3254 {
3255         if (session) {
3256                 session->midi_panic();
3257         }
3258 }
3259
3260 void
3261 Editor::setup_midi_toolbar ()
3262 {
3263         string pixmap_path;
3264
3265         /* Mode Buttons (tool selection) */
3266
3267         vector<ToggleButton *> midi_tool_buttons;
3268
3269         midi_tool_pencil_button.add (*(manage (new Image (::get_icon("midi_tool_pencil")))));
3270         midi_tool_pencil_button.set_relief(Gtk::RELIEF_NONE);
3271         midi_tool_buttons.push_back (&midi_tool_pencil_button);
3272         midi_tool_select_button.add (*(manage (new Image (::get_icon("midi_tool_select")))));
3273         midi_tool_select_button.set_relief(Gtk::RELIEF_NONE);
3274         midi_tool_buttons.push_back (&midi_tool_select_button);
3275         midi_tool_resize_button.add (*(manage (new Image (::get_icon("strip_width")))));
3276         midi_tool_resize_button.set_relief(Gtk::RELIEF_NONE);
3277         midi_tool_buttons.push_back (&midi_tool_resize_button);
3278         midi_tool_erase_button.add (*(manage (new Image (::get_icon("midi_tool_erase")))));
3279         midi_tool_erase_button.set_relief(Gtk::RELIEF_NONE);
3280         midi_tool_buttons.push_back (&midi_tool_erase_button);
3281
3282         midi_tool_pencil_button.set_active(true);
3283         
3284         midi_tool_button_set = new GroupedButtons (midi_tool_buttons);
3285
3286         midi_tool_button_box.set_border_width (2);
3287         midi_tool_button_box.set_spacing(1);
3288         midi_tool_button_box.pack_start(midi_tool_pencil_button, true, true);
3289         midi_tool_button_box.pack_start(midi_tool_select_button, true, true);
3290         midi_tool_button_box.pack_start(midi_tool_resize_button, true, true);
3291         midi_tool_button_box.pack_start(midi_tool_erase_button , true, true);
3292         midi_tool_button_box.set_homogeneous(true);
3293
3294         midi_tool_pencil_button.set_name ("MouseModeButton");
3295         midi_tool_select_button.set_name ("MouseModeButton");
3296         midi_tool_resize_button.set_name ("MouseModeButton");
3297         midi_tool_erase_button .set_name ("MouseModeButton");
3298
3299         ARDOUR_UI::instance()->tooltips().set_tip (midi_tool_pencil_button, _("Add/Move/Stretch Notes"));
3300         ARDOUR_UI::instance()->tooltips().set_tip (midi_tool_select_button, _("Select/Move Notes"));
3301         ARDOUR_UI::instance()->tooltips().set_tip (midi_tool_resize_button, _("Resize Notes"));
3302         ARDOUR_UI::instance()->tooltips().set_tip (midi_tool_erase_button,  _("Erase Notes"));
3303
3304         midi_tool_pencil_button.unset_flags (CAN_FOCUS);
3305         midi_tool_select_button.unset_flags (CAN_FOCUS);
3306         midi_tool_resize_button.unset_flags (CAN_FOCUS);
3307         midi_tool_erase_button.unset_flags (CAN_FOCUS);
3308         
3309         midi_tool_pencil_button.signal_toggled().connect (bind (mem_fun(*this,
3310                                 &Editor::midi_edit_mode_toggled), Editing::MidiEditPencil));
3311         midi_tool_select_button.signal_toggled().connect (bind (mem_fun(*this,
3312                                 &Editor::midi_edit_mode_toggled), Editing::MidiEditSelect));
3313         midi_tool_resize_button.signal_toggled().connect (bind (mem_fun(*this,
3314                                 &Editor::midi_edit_mode_toggled), Editing::MidiEditResize));
3315         midi_tool_erase_button.signal_toggled().connect (bind (mem_fun(*this,
3316                                 &Editor::midi_edit_mode_toggled), Editing::MidiEditErase));
3317
3318         
3319         /* Midi sound notes */
3320         midi_sound_notes.add (*(manage (new Image (::get_icon("midi_sound_notes")))));
3321         midi_sound_notes.set_relief(Gtk::RELIEF_NONE);
3322         ARDOUR_UI::instance()->tooltips().set_tip (midi_sound_notes, _("Sound Notes"));
3323         midi_sound_notes.unset_flags (CAN_FOCUS);
3324         
3325         /* Panic */
3326         
3327         HBox* panic_box = manage (new HBox);
3328         midi_panic_button.set_name("MidiPanicButton");
3329         midi_panic_button.signal_pressed().connect (
3330                         mem_fun(this, &Editor::midi_panic_button_pressed));
3331         panic_box->pack_start (midi_sound_notes , true, true);
3332         panic_box->pack_start (midi_panic_button, true, true);
3333         
3334         /* Pack everything in... */
3335
3336         midi_tools_tearoff = manage (new TearOff (midi_tool_button_box));
3337         midi_tools_tearoff->set_name ("MouseModeBase");
3338
3339         /*
3340         midi_tools_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&midi_toolbar_hbox), 
3341                                              &midi_tools_tearoff->tearoff_window()));
3342         midi_tools_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&midi_toolbar_hbox), 
3343                                              &midi_tools_tearoff->tearoff_window(), 0));
3344         midi_tools_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&midi_toolbar_hbox), 
3345                                              &midi_tools_tearoff->tearoff_window()));
3346         midi_tools_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&midi_toolbar_hbox), 
3347                                               &midi_tools_tearoff->tearoff_window(), 0));
3348         */
3349
3350         midi_toolbar_hbox.set_spacing (10);
3351         midi_toolbar_hbox.set_border_width (1);
3352
3353         midi_toolbar_hbox.pack_start (*midi_tools_tearoff, false, true);
3354         
3355         midi_toolbar_hbox.pack_start(*panic_box, false, true, 4);
3356
3357         midi_tool_button_box.show_all ();
3358         midi_toolbar_hbox.show_all();
3359         midi_tools_tearoff->show_all();
3360         
3361         midi_toolbar_base.set_name ("ToolBarBase");
3362         midi_toolbar_base.add (midi_toolbar_hbox);
3363
3364         midi_toolbar_frame.set_shadow_type (SHADOW_OUT);
3365         midi_toolbar_frame.set_name ("BaseFrame");
3366         midi_toolbar_frame.add (midi_toolbar_base);
3367 }
3368
3369 int
3370 Editor::convert_drop_to_paths (vector<ustring>& paths, 
3371                                const RefPtr<Gdk::DragContext>& context,
3372                                gint                x,
3373                                gint                y,
3374                                const SelectionData& data,
3375                                guint               info,
3376                                guint               time)                               
3377
3378 {       
3379         if (session == 0) {
3380                 return -1;
3381         }
3382
3383         vector<ustring> uris = data.get_uris();
3384
3385         if (uris.empty()) {
3386
3387                 /* This is seriously fucked up. Nautilus doesn't say that its URI lists
3388                    are actually URI lists. So do it by hand.
3389                 */
3390
3391                 if (data.get_target() != "text/plain") {
3392                         return -1;
3393                 }
3394   
3395                 /* Parse the "uri-list" format that Nautilus provides, 
3396                    where each pathname is delimited by \r\n.
3397
3398                    THERE MAY BE NO NULL TERMINATING CHAR!!!
3399                 */
3400
3401                 ustring txt = data.get_text();
3402                 const char* p;
3403                 const char* q;
3404
3405                 p = (const char *) malloc (txt.length() + 1);
3406                 txt.copy ((char *) p, txt.length(), 0);
3407                 ((char*)p)[txt.length()] = '\0';
3408
3409                 while (p)
3410                 {
3411                         if (*p != '#')
3412                         {
3413                                 while (g_ascii_isspace (*p))
3414                                         p++;
3415                                 
3416                                 q = p;
3417                                 while (*q && (*q != '\n') && (*q != '\r')) {
3418                                         q++;
3419                                 }
3420                                 
3421                                 if (q > p)
3422                                 {
3423                                         q--;
3424                                         while (q > p && g_ascii_isspace (*q))
3425                                                 q--;
3426                                         
3427                                         if (q > p)
3428                                         {
3429                                                 uris.push_back (ustring (p, q - p + 1));
3430                                         }
3431                                 }
3432                         }
3433                         p = strchr (p, '\n');
3434                         if (p)
3435                                 p++;
3436                 }
3437
3438                 free ((void*)p);
3439                 
3440                 if (uris.empty()) {
3441                         return -1;
3442                 }
3443         }
3444         
3445         for (vector<ustring>::iterator i = uris.begin(); i != uris.end(); ++i) {
3446
3447                 if ((*i).substr (0,7) == "file://") {
3448                         
3449                         ustring p = *i;
3450                         PBD::url_decode (p);
3451
3452                         // scan forward past three slashes
3453                         
3454                         ustring::size_type slashcnt = 0;
3455                         ustring::size_type n = 0;
3456                         ustring::iterator x = p.begin();
3457
3458                         while (slashcnt < 3 && x != p.end()) {
3459                                 if ((*x) == '/') {
3460                                         slashcnt++;
3461                                 } else if (slashcnt == 3) {
3462                                         break;
3463                                 }
3464                                 ++n;
3465                                 ++x;
3466                         }
3467
3468                         if (slashcnt != 3 || x == p.end()) {
3469                                 error << _("malformed URL passed to drag-n-drop code") << endmsg;
3470                                 continue;
3471                         }
3472
3473                         paths.push_back (p.substr (n - 1));
3474                 }
3475         }
3476
3477         return 0;
3478 }
3479
3480 void
3481 Editor::new_tempo_section ()
3482
3483 {
3484 }
3485
3486 void
3487 Editor::map_transport_state ()
3488 {
3489         ENSURE_GUI_THREAD (mem_fun(*this, &Editor::map_transport_state));
3490
3491         if (session->transport_stopped()) {
3492                 have_pending_keyboard_selection = false;
3493         }
3494
3495         update_loop_range_view (true);
3496 }
3497
3498 /* UNDO/REDO */
3499
3500 Editor::State::State (PublicEditor const * e)
3501 {
3502         selection = new Selection (e);
3503 }
3504
3505 Editor::State::~State ()
3506 {
3507         delete selection;
3508 }
3509
3510 void
3511 Editor::store_state (State& state) const
3512 {
3513         *state.selection = *selection;
3514 }
3515
3516 void
3517 Editor::restore_state (State *state)
3518 {
3519         if (*selection == *state->selection) {
3520                 return;
3521         }
3522
3523         *selection = *state->selection;
3524         time_selection_changed ();
3525         region_selection_changed ();
3526
3527         /* XXX other selection change handlers? */
3528 }
3529
3530 void
3531 Editor::begin_reversible_command (string name)
3532 {
3533         if (session) {
3534                 before = &get_state();
3535                 session->begin_reversible_command (name);
3536         }
3537 }
3538
3539 void
3540 Editor::commit_reversible_command ()
3541 {
3542         if (session) {
3543                 session->commit_reversible_command (new MementoCommand<Editor>(*this, before, &get_state()));
3544         }
3545 }
3546
3547 void
3548 Editor::set_edit_group_solo (Route& route, bool yn)
3549 {
3550         RouteGroup *edit_group;
3551
3552         if ((edit_group = route.edit_group()) != 0) {
3553                 edit_group->apply (&Route::set_solo, yn, this);
3554         } else {
3555                 route.set_solo (yn, this);
3556         }
3557 }
3558
3559 void
3560 Editor::set_edit_group_mute (Route& route, bool yn)
3561 {
3562         RouteGroup *edit_group = 0;
3563
3564         if ((edit_group == route.edit_group()) != 0) {
3565                 edit_group->apply (&Route::set_mute, yn, this);
3566         } else {
3567                 route.set_mute (yn, this);
3568         }
3569 }
3570                 
3571 void
3572 Editor::history_changed ()
3573 {
3574         string label;
3575
3576         if (undo_action && session) {
3577                 if (session->undo_depth() == 0) {
3578                         label = _("Undo");
3579                 } else {
3580                         label = string_compose(_("Undo (%1)"), session->next_undo());
3581                 }
3582                 undo_action->property_label() = label;
3583         }
3584
3585         if (redo_action && session) {
3586                 if (session->redo_depth() == 0) {
3587                         label = _("Redo");
3588                 } else {
3589                         label = string_compose(_("Redo (%1)"), session->next_redo());
3590                 }
3591                 redo_action->property_label() = label;
3592         }
3593 }
3594
3595 void
3596 Editor::duplicate_dialog (bool with_dialog)
3597 {
3598         float times = 1.0f;
3599
3600         if (mouse_mode == MouseRange) {
3601                 if (selection->time.length() == 0) {
3602                         return;
3603                 }
3604         }
3605
3606         RegionSelection rs;
3607         get_regions_for_action (rs);
3608         
3609         if (mouse_mode != MouseRange) {
3610
3611                 if (rs.empty()) {
3612                         return;
3613                 }
3614         }
3615
3616         if (with_dialog) {
3617
3618                 ArdourDialog win ("Duplication Dialog");
3619                 Label  label (_("Number of Duplications:"));
3620                 Adjustment adjustment (1.0, 1.0, 1000000.0, 1.0, 5.0);
3621                 SpinButton spinner (adjustment, 0.0, 1);
3622                 HBox hbox;
3623                 
3624                 win.get_vbox()->set_spacing (12);
3625                 win.get_vbox()->pack_start (hbox);
3626                 hbox.set_border_width (6);
3627                 hbox.pack_start (label, PACK_EXPAND_PADDING, 12);
3628                 
3629                 /* dialogs have ::add_action_widget() but that puts the spinner in the wrong
3630                    place, visually. so do this by hand.
3631                 */
3632                 
3633                 hbox.pack_start (spinner, PACK_EXPAND_PADDING, 12);
3634                 spinner.signal_activate().connect (sigc::bind (mem_fun (win, &ArdourDialog::response), RESPONSE_ACCEPT));
3635                 spinner.grab_focus();
3636
3637                 hbox.show ();
3638                 label.show ();
3639                 spinner.show ();
3640                 
3641                 win.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3642                 win.add_button (_("Duplicate"), RESPONSE_ACCEPT);
3643                 win.set_default_response (RESPONSE_ACCEPT);
3644                 
3645                 win.set_position (WIN_POS_MOUSE);
3646                 
3647                 spinner.grab_focus ();
3648                 
3649                 switch (win.run ()) {
3650                 case RESPONSE_ACCEPT:
3651                         break;
3652                 default:
3653                         return;
3654                 }
3655                 
3656                 times = adjustment.get_value();
3657         }
3658
3659         if (mouse_mode == MouseRange) {
3660                 duplicate_selection (times);
3661         } else {
3662                 duplicate_some_regions (rs, times);
3663         }
3664 }
3665
3666 void
3667 Editor::show_verbose_canvas_cursor ()
3668 {
3669         verbose_canvas_cursor->raise_to_top();
3670         verbose_canvas_cursor->show();
3671         verbose_cursor_visible = true;
3672 }
3673
3674 void
3675 Editor::hide_verbose_canvas_cursor ()
3676 {
3677         verbose_canvas_cursor->hide();
3678         verbose_cursor_visible = false;
3679 }
3680
3681 double
3682 Editor::clamp_verbose_cursor_x (double x)
3683 {
3684         if (x < 0) {
3685                 x = 0;
3686         } else {
3687                 x = min (canvas_width - 200.0, x);
3688         }
3689         return x;
3690 }
3691
3692 double
3693 Editor::clamp_verbose_cursor_y (double y)
3694 {
3695         if (y < canvas_timebars_vsize) {
3696                 y = canvas_timebars_vsize;
3697         } else {
3698                 y = min (canvas_height - 50, y);
3699         }
3700         return y;
3701 }
3702
3703 void
3704 Editor::set_verbose_canvas_cursor (const string & txt, double x, double y)
3705 {
3706         verbose_canvas_cursor->property_text() = txt.c_str();
3707         /* don't get too close to the edge */
3708         verbose_canvas_cursor->property_x() = clamp_verbose_cursor_x (x);
3709         verbose_canvas_cursor->property_y() = clamp_verbose_cursor_y (y);
3710 }
3711
3712 void
3713 Editor::set_verbose_canvas_cursor_text (const string & txt)
3714 {
3715         verbose_canvas_cursor->property_text() = txt.c_str();
3716 }
3717
3718 void
3719 Editor::set_edit_mode (EditMode m)
3720 {
3721         Config->set_edit_mode (m);
3722 }
3723
3724 void
3725 Editor::cycle_edit_mode ()
3726 {
3727         switch (Config->get_edit_mode()) {
3728         case Slide:
3729                 if (Profile->get_sae()) {
3730                         Config->set_edit_mode (Lock);
3731                 } else {
3732                         Config->set_edit_mode (Splice);
3733                 }
3734                 break;
3735         case Splice:
3736                 Config->set_edit_mode (Lock);
3737                 break;
3738         case Lock:
3739                 Config->set_edit_mode (Slide);
3740                 break;
3741         }
3742 }
3743
3744 void
3745 Editor::edit_mode_selection_done ()
3746 {
3747         if (session == 0) {
3748                 return;
3749         }
3750
3751         string choice = edit_mode_selector.get_active_text();
3752         EditMode mode = Slide;
3753
3754         if (choice == _("Splice Edit")) {
3755                 mode = Splice;
3756         } else if (choice == _("Slide Edit")) {
3757                 mode = Slide;
3758         } else if (choice == _("Lock Edit")) {
3759                 mode = Lock;
3760         }
3761
3762         Config->set_edit_mode (mode);
3763 }       
3764
3765 void
3766 Editor::snap_type_selection_done ()
3767 {
3768         string choice = snap_type_selector.get_active_text();
3769         SnapType snaptype = SnapToBeat;
3770
3771         if (choice == _("Beats/3")) {
3772                 snaptype = SnapToAThirdBeat;
3773         } else if (choice == _("Beats/4")) {
3774                 snaptype = SnapToAQuarterBeat;
3775         } else if (choice == _("Beats/8")) {
3776                 snaptype = SnapToAEighthBeat;
3777         } else if (choice == _("Beats/16")) {
3778                 snaptype = SnapToASixteenthBeat;
3779         } else if (choice == _("Beats/32")) {
3780                 snaptype = SnapToAThirtysecondBeat;
3781         } else if (choice == _("Beats")) {
3782                 snaptype = SnapToBeat;
3783         } else if (choice == _("Bars")) {
3784                 snaptype = SnapToBar;
3785         } else if (choice == _("Marks")) {
3786                 snaptype = SnapToMark;
3787         } else if (choice == _("Region starts")) {
3788                 snaptype = SnapToRegionStart;
3789         } else if (choice == _("Region ends")) {
3790                 snaptype = SnapToRegionEnd;
3791         } else if (choice == _("Region bounds")) {
3792                 snaptype = SnapToRegionBoundary;
3793         } else if (choice == _("Region syncs")) {
3794                 snaptype = SnapToRegionSync;
3795         } else if (choice == _("CD Frames")) {
3796                 snaptype = SnapToCDFrame;
3797         } else if (choice == _("SMPTE Frames")) {
3798                 snaptype = SnapToSMPTEFrame;
3799         } else if (choice == _("SMPTE Seconds")) {
3800                 snaptype = SnapToSMPTESeconds;
3801         } else if (choice == _("SMPTE Minutes")) {
3802                 snaptype = SnapToSMPTEMinutes;
3803         } else if (choice == _("Seconds")) {
3804                 snaptype = SnapToSeconds;
3805         } else if (choice == _("Minutes")) {
3806                 snaptype = SnapToMinutes;
3807         }
3808
3809         RefPtr<RadioAction> ract = snap_type_action (snaptype);
3810         if (ract) {
3811                 ract->set_active ();
3812         }
3813 }       
3814
3815 void
3816 Editor::snap_mode_selection_done ()
3817 {
3818         string choice = snap_mode_selector.get_active_text();
3819         SnapMode mode = SnapNormal;
3820
3821         if (choice == _("No Grid")) {
3822                 mode = SnapOff;
3823         } else if (choice == _("Grid")) {
3824                 mode = SnapNormal;
3825         } else if (choice == _("Magnetic")) {
3826                 mode = SnapMagnetic;
3827         }
3828
3829         RefPtr<RadioAction> ract = snap_mode_action (mode);
3830
3831         if (ract) {
3832                 ract->set_active (true);
3833         }
3834 }
3835
3836 void
3837 Editor::cycle_edit_point (bool with_marker)
3838 {
3839         switch (_edit_point) {
3840         case EditAtMouse:
3841                 set_edit_point_preference (EditAtPlayhead);
3842                 break;
3843         case EditAtPlayhead:
3844                 if (with_marker) {
3845                         set_edit_point_preference (EditAtSelectedMarker);
3846                 } else {
3847                         set_edit_point_preference (EditAtMouse);
3848                 }
3849                 break;
3850         case EditAtSelectedMarker:
3851                 set_edit_point_preference (EditAtMouse);
3852                 break;
3853         }
3854 }
3855
3856 void
3857 Editor::edit_point_selection_done ()
3858 {
3859         string choice = edit_point_selector.get_active_text();
3860         EditPoint ep = EditAtSelectedMarker;
3861
3862         if (choice == _("Marker")) {
3863                 set_edit_point_preference (EditAtSelectedMarker);
3864         } else if (choice == _("Playhead")) {
3865                 set_edit_point_preference (EditAtPlayhead);
3866         } else {
3867                 set_edit_point_preference (EditAtMouse);
3868         }
3869
3870         RefPtr<RadioAction> ract = edit_point_action (ep);
3871
3872         if (ract) {
3873                 ract->set_active (true);
3874         }
3875 }
3876
3877 void
3878 Editor::zoom_focus_selection_done ()
3879 {
3880         string choice = zoom_focus_selector.get_active_text();
3881         ZoomFocus focus_type = ZoomFocusLeft;
3882
3883         if (choice == _("Left")) {
3884                 focus_type = ZoomFocusLeft;
3885         } else if (choice == _("Right")) {
3886                 focus_type = ZoomFocusRight;
3887         } else if (choice == _("Center")) {
3888                 focus_type = ZoomFocusCenter;
3889         } else if (choice == _("Play")) {
3890                 focus_type = ZoomFocusPlayhead;
3891         } else if (choice == _("Edit")) {
3892                 focus_type = ZoomFocusEdit;
3893         } else if (choice == _("Active Mark")) {
3894                 focus_type = ZoomFocusEdit;
3895         } else if (choice == _("Active Mark")) {
3896                 focus_type = ZoomFocusEdit;
3897         } else {
3898                 focus_type = ZoomFocusMouse;
3899         } 
3900         
3901         RefPtr<RadioAction> ract = zoom_focus_action (focus_type);
3902
3903         if (ract) {
3904                 ract->set_active ();
3905         }
3906 }       
3907
3908 gint
3909 Editor::edit_controls_button_release (GdkEventButton* ev)
3910 {
3911         if (Keyboard::is_context_menu_event (ev)) {
3912                 ARDOUR_UI::instance()->add_route (this);
3913         }
3914         return TRUE;
3915 }
3916
3917 gint
3918 Editor::mouse_select_button_release (GdkEventButton* ev)
3919 {
3920         /* this handles just right-clicks */
3921
3922         if (ev->button != 3) {
3923                 return false;
3924         }
3925
3926         return true;
3927 }
3928
3929 Editor::TrackViewList *
3930 Editor::get_valid_views (TimeAxisView* track, RouteGroup* group)
3931 {
3932         TrackViewList *v;
3933         TrackViewList::iterator i;
3934
3935         v = new TrackViewList;
3936
3937         if (track == 0 && group == 0) {
3938
3939                 /* all views */
3940
3941                 for (i = track_views.begin(); i != track_views.end (); ++i) {
3942                         v->push_back (*i);
3943                 }
3944
3945         } else if ((track != 0 && group == 0) || (track != 0 && group != 0 && !group->is_active())) {
3946                 
3947                 /* just the view for this track
3948                  */
3949
3950                 v->push_back (track);
3951
3952         } else {
3953                 
3954                 /* views for all tracks in the edit group */
3955                 
3956                 for (i  = track_views.begin(); i != track_views.end (); ++i) {
3957
3958                         if (group == 0 || (*i)->edit_group() == group) {
3959                                 v->push_back (*i);
3960                         }
3961                 }
3962         }
3963         
3964         return v;
3965 }
3966
3967 void
3968 Editor::set_zoom_focus (ZoomFocus f)
3969 {
3970         string str = zoom_focus_strings[(int)f];
3971
3972         if (str != zoom_focus_selector.get_active_text()) {
3973                 zoom_focus_selector.set_active_text (str);
3974         }
3975         
3976         if (zoom_focus != f) {
3977                 zoom_focus = f;
3978
3979                 ZoomFocusChanged (); /* EMIT_SIGNAL */
3980
3981                 instant_save ();
3982         }
3983 }
3984
3985 void
3986 Editor::ensure_float (Window& win)
3987 {
3988         win.set_transient_for (*this);
3989 }
3990
3991 void 
3992 Editor::pane_allocation_handler (Allocation &alloc, Paned* which)
3993 {
3994         /* recover or initialize pane positions. do this here rather than earlier because
3995            we don't want the positions to change the child allocations, which they seem to do.
3996          */
3997
3998         int pos;
3999         XMLProperty* prop;
4000         char buf[32];
4001         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
4002         int width, height;
4003         static int32_t done;
4004         XMLNode* geometry;
4005
4006         width = default_width;
4007         height = default_height;
4008
4009         if ((geometry = find_named_node (*node, "geometry")) != 0) {
4010
4011                 if ((prop = geometry->property ("x_size")) == 0) {
4012                         prop = geometry->property ("x-size");
4013                 }
4014                 if (prop) {
4015                         width = atoi (prop->value());
4016                 }
4017                 if ((prop = geometry->property ("y_size")) == 0) {
4018                         prop = geometry->property ("y-size");
4019                 }
4020                 if (prop) {
4021                         height = atoi (prop->value());
4022                 }
4023         }
4024
4025         if (which == static_cast<Paned*> (&edit_pane)) {
4026
4027                 if (done) {
4028                         return;
4029                 }
4030
4031                 if (!geometry || (prop = geometry->property ("edit-pane-pos")) == 0) {
4032                         /* initial allocation is 90% to canvas, 10% to notebook */
4033                         pos = (int) floor (alloc.get_width() * 0.90f);
4034                         snprintf (buf, sizeof(buf), "%d", pos);
4035                 } else {
4036                         pos = atoi (prop->value());
4037                 }
4038
4039                 if ((done = GTK_WIDGET(edit_pane.gobj())->allocation.width > pos)) {
4040                         edit_pane.set_position (pos);
4041                         pre_maximal_pane_position = pos;
4042                 }
4043         }
4044 }
4045
4046 void
4047 Editor::detach_tearoff (Box* b, Window* w)
4048 {
4049         if (tools_tearoff->torn_off() && 
4050             mouse_mode_tearoff->torn_off()) {
4051                 top_hbox.remove (toolbar_frame);
4052         }
4053 }
4054
4055 void
4056 Editor::reattach_tearoff (Box* b, Window* w, int32_t n)
4057 {
4058         if (toolbar_frame.get_parent() == 0) {
4059                 top_hbox.pack_end (toolbar_frame);
4060         }
4061 }
4062
4063 void
4064 Editor::set_show_measures (bool yn)
4065 {
4066         if (_show_measures != yn) {
4067                 hide_measures ();
4068
4069                 if ((_show_measures = yn) == true) {
4070                         if (tempo_lines)
4071                                 tempo_lines->show();
4072                         draw_measures ();
4073                 }
4074                 instant_save ();
4075         }
4076 }
4077
4078 void
4079 Editor::toggle_follow_playhead ()
4080 {
4081         RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
4082         if (act) {
4083                 RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
4084                 set_follow_playhead (tact->get_active());
4085         }
4086 }
4087
4088 void
4089 Editor::set_follow_playhead (bool yn)
4090 {
4091         if (_follow_playhead != yn) {
4092                 if ((_follow_playhead = yn) == true) {
4093                         /* catch up */
4094                         update_current_screen ();
4095                 }
4096                 instant_save ();
4097         }
4098 }
4099
4100 void
4101 Editor::toggle_xfade_active (boost::weak_ptr<Crossfade> wxfade)
4102 {
4103         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
4104         if (xfade) {
4105                 xfade->set_active (!xfade->active());
4106         }
4107 }
4108
4109 void
4110 Editor::toggle_xfade_length (boost::weak_ptr<Crossfade> wxfade)
4111 {
4112         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
4113         if (xfade) {
4114                 xfade->set_follow_overlap (!xfade->following_overlap());
4115         }
4116 }
4117
4118 void
4119 Editor::edit_xfade (boost::weak_ptr<Crossfade> wxfade)
4120 {
4121         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
4122
4123         if (!xfade) {
4124                 return;
4125         }
4126
4127         CrossfadeEditor cew (*session, xfade, xfade->fade_in().get_min_y(), 1.0);
4128                 
4129         ensure_float (cew);
4130         
4131         switch (cew.run ()) {
4132         case RESPONSE_ACCEPT:
4133                 break;
4134         default:
4135                 return;
4136         }
4137         
4138         cew.apply ();
4139         xfade->StateChanged (Change (~0));
4140 }
4141
4142 PlaylistSelector&
4143 Editor::playlist_selector () const
4144 {
4145         return *_playlist_selector;
4146 }
4147
4148 nframes64_t
4149 Editor::get_nudge_distance (nframes64_t pos, nframes64_t& next)
4150 {
4151         nframes64_t ret;
4152
4153         ret = nudge_clock.current_duration (pos);
4154         next = ret + 1; /* XXXX fix me */
4155
4156         return ret;
4157 }
4158
4159 void
4160 Editor::end_location_changed (Location* location)
4161 {
4162         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::end_location_changed), location));
4163         //reset_scrolling_region ();
4164         nframes64_t session_span = location->start() + (nframes64_t) floorf (current_page_frames() * 0.10f);
4165         horizontal_adjustment.set_upper (session_span / frames_per_unit);
4166 }
4167
4168 int
4169 Editor::playlist_deletion_dialog (boost::shared_ptr<Playlist> pl)
4170 {
4171         ArdourDialog dialog ("playlist deletion dialog");
4172         Label  label (string_compose (_("Playlist %1 is currently unused.\n"
4173                                         "If left alone, no audio files used by it will be cleaned.\n"
4174                                         "If deleted, audio files used by it alone by will cleaned."),
4175                                       pl->name()));
4176         
4177         dialog.set_position (WIN_POS_CENTER);
4178         dialog.get_vbox()->pack_start (label);
4179
4180         label.show ();
4181
4182         dialog.add_button (_("Delete playlist"), RESPONSE_ACCEPT);
4183         dialog.add_button (_("Keep playlist"), RESPONSE_REJECT);
4184         dialog.add_button (_("Cancel"), RESPONSE_CANCEL);
4185
4186         switch (dialog.run ()) {
4187         case RESPONSE_ACCEPT:
4188                 /* delete the playlist */
4189                 return 0;
4190                 break;
4191
4192         case RESPONSE_REJECT:
4193                 /* keep the playlist */
4194                 return 1;
4195                 break;
4196
4197         default:
4198                 break;
4199         }
4200
4201         return -1;
4202 }
4203
4204 bool
4205 Editor::audio_region_selection_covers (nframes64_t where)
4206 {
4207         for (RegionSelection::iterator a = selection->regions.begin(); a != selection->regions.end(); ++a) {
4208                 if ((*a)->region()->covers (where)) {
4209                         return true;
4210                 }
4211         }
4212
4213         return false;
4214 }
4215
4216 void
4217 Editor::prepare_for_cleanup ()
4218 {
4219         cut_buffer->clear_regions ();
4220         cut_buffer->clear_playlists ();
4221
4222         selection->clear_regions ();
4223         selection->clear_playlists ();
4224
4225         no_region_list_redisplay = true;
4226 }
4227
4228 void
4229 Editor::finish_cleanup ()
4230 {
4231         no_region_list_redisplay = false;
4232         redisplay_regions ();
4233 }
4234
4235 Location*
4236 Editor::transport_loop_location()
4237 {
4238         if (session) {
4239                 return session->locations()->auto_loop_location();
4240         } else {
4241                 return 0;
4242         }
4243 }
4244
4245 Location*
4246 Editor::transport_punch_location()
4247 {
4248         if (session) {
4249                 return session->locations()->auto_punch_location();
4250         } else {
4251                 return 0;
4252         }
4253 }
4254
4255 bool
4256 Editor::control_layout_scroll (GdkEventScroll* ev)
4257 {
4258         switch (ev->direction) {
4259         case GDK_SCROLL_UP:
4260                 scroll_tracks_up_line ();
4261                 return true;
4262                 break;
4263
4264         case GDK_SCROLL_DOWN:
4265                 scroll_tracks_down_line ();
4266                 return true;
4267                 
4268         default:
4269                 /* no left/right handling yet */
4270                 break;
4271         }
4272
4273         return false;
4274 }
4275
4276
4277 /** A new snapshot has been selected.
4278  */
4279 void
4280 Editor::snapshot_display_selection_changed ()
4281 {
4282         if (snapshot_display.get_selection()->count_selected_rows() > 0) {
4283
4284                 TreeModel::iterator i = snapshot_display.get_selection()->get_selected();
4285                 
4286                 Glib::ustring snap_name = (*i)[snapshot_display_columns.real_name];
4287
4288                 if (snap_name.length() == 0) {
4289                         return;
4290                 }
4291                 
4292                 if (session->snap_name() == snap_name) {
4293                         return;
4294                 }
4295                 
4296                 ARDOUR_UI::instance()->load_session(session->path(), string (snap_name));
4297         }
4298 }
4299
4300 bool
4301 Editor::snapshot_display_button_press (GdkEventButton* ev)
4302 {
4303         if (ev->button == 3) {
4304                 /* Right-click on the snapshot list. Work out which snapshot it
4305                    was over. */
4306                 Gtk::TreeModel::Path path;
4307                 Gtk::TreeViewColumn* col;
4308                 int cx;
4309                 int cy;
4310                 snapshot_display.get_path_at_pos ((int) ev->x, (int) ev->y, path, col, cx, cy);
4311                 Gtk::TreeModel::iterator iter = snapshot_display_model->get_iter (path);
4312                 if (iter) {
4313                         Gtk::TreeModel::Row row = *iter;
4314                         popup_snapshot_context_menu (ev->button, ev->time, row[snapshot_display_columns.real_name]);
4315                 }
4316                 return true;
4317         }
4318
4319         return false;
4320 }
4321
4322
4323 /** Pop up the snapshot display context menu.
4324  * @param button Button used to open the menu.
4325  * @param time Menu open time.
4326  * @snapshot_name Name of the snapshot that the menu click was over.
4327  */
4328
4329 void
4330 Editor::popup_snapshot_context_menu (int button, int32_t time, Glib::ustring snapshot_name)
4331 {
4332         using namespace Menu_Helpers;
4333
4334         MenuList& items (snapshot_context_menu.items());
4335         items.clear ();
4336
4337         const bool modification_allowed = (session->snap_name() != snapshot_name && session->name() != snapshot_name);
4338
4339         add_item_with_sensitivity (items, MenuElem (_("Remove"), bind (mem_fun (*this, &Editor::remove_snapshot), snapshot_name)), modification_allowed);
4340
4341         add_item_with_sensitivity (items, MenuElem (_("Rename"), bind (mem_fun (*this, &Editor::rename_snapshot), snapshot_name)), modification_allowed);
4342
4343         snapshot_context_menu.popup (button, time);
4344 }
4345
4346 void
4347 Editor::rename_snapshot (Glib::ustring old_name)
4348 {
4349         ArdourPrompter prompter(true);
4350
4351         string new_name;
4352
4353         prompter.set_name ("Prompter");
4354         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
4355         prompter.set_prompt (_("New name of snapshot"));
4356         prompter.set_initial_text (old_name);
4357         
4358         if (prompter.run() == RESPONSE_ACCEPT) {
4359                 prompter.get_result (new_name);
4360                 if (new_name.length()) {
4361                         session->rename_state (old_name, new_name);
4362                         redisplay_snapshots ();
4363                 }
4364         }
4365 }
4366
4367
4368 void
4369 Editor::remove_snapshot (Glib::ustring name)
4370 {
4371         vector<string> choices;
4372
4373         std::string prompt  = string_compose (_("Do you really want to remove snapshot \"%1\" ?\n(cannot be undone)"), name);
4374
4375         choices.push_back (_("No, do nothing."));
4376         choices.push_back (_("Yes, remove it."));
4377
4378         Gtkmm2ext::Choice prompter (prompt, choices);
4379
4380         if (prompter.run () == 1) {
4381                 session->remove_state (name);
4382                 redisplay_snapshots ();
4383         }
4384 }
4385
4386 void
4387 Editor::redisplay_snapshots ()
4388 {
4389         if (session == 0) {
4390                 return;
4391         }
4392
4393         vector<sys::path> state_file_paths;
4394
4395         get_state_files_in_directory (session->session_directory().root_path(),
4396                         state_file_paths);
4397
4398         if (state_file_paths.empty()) return;
4399
4400         vector<string> state_file_names(get_file_names_no_extension(state_file_paths));
4401
4402         snapshot_display_model->clear ();
4403
4404         for (vector<string>::iterator i = state_file_names.begin();
4405                         i != state_file_names.end(); ++i)
4406         {
4407                 string statename = (*i);
4408                 TreeModel::Row row = *(snapshot_display_model->append());
4409                 
4410                 /* this lingers on in case we ever want to change the visible
4411                    name of the snapshot.
4412                 */
4413                 
4414                 string display_name;
4415                 display_name = statename;
4416
4417                 if (statename == session->snap_name()) {
4418                         snapshot_display.get_selection()->select(row);
4419                 } 
4420                 
4421                 row[snapshot_display_columns.visible_name] = display_name;
4422                 row[snapshot_display_columns.real_name] = statename;
4423         }
4424 }
4425
4426 void
4427 Editor::session_state_saved (string snap_name)
4428 {
4429         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::session_state_saved), snap_name));
4430         redisplay_snapshots ();
4431 }
4432
4433 void
4434 Editor::maximise_editing_space ()
4435 {
4436         mouse_mode_tearoff->set_visible (false);
4437         tools_tearoff->set_visible (false);
4438
4439         pre_maximal_pane_position = edit_pane.get_position();
4440         pre_maximal_editor_width = this->get_width();
4441
4442         if(post_maximal_pane_position == 0) {
4443                 post_maximal_pane_position = edit_pane.get_width();
4444         }
4445
4446         fullscreen();
4447
4448         if(post_maximal_editor_width) {
4449                 edit_pane.set_position (post_maximal_pane_position - 
4450                         abs(post_maximal_editor_width - pre_maximal_editor_width));
4451         } else {
4452                 edit_pane.set_position (post_maximal_pane_position);
4453         }
4454 }
4455
4456 void
4457 Editor::restore_editing_space ()
4458 {
4459         // user changed width of pane during fullscreen
4460
4461         if(post_maximal_pane_position != edit_pane.get_position()) {
4462                 post_maximal_pane_position = edit_pane.get_position();
4463         }
4464
4465         unfullscreen();
4466
4467         mouse_mode_tearoff->set_visible (true);
4468         tools_tearoff->set_visible (true);
4469         post_maximal_editor_width = this->get_width();
4470
4471         edit_pane.set_position (pre_maximal_pane_position + abs(this->get_width() - pre_maximal_editor_width));
4472 }
4473
4474 /**
4475  *  Make new playlists for a given track and also any others that belong
4476  *  to the same active edit group.
4477  *  @param v Track.
4478  */
4479
4480 void 
4481 Editor::new_playlists (TimeAxisView* v)
4482 {
4483         begin_reversible_command (_("new playlists"));
4484         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4485         session->get_playlists(playlists);
4486         mapover_tracks ( bind(mem_fun (*this, &Editor::mapped_use_new_playlist), playlists), v );
4487         commit_reversible_command ();
4488 }
4489
4490 /**
4491  *  Use a copy of the current playlist for a given track and also any others that belong
4492  *  to the same active edit group.
4493  *  @param v Track.
4494  */
4495
4496 void
4497 Editor::copy_playlists (TimeAxisView* v)
4498 {
4499         begin_reversible_command (_("copy playlists"));
4500         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4501         session->get_playlists(playlists);
4502         mapover_tracks ( bind(mem_fun (*this, &Editor::mapped_use_copy_playlist), playlists), v );
4503         commit_reversible_command ();
4504 }
4505
4506 /**
4507  *  Clear the current playlist for a given track and also any others that belong
4508  *  to the same active edit group.
4509  *  @param v Track.
4510  */
4511
4512 void 
4513 Editor::clear_playlists (TimeAxisView* v)
4514 {
4515         begin_reversible_command (_("clear playlists"));
4516         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4517         session->get_playlists(playlists);
4518         mapover_tracks ( mem_fun (*this, &Editor::mapped_clear_playlist), v );
4519         commit_reversible_command ();
4520 }
4521
4522 void 
4523 Editor::mapped_use_new_playlist (RouteTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4524 {
4525         atv.use_new_playlist (sz > 1 ? false : true, playlists);
4526 }
4527
4528 void
4529 Editor::mapped_use_copy_playlist (RouteTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4530 {
4531         atv.use_copy_playlist (sz > 1 ? false : true, playlists);
4532 }
4533
4534 void 
4535 Editor::mapped_clear_playlist (RouteTimeAxisView& atv, uint32_t sz)
4536 {
4537         atv.clear_playlist ();
4538 }
4539
4540 bool
4541 Editor::on_key_press_event (GdkEventKey* ev)
4542 {
4543         return key_press_focus_accelerator_handler (*this, ev);
4544 }
4545
4546 bool
4547 Editor::on_key_release_event (GdkEventKey* ev)
4548 {
4549         return Gtk::Window::on_key_release_event (ev);
4550         // return key_press_focus_accelerator_handler (*this, ev);
4551 }
4552
4553 void
4554 Editor::reset_x_origin (nframes64_t frame)
4555 {
4556         //cerr << "resetting x origin" << endl;
4557         queue_visual_change (frame);
4558 }
4559
4560 void
4561 Editor::reset_zoom (double fpu)
4562 {
4563         queue_visual_change (fpu);
4564 }
4565
4566 void
4567 Editor::reposition_and_zoom (nframes64_t frame, double fpu)
4568 {
4569         //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
4570         reset_x_origin (frame);
4571         reset_zoom (fpu);
4572
4573         if (!no_save_visual) {
4574                 undo_visual_stack.push_back (current_visual_state(false));
4575         }
4576 }
4577
4578 Editor::VisualState*
4579 Editor::current_visual_state (bool with_tracks)
4580 {
4581         VisualState* vs = new VisualState;
4582         vs->y_position = vertical_adjustment.get_value();
4583         vs->frames_per_unit = frames_per_unit;
4584         vs->leftmost_frame = leftmost_frame;
4585         vs->zoom_focus = zoom_focus;
4586         vs->zoomed_to_region = zoomed_to_region;
4587
4588         if (with_tracks) {
4589                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4590                         vs->track_states.push_back (TAVState ((*i), &(*i)->get_state()));
4591                 }
4592         }
4593         
4594         return vs;
4595 }
4596
4597 void
4598 Editor::undo_visual_state ()
4599 {
4600         if (undo_visual_stack.empty()) {
4601                 return;
4602         }
4603
4604         VisualState* vs = undo_visual_stack.back();
4605         undo_visual_stack.pop_back();
4606         use_visual_state (*vs);
4607         redo_visual_stack.push_back (vs);
4608 }
4609
4610 void
4611 Editor::redo_visual_state ()
4612 {
4613         if (redo_visual_stack.empty()) {
4614                 return;
4615         }
4616
4617         VisualState* vs = redo_visual_stack.back();
4618         redo_visual_stack.pop_back();
4619         use_visual_state (*vs);
4620         undo_visual_stack.push_back (vs);
4621 }
4622
4623 void
4624 Editor::swap_visual_state ()
4625 {
4626         if (undo_visual_stack.empty()) {
4627                 redo_visual_state ();
4628         } else {
4629                 undo_visual_state ();
4630         }
4631 }
4632
4633 void
4634 Editor::use_visual_state (VisualState& vs)
4635 {
4636         no_save_visual = true;
4637         no_route_list_redisplay = true;
4638
4639         vertical_adjustment.set_value (vs.y_position);
4640
4641         set_zoom_focus (vs.zoom_focus);
4642         reposition_and_zoom (vs.leftmost_frame, vs.frames_per_unit);
4643         zoomed_to_region = vs.zoomed_to_region;
4644         
4645         for (list<TAVState>::iterator i = vs.track_states.begin(); i != vs.track_states.end(); ++i) {
4646                 TrackViewList::iterator t;
4647
4648                 /* check if the track still exists - it could have been deleted */
4649
4650                 if ((t = find (track_views.begin(), track_views.end(), i->first)) != track_views.end()) {
4651                         (*t)->set_state (*(i->second));
4652                 }
4653         }
4654
4655
4656         if (!vs.track_states.empty()) {
4657                 update_route_visibility ();
4658         } 
4659
4660         no_route_list_redisplay = false;
4661         redisplay_route_list ();
4662
4663         no_save_visual = false;
4664 }
4665
4666 void
4667 Editor::set_frames_per_unit (double fpu)
4668 {
4669         /* this is the core function that controls the zoom level of the canvas. it is called
4670            whenever one or more calls are made to reset_zoom(). it executes in an idle handler.
4671         */
4672
4673         if (fpu == frames_per_unit) {
4674                 return;
4675         }
4676
4677         if (fpu < 2.0) {
4678                 fpu = 2.0;
4679         }
4680
4681         
4682         /* don't allow zooms that fit more than the maximum number
4683            of frames into an 800 pixel wide space.
4684         */
4685
4686         if (max_frames / fpu < 800.0) {
4687                 return;
4688         }
4689         
4690         if (tempo_lines)
4691                 tempo_lines->tempo_map_changed();
4692
4693         frames_per_unit = fpu;
4694         post_zoom ();
4695 }
4696
4697 void
4698 Editor::post_zoom ()
4699 {
4700         nframes64_t cef = 0;
4701
4702         // convert fpu to frame count
4703
4704         nframes64_t frames = (nframes64_t) floor (frames_per_unit * canvas_width);
4705
4706         if (frames_per_unit != zoom_range_clock.current_duration()) {
4707                 zoom_range_clock.set (frames);
4708         }
4709
4710         if (mouse_mode == MouseRange && selection->time.start () != selection->time.end_frame ()) {
4711                 if (!selection->tracks.empty()) {
4712                         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4713                                 (*i)->reshow_selection (selection->time);
4714                         }
4715                 } else {
4716                         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4717                                 (*i)->reshow_selection (selection->time);
4718                         }
4719                 }
4720         }
4721
4722
4723         ZoomChanged (); /* EMIT_SIGNAL */
4724
4725         reset_hscrollbar_stepping ();
4726
4727         if (session) {
4728                 cef = session->current_end_frame() + (current_page_frames() / 10);// Add a little extra so we can see the end marker
4729         }
4730         horizontal_adjustment.set_upper (cef / frames_per_unit);
4731
4732         //reset_scrolling_region ();
4733
4734         if (playhead_cursor) {
4735                 playhead_cursor->set_position (playhead_cursor->current_frame);
4736         }
4737
4738         instant_save ();
4739 }
4740
4741 void
4742 Editor::queue_visual_change (nframes64_t where)
4743 {
4744         pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::TimeOrigin);
4745         
4746         /* if we're moving beyond the end, make sure the upper limit of the horizontal adjustment
4747            can reach.
4748         */
4749         
4750         if (where > session->current_end_frame()) {
4751                 horizontal_adjustment.set_upper ((where + current_page_frames()) / frames_per_unit);
4752         }
4753         
4754         pending_visual_change.time_origin = where;
4755         
4756         if (pending_visual_change.idle_handler_id < 0) {
4757                 pending_visual_change.idle_handler_id = g_idle_add (_idle_visual_changer, this);
4758         }
4759 }
4760
4761 void
4762 Editor::queue_visual_change (double fpu)
4763 {
4764         pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::ZoomLevel);
4765         pending_visual_change.frames_per_unit = fpu;
4766
4767         if (pending_visual_change.idle_handler_id < 0) {
4768                 pending_visual_change.idle_handler_id = g_idle_add ( _idle_visual_changer, this);
4769         }
4770         
4771 }
4772
4773 int
4774 Editor::_idle_visual_changer (void* arg)
4775 {
4776         return static_cast<Editor*>(arg)->idle_visual_changer ();
4777 }
4778
4779 int
4780 Editor::idle_visual_changer ()
4781 {
4782         VisualChange::Type p = pending_visual_change.pending;
4783         pending_visual_change.pending = (VisualChange::Type) 0;
4784
4785 #ifdef FIX_THIS_FOR_V3
4786         double last_time_origin = horizontal_adjustment.get_value();
4787 #endif
4788
4789         if (p & VisualChange::ZoomLevel) {
4790                 set_frames_per_unit (pending_visual_change.frames_per_unit);
4791
4792                 compute_fixed_ruler_scale ();
4793                 compute_current_bbt_points(pending_visual_change.time_origin, pending_visual_change.time_origin + current_page_frames());
4794                 compute_bbt_ruler_scale (pending_visual_change.time_origin, pending_visual_change.time_origin + current_page_frames());
4795                 update_tempo_based_rulers ();
4796         }
4797         if (p & VisualChange::TimeOrigin) {
4798                 horizontal_adjustment.set_value (pending_visual_change.time_origin / frames_per_unit);
4799         }
4800
4801         nframes64_t csf=0, cef=0;
4802         nframes64_t current_time_origin = (nframes64_t) floor (horizontal_adjustment.get_value() * frames_per_unit);
4803         
4804         if (session) {
4805                 csf = session->current_start_frame();
4806                 cef = session->current_end_frame();
4807         }
4808         
4809         /* if we seek beyond the current end of the canvas, move the end */
4810
4811 #ifdef FIX_THIS_FOR_V3
4812         if (last_time_origin == horizontal_adjustment.get_value() ) {
4813                 /* changed signal not emitted */
4814                 update_fixed_rulers ();
4815                 redisplay_tempo (true);
4816         }
4817 #endif
4818         
4819         if (current_time_origin != pending_visual_change.time_origin) {
4820                 cef += current_page_frames() / 10; // Add a little extra so we can see the end marker
4821                 horizontal_adjustment.set_upper (cef / frames_per_unit);
4822                 horizontal_adjustment.set_value (pending_visual_change.time_origin / frames_per_unit);
4823         } else {
4824                 update_fixed_rulers();
4825                 redisplay_tempo (true);
4826         }
4827         //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
4828         pending_visual_change.idle_handler_id = -1;
4829         return 0; /* this is always a one-shot call */
4830 }
4831
4832 struct EditorOrderTimeAxisSorter {
4833     bool operator() (const TimeAxisView* a, const TimeAxisView* b) const {
4834             return a->order () < b->order ();
4835     }
4836 };
4837         
4838 void
4839 Editor::sort_track_selection (TrackSelection* sel)
4840 {
4841         EditorOrderTimeAxisSorter cmp;
4842
4843         if (sel) {
4844                 sel->sort (cmp);
4845         } else {
4846                 selection->tracks.sort (cmp);
4847         }
4848 }
4849
4850 nframes64_t
4851 Editor::get_preferred_edit_position (bool ignore_playhead)
4852 {
4853         bool ignored;
4854         nframes64_t where = 0;
4855         EditPoint ep = _edit_point;
4856
4857         if (entered_marker) {
4858                 return entered_marker->position();
4859         }
4860
4861         if (ignore_playhead && ep == EditAtPlayhead) {
4862                 ep = EditAtSelectedMarker;
4863         }
4864
4865         switch (ep) {
4866         case EditAtPlayhead:
4867                 where = session->audible_frame();
4868                 break;
4869                 
4870         case EditAtSelectedMarker:
4871                 if (!selection->markers.empty()) {
4872                         bool is_start;
4873                         Location* loc = find_location_from_marker (selection->markers.front(), is_start);
4874                         if (loc) {
4875                                 if (is_start) {
4876                                         where =  loc->start();
4877                                 } else {
4878                                         where = loc->end();
4879                                 }
4880                                 break;
4881                         }
4882                 } 
4883                 /* fallthru */
4884                 
4885         default:
4886         case EditAtMouse:
4887                 if (!mouse_frame (where, ignored)) {
4888                         /* XXX not right but what can we do ? */
4889                         return 0;
4890                 }
4891                 snap_to (where);
4892                 break;
4893         }
4894
4895         return where;
4896 }
4897
4898 void
4899 Editor::set_loop_range (nframes64_t start, nframes64_t end, string cmd)
4900 {
4901         if (!session) return;
4902
4903         begin_reversible_command (cmd);
4904         
4905         Location* tll;
4906
4907         if ((tll = transport_loop_location()) == 0) {
4908                 Location* loc = new Location (start, end, _("Loop"),  Location::IsAutoLoop);
4909                 XMLNode &before = session->locations()->get_state();
4910                 session->locations()->add (loc, true);
4911                 session->set_auto_loop_location (loc);
4912                 XMLNode &after = session->locations()->get_state();
4913                 session->add_command (new MementoCommand<Locations>(*(session->locations()), &before, &after));
4914         } else {
4915                 XMLNode &before = tll->get_state();
4916                 tll->set_hidden (false, this);
4917                 tll->set (start, end);
4918                 XMLNode &after = tll->get_state();
4919                 session->add_command (new MementoCommand<Location>(*tll, &before, &after));
4920         }
4921         
4922         commit_reversible_command ();
4923 }
4924
4925 void
4926 Editor::set_punch_range (nframes64_t start, nframes64_t end, string cmd)
4927 {
4928         if (!session) return;
4929
4930         begin_reversible_command (cmd);
4931         
4932         Location* tpl;
4933
4934         if ((tpl = transport_punch_location()) == 0) {
4935                 Location* loc = new Location (start, end, _("Loop"),  Location::IsAutoPunch);
4936                 XMLNode &before = session->locations()->get_state();
4937                 session->locations()->add (loc, true);
4938                 session->set_auto_loop_location (loc);
4939                 XMLNode &after = session->locations()->get_state();
4940                 session->add_command (new MementoCommand<Locations>(*(session->locations()), &before, &after));
4941         }
4942         else {
4943                 XMLNode &before = tpl->get_state();
4944                 tpl->set_hidden (false, this);
4945                 tpl->set (start, end);
4946                 XMLNode &after = tpl->get_state();
4947                 session->add_command (new MementoCommand<Location>(*tpl, &before, &after));
4948         }
4949         
4950         commit_reversible_command ();
4951 }
4952
4953 void
4954 Editor::get_regions_at (RegionSelection& rs, nframes64_t where, const TrackSelection& ts) const
4955 {
4956         const TrackSelection* tracks;
4957
4958         if (ts.empty()) {
4959                 tracks = &track_views;
4960         } else {
4961                 tracks = &ts;
4962         }
4963
4964         for (TrackSelection::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
4965                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*t);
4966                 if (rtv) {
4967                         boost::shared_ptr<Diskstream> ds;
4968                         boost::shared_ptr<Playlist> pl;
4969                         
4970                         if ((ds = rtv->get_diskstream()) && ((pl = ds->playlist()))) {
4971
4972                                 Playlist::RegionList* regions = pl->regions_at (
4973                                                 (nframes64_t) floor ( (double)where * ds->speed()));
4974
4975                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
4976                                         RegionView* rv = rtv->view()->find_view (*i);
4977                                         if (rv) {
4978                                                 rs.add (rv);
4979                                         }
4980                                 }
4981
4982                                 delete regions;
4983                         }
4984                 }
4985         }
4986 }
4987
4988 void
4989 Editor::get_regions_after (RegionSelection& rs, nframes64_t where, const TrackSelection& ts) const
4990 {
4991         const TrackSelection* tracks;
4992
4993         if (ts.empty()) {
4994                 tracks = &track_views;
4995         } else {
4996                 tracks = &ts;
4997         }
4998
4999         for (TrackSelection::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
5000                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*t);
5001                 if (rtv) {
5002                         boost::shared_ptr<Diskstream> ds;
5003                         boost::shared_ptr<Playlist> pl;
5004                         
5005                         if ((ds = rtv->get_diskstream()) && ((pl = ds->playlist()))) {
5006
5007                                 Playlist::RegionList* regions = pl->regions_touched (
5008                                                 (nframes64_t) floor ( (double)where * ds->speed()), max_frames);
5009
5010                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
5011
5012                                         RegionView* rv = rtv->view()->find_view (*i);
5013
5014                                         if (rv) {
5015                                                 rs.push_back (rv);
5016                                         }
5017                                 }
5018
5019                                 delete regions;
5020                         }
5021                 }
5022         }
5023 }
5024
5025 void
5026 Editor::get_regions_for_action (RegionSelection& rs, bool allow_entered)
5027 {
5028         if (selection->regions.empty()) {
5029
5030                 if (selection->tracks.empty()) {
5031
5032                         /* no regions or tracks selected
5033                         */
5034                         
5035                         if (entered_regionview && mouse_mode == Editing::MouseObject) {
5036
5037                                 /*  entered regionview is valid and we're in object mode - 
5038                                     just use entered regionview
5039                                 */
5040
5041                                 rs.add (entered_regionview);
5042                         }
5043
5044                         return;
5045
5046                 } else {
5047
5048                         /* no regions selected, so get all regions at the edit point across
5049                            all selected tracks. 
5050                         */
5051
5052                         nframes64_t where = get_preferred_edit_position();
5053                         get_regions_at (rs, where, selection->tracks);
5054
5055                         /* if the entered regionview wasn't selected and neither was its track
5056                            then add it.
5057                         */
5058
5059                         if (entered_regionview != 0 &&
5060                             !selection->selected (entered_regionview) && 
5061                             !selection->selected (&entered_regionview->get_time_axis_view())) {
5062                                 rs.add (entered_regionview);
5063                         }
5064                 }
5065
5066         } else {
5067                 
5068                 /* just use the selected regions */
5069
5070                 rs = selection->regions;
5071
5072                 /* if the entered regionview wasn't selected and we allow this sort of thing,
5073                    then add it.
5074                 */
5075
5076                 if (allow_entered && entered_regionview && !selection->selected (entered_regionview)) {
5077                         rs.add (entered_regionview);
5078                 }
5079
5080         }
5081 }
5082
5083 void
5084 Editor::get_regions_corresponding_to (boost::shared_ptr<Region> region, vector<RegionView*>& regions)
5085 {
5086
5087         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5088                 
5089                 RouteTimeAxisView* tatv;
5090                 
5091                 if ((tatv = dynamic_cast<RouteTimeAxisView*> (*i)) != 0) {
5092                         
5093                         boost::shared_ptr<Playlist> pl;
5094                         vector<boost::shared_ptr<Region> > results;
5095                         RegionView* marv;
5096                         boost::shared_ptr<Diskstream> ds;
5097                         
5098                         if ((ds = tatv->get_diskstream()) == 0) {
5099                                 /* bus */
5100                                 continue;
5101                         }
5102                         
5103                         if ((pl = (ds->playlist())) != 0) {
5104                                 pl->get_region_list_equivalent_regions (region, results);
5105                         }
5106                         
5107                         for (vector<boost::shared_ptr<Region> >::iterator ir = results.begin(); ir != results.end(); ++ir) {
5108                                 if ((marv = tatv->view()->find_view (*ir)) != 0) {
5109                                         regions.push_back (marv);
5110                                 }
5111                         }
5112                         
5113                 }
5114         }
5115 }       
5116
5117 void
5118 Editor::show_rhythm_ferret ()
5119 {
5120         if (rhythm_ferret == 0) {
5121                 rhythm_ferret = new RhythmFerret(*this);
5122         }
5123
5124         rhythm_ferret->set_session (session);
5125         rhythm_ferret->show ();
5126         rhythm_ferret->present ();
5127 }
5128
5129 void
5130 Editor::show_bundle_manager ()
5131 {
5132         if (_bundle_manager == 0) {
5133                 _bundle_manager = new BundleManager (*session);
5134         }
5135
5136         _bundle_manager->show ();
5137 }
5138
5139 void
5140 Editor::show_global_port_matrix (ARDOUR::DataType t)
5141 {
5142         if (_global_port_matrix[t] == 0) {
5143                 _global_port_matrix[t] = new GlobalPortMatrixWindow (*session, t);
5144         }
5145
5146         _global_port_matrix[t]->show ();
5147 }
5148
5149 void
5150 Editor::first_idle ()
5151 {
5152         MessageDialog* dialog = 0;
5153
5154         if (track_views.size() > 1) { 
5155                 dialog = new MessageDialog (*this, 
5156                                             _("Please wait while Ardour loads visual data"),
5157                                             true,
5158                                             Gtk::MESSAGE_INFO,
5159                                             Gtk::BUTTONS_NONE);
5160                 dialog->present ();
5161                 ARDOUR_UI::instance()->flush_pending ();
5162         }
5163
5164         for (TrackViewList::iterator t = track_views.begin(); t != track_views.end(); ++t) {
5165                 (*t)->first_idle();
5166         }
5167
5168         // first idle adds route children (automation tracks), so we need to redisplay here
5169         redisplay_route_list();
5170         
5171         delete dialog;
5172
5173         _have_idled = true;
5174 }
5175
5176 void
5177 Editor::start_resize_line_ops ()
5178 {
5179 #if 0
5180         old_resize_line_y = -1;
5181         resize_line_y = -1;
5182         need_resize_line = true;
5183 #endif  
5184 }
5185
5186 void
5187 Editor::end_resize_line_ops ()
5188 {
5189 #if 0
5190         need_resize_line = false;
5191
5192         if (old_resize_line_y >= 0) {
5193                 Gdk::Rectangle r (0, old_resize_line_y, (int) canvas_width, 3);
5194                 Glib::RefPtr<Gdk::Window> win = get_window();
5195                 cerr << "Final invalidation at " << old_resize_line_y << endl;
5196                 win->invalidate_rect (r, false);
5197         }
5198 #endif
5199 }
5200
5201 void
5202 Editor::queue_draw_resize_line (int at)
5203 {
5204 #if 0   
5205         Glib::RefPtr<Gdk::Window> win = get_window();
5206
5207         resize_line_y = at;
5208
5209         if (win && canvas_width) {
5210
5211                 int controls_width = controls_layout.get_width();
5212                 int xroot, discard;
5213                 
5214                 controls_layout.get_window()->get_origin (xroot, discard);
5215
5216                 if (old_resize_line_y >= 0) {
5217                         
5218                         /* redraw where it used to be */
5219                         
5220                         
5221                         Gdk::Rectangle r (0, old_resize_line_y - 1, controls_width + (int) canvas_width, 3);
5222                         win->invalidate_rect (r, true);
5223                         cerr << "invalidate " << xroot << "," << old_resize_line_y - 1 << ' ' 
5224                              << controls_width + canvas_width << " x 3\n";
5225                 }
5226
5227                 /* draw where it is */
5228
5229                 Gdk::Rectangle r (0, at - 1, controls_width + (int) canvas_width, 3);
5230                 win->invalidate_rect (r, true);
5231         }
5232 #endif
5233 }
5234
5235 bool
5236 Editor::on_expose_event (GdkEventExpose* ev)
5237 {
5238         /* cerr << "+++ editor expose "
5239              << ev->area.x << ',' << ev->area.y
5240              << ' '
5241              << ev->area.width << " x " << ev->area.height
5242              << " need reize ? " << need_resize_line
5243              << endl;
5244         */
5245         bool ret = Window::on_expose_event (ev);
5246
5247 #if 0
5248         if (need_resize_line) {
5249                 
5250                 int xroot, yroot, discard;
5251                 int controls_width;
5252
5253                 /* Our root coordinates for drawing the line will be the left edge 
5254                    of the track controls, and the upper left edge of our own window.
5255                 */
5256
5257                 get_window()->get_origin (discard, yroot);
5258                 controls_layout.get_window()->get_origin (xroot, discard);
5259                 controls_width = controls_layout.get_width();
5260                 
5261                 GdkRectangle lr;
5262                 GdkRectangle intersection;
5263
5264                 lr.x = 0;
5265                 lr.y = resize_line_y;
5266                 lr.width = controls_width + (int) canvas_width;
5267                 lr.height = 3;
5268
5269                 if (gdk_rectangle_intersect (&lr, &ev->area, &intersection)) {
5270                         
5271                         Glib::RefPtr<Gtk::Style> style (get_style());
5272                         Glib::RefPtr<Gdk::GC> black_gc (style->get_black_gc ());
5273                         Glib::RefPtr<Gdk::GC> gc = wrap (black_gc->gobj_copy(), false);
5274
5275                         /* draw on root window */
5276
5277                         GdkWindow* win = gdk_get_default_root_window();
5278                         
5279                         gc->set_subwindow (Gdk::INCLUDE_INFERIORS);
5280                         gc->set_line_attributes (3, Gdk::LINE_SOLID, 
5281                                                  Gdk::CAP_NOT_LAST,
5282                                                  Gdk::JOIN_MITER);
5283                         
5284                         gdk_draw_line (win, gc->gobj(), 
5285                                        0,
5286                                        resize_line_y, 
5287                                        (int) canvas_width + controls_width,
5288                                        resize_line_y);
5289 #if 0
5290                         cerr << "drew line @ " << xroot << ", " << yroot + resize_line_y 
5291                              << " to " << xroot + (int) canvas_width + controls_width
5292                              << ", " << yroot + resize_line_y
5293                              << endl;
5294 #endif
5295                         old_resize_line_y = resize_line_y;
5296                         cerr << "NEXT EXPOSE SHOULD BE AT " << old_resize_line_y << endl;
5297                 } else {
5298                         cerr << "no intersect with "
5299                              << lr.x << ',' << lr.y
5300                              << ' '
5301                              << lr.width << " x " << lr.height
5302                              << endl;
5303                 }
5304         }
5305
5306         //cerr << "--- editor expose\n";
5307 #endif
5308
5309         return ret;
5310 }
5311
5312 static gboolean
5313 _idle_resizer (gpointer arg)
5314 {
5315         return ((Editor*)arg)->idle_resize ();
5316 }
5317
5318 void
5319 Editor::add_to_idle_resize (TimeAxisView* view, uint32_t h)
5320 {
5321         if (resize_idle_id < 0) {
5322                 resize_idle_id = g_idle_add (_idle_resizer, this);
5323         } 
5324
5325         resize_idle_target = h;
5326
5327         pending_resizes.push_back (view);
5328
5329         if (selection->selected (view) && !selection->tracks.empty()) {
5330                 pending_resizes.insert (pending_resizes.end(), selection->tracks.begin(), selection->tracks.end());
5331         }
5332 }
5333
5334 bool
5335 Editor::idle_resize ()
5336 {
5337         for (vector<TimeAxisView*>::iterator i = pending_resizes.begin(); i != pending_resizes.end(); ++i) {
5338                 (*i)->idle_resize (resize_idle_target);
5339         }
5340         pending_resizes.clear();
5341         flush_canvas ();
5342         resize_idle_id = -1;
5343         return false;
5344 }
5345
5346 void
5347 Editor::located ()
5348 {
5349         ENSURE_GUI_THREAD (mem_fun (*this, &Editor::located));
5350
5351         _pending_locate_request = false;
5352 }