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