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