* Made MIDI channel coloring work in the track channel selector
[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_button_pressed ()
3245 {
3246         if (session) {
3247                 session->midi_panic();
3248         }
3249 }
3250
3251 void Editor::midi_sound_notes_toggled ()
3252 {
3253         cerr << "toggle sound notes" << endl;
3254 }
3255
3256 void
3257 Editor::setup_midi_toolbar ()
3258 {
3259         string pixmap_path;
3260
3261         /* Mode Buttons (tool selection) */
3262
3263         vector<ToggleButton *> midi_tool_buttons;
3264
3265         midi_tool_pencil_button.add (*(manage (new Image (::get_icon("midi_tool_pencil")))));
3266         midi_tool_pencil_button.set_relief(Gtk::RELIEF_NONE);
3267         midi_tool_buttons.push_back (&midi_tool_pencil_button);
3268         midi_tool_select_button.add (*(manage (new Image (::get_icon("midi_tool_select")))));
3269         midi_tool_select_button.set_relief(Gtk::RELIEF_NONE);
3270         midi_tool_buttons.push_back (&midi_tool_select_button);
3271         midi_tool_resize_button.add (*(manage (new Image (::get_icon("strip_width")))));
3272         midi_tool_resize_button.set_relief(Gtk::RELIEF_NONE);
3273         midi_tool_buttons.push_back (&midi_tool_resize_button);
3274         midi_tool_erase_button.add (*(manage (new Image (::get_icon("midi_tool_erase")))));
3275         midi_tool_erase_button.set_relief(Gtk::RELIEF_NONE);
3276         midi_tool_buttons.push_back (&midi_tool_erase_button);
3277
3278         midi_tool_pencil_button.set_active(true);
3279         
3280         midi_tool_button_set = new GroupedButtons (midi_tool_buttons);
3281
3282         midi_tool_button_box.set_border_width (2);
3283         midi_tool_button_box.set_spacing(1);
3284         midi_tool_button_box.pack_start(midi_tool_pencil_button, true, true);
3285         midi_tool_button_box.pack_start(midi_tool_select_button, true, true);
3286         midi_tool_button_box.pack_start(midi_tool_resize_button, true, true);
3287         midi_tool_button_box.pack_start(midi_tool_erase_button , true, true);
3288         midi_tool_button_box.set_homogeneous(true);
3289
3290         midi_tool_pencil_button.set_name ("MouseModeButton");
3291         midi_tool_select_button.set_name ("MouseModeButton");
3292         midi_tool_resize_button.set_name ("MouseModeButton");
3293         midi_tool_erase_button .set_name ("MouseModeButton");
3294
3295         ARDOUR_UI::instance()->tooltips().set_tip (midi_tool_pencil_button, _("Add/Move/Stretch Notes"));
3296         ARDOUR_UI::instance()->tooltips().set_tip (midi_tool_select_button, _("Select/Move Notes"));
3297         ARDOUR_UI::instance()->tooltips().set_tip (midi_tool_resize_button, _("Resize Notes"));
3298         ARDOUR_UI::instance()->tooltips().set_tip (midi_tool_erase_button,  _("Erase Notes"));
3299
3300         midi_tool_pencil_button.unset_flags (CAN_FOCUS);
3301         midi_tool_select_button.unset_flags (CAN_FOCUS);
3302         midi_tool_resize_button.unset_flags (CAN_FOCUS);
3303         midi_tool_erase_button.unset_flags (CAN_FOCUS);
3304         
3305         midi_tool_pencil_button.signal_toggled().connect (bind (mem_fun(*this,
3306                                 &Editor::midi_edit_mode_toggled), Editing::MidiEditPencil));
3307         midi_tool_select_button.signal_toggled().connect (bind (mem_fun(*this,
3308                                 &Editor::midi_edit_mode_toggled), Editing::MidiEditSelect));
3309         midi_tool_resize_button.signal_toggled().connect (bind (mem_fun(*this,
3310                                 &Editor::midi_edit_mode_toggled), Editing::MidiEditResize));
3311         midi_tool_erase_button.signal_toggled().connect (bind (mem_fun(*this,
3312                                 &Editor::midi_edit_mode_toggled), Editing::MidiEditErase));
3313
3314         
3315         /* Midi sound notes */
3316         midi_sound_notes.add (*(manage (new Image (::get_icon("midi_sound_notes")))));
3317         midi_sound_notes.set_relief(Gtk::RELIEF_NONE);
3318         ARDOUR_UI::instance()->tooltips().set_tip (midi_sound_notes, _("Sound Notes"));
3319         midi_sound_notes.unset_flags (CAN_FOCUS);
3320         midi_sound_notes.signal_toggled().connect (mem_fun(*this,
3321                                 &Editor::midi_sound_notes_toggled));
3322         
3323         /* Panic */
3324         
3325         HBox* panic_box = manage (new HBox);
3326         midi_panic_button.set_name("MidiPanicButton");
3327         midi_panic_button.signal_pressed().connect (
3328                         mem_fun(this, &Editor::midi_panic_button_pressed));
3329         panic_box->pack_start (midi_sound_notes , true, true);
3330         panic_box->pack_start (midi_panic_button, true, true);
3331         
3332         /* Pack everything in... */
3333
3334         midi_tools_tearoff = manage (new TearOff (midi_tool_button_box));
3335         midi_tools_tearoff->set_name ("MouseModeBase");
3336
3337         /*
3338         midi_tools_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&midi_toolbar_hbox), 
3339                                              &midi_tools_tearoff->tearoff_window()));
3340         midi_tools_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&midi_toolbar_hbox), 
3341                                              &midi_tools_tearoff->tearoff_window(), 0));
3342         midi_tools_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&midi_toolbar_hbox), 
3343                                              &midi_tools_tearoff->tearoff_window()));
3344         midi_tools_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&midi_toolbar_hbox), 
3345                                               &midi_tools_tearoff->tearoff_window(), 0));
3346         */
3347
3348         midi_toolbar_hbox.set_spacing (10);
3349         midi_toolbar_hbox.set_border_width (1);
3350
3351         midi_toolbar_hbox.pack_start (*midi_tools_tearoff, false, true);
3352         
3353         midi_toolbar_hbox.pack_start(*panic_box, false, true, 4);
3354
3355         midi_tool_button_box.show_all ();
3356         midi_toolbar_hbox.show_all();
3357         midi_tools_tearoff->show_all();
3358         
3359         midi_toolbar_base.set_name ("ToolBarBase");
3360         midi_toolbar_base.add (midi_toolbar_hbox);
3361
3362         midi_toolbar_frame.set_shadow_type (SHADOW_OUT);
3363         midi_toolbar_frame.set_name ("BaseFrame");
3364         midi_toolbar_frame.add (midi_toolbar_base);
3365 }
3366
3367 int
3368 Editor::convert_drop_to_paths (vector<ustring>& paths, 
3369                                const RefPtr<Gdk::DragContext>& context,
3370                                gint                x,
3371                                gint                y,
3372                                const SelectionData& data,
3373                                guint               info,
3374                                guint               time)                               
3375
3376 {       
3377         if (session == 0) {
3378                 return -1;
3379         }
3380
3381         vector<ustring> uris = data.get_uris();
3382
3383         if (uris.empty()) {
3384
3385                 /* This is seriously fucked up. Nautilus doesn't say that its URI lists
3386                    are actually URI lists. So do it by hand.
3387                 */
3388
3389                 if (data.get_target() != "text/plain") {
3390                         return -1;
3391                 }
3392   
3393                 /* Parse the "uri-list" format that Nautilus provides, 
3394                    where each pathname is delimited by \r\n.
3395
3396                    THERE MAY BE NO NULL TERMINATING CHAR!!!
3397                 */
3398
3399                 ustring txt = data.get_text();
3400                 const char* p;
3401                 const char* q;
3402
3403                 p = (const char *) malloc (txt.length() + 1);
3404                 txt.copy ((char *) p, txt.length(), 0);
3405                 ((char*)p)[txt.length()] = '\0';
3406
3407                 while (p)
3408                 {
3409                         if (*p != '#')
3410                         {
3411                                 while (g_ascii_isspace (*p))
3412                                         p++;
3413                                 
3414                                 q = p;
3415                                 while (*q && (*q != '\n') && (*q != '\r')) {
3416                                         q++;
3417                                 }
3418                                 
3419                                 if (q > p)
3420                                 {
3421                                         q--;
3422                                         while (q > p && g_ascii_isspace (*q))
3423                                                 q--;
3424                                         
3425                                         if (q > p)
3426                                         {
3427                                                 uris.push_back (ustring (p, q - p + 1));
3428                                         }
3429                                 }
3430                         }
3431                         p = strchr (p, '\n');
3432                         if (p)
3433                                 p++;
3434                 }
3435
3436                 free ((void*)p);
3437                 
3438                 if (uris.empty()) {
3439                         return -1;
3440                 }
3441         }
3442         
3443         for (vector<ustring>::iterator i = uris.begin(); i != uris.end(); ++i) {
3444
3445                 if ((*i).substr (0,7) == "file://") {
3446                         
3447                         ustring p = *i;
3448                         PBD::url_decode (p);
3449
3450                         // scan forward past three slashes
3451                         
3452                         ustring::size_type slashcnt = 0;
3453                         ustring::size_type n = 0;
3454                         ustring::iterator x = p.begin();
3455
3456                         while (slashcnt < 3 && x != p.end()) {
3457                                 if ((*x) == '/') {
3458                                         slashcnt++;
3459                                 } else if (slashcnt == 3) {
3460                                         break;
3461                                 }
3462                                 ++n;
3463                                 ++x;
3464                         }
3465
3466                         if (slashcnt != 3 || x == p.end()) {
3467                                 error << _("malformed URL passed to drag-n-drop code") << endmsg;
3468                                 continue;
3469                         }
3470
3471                         paths.push_back (p.substr (n - 1));
3472                 }
3473         }
3474
3475         return 0;
3476 }
3477
3478 void
3479 Editor::new_tempo_section ()
3480
3481 {
3482 }
3483
3484 void
3485 Editor::map_transport_state ()
3486 {
3487         ENSURE_GUI_THREAD (mem_fun(*this, &Editor::map_transport_state));
3488
3489         if (session->transport_stopped()) {
3490                 have_pending_keyboard_selection = false;
3491         }
3492
3493         update_loop_range_view (true);
3494 }
3495
3496 /* UNDO/REDO */
3497
3498 Editor::State::State (PublicEditor const * e)
3499 {
3500         selection = new Selection (e);
3501 }
3502
3503 Editor::State::~State ()
3504 {
3505         delete selection;
3506 }
3507
3508 UndoAction
3509 Editor::get_memento () const
3510 {
3511         State *state = new State (this);
3512
3513         store_state (*state);
3514         return bind (mem_fun (*(const_cast<Editor*>(this)), &Editor::restore_state), state);
3515 }
3516
3517 void
3518 Editor::store_state (State& state) const
3519 {
3520         *state.selection = *selection;
3521 }
3522
3523 void
3524 Editor::restore_state (State *state)
3525 {
3526         if (*selection == *state->selection) {
3527                 return;
3528         }
3529
3530         *selection = *state->selection;
3531         time_selection_changed ();
3532         region_selection_changed ();   
3533
3534         /* XXX other selection change handlers? */
3535 }
3536
3537 void
3538 Editor::begin_reversible_command (string name)
3539 {
3540         if (session) {
3541                 before = &get_state();
3542                 session->begin_reversible_command (name);
3543         }
3544 }
3545
3546 void
3547 Editor::commit_reversible_command ()
3548 {
3549         if (session) {
3550                 session->commit_reversible_command (new MementoCommand<Editor>(*this, before, &get_state()));
3551         }
3552 }
3553
3554 void
3555 Editor::set_edit_group_solo (Route& route, bool yn)
3556 {
3557         RouteGroup *edit_group;
3558
3559         if ((edit_group = route.edit_group()) != 0) {
3560                 edit_group->apply (&Route::set_solo, yn, this);
3561         } else {
3562                 route.set_solo (yn, this);
3563         }
3564 }
3565
3566 void
3567 Editor::set_edit_group_mute (Route& route, bool yn)
3568 {
3569         RouteGroup *edit_group = 0;
3570
3571         if ((edit_group == route.edit_group()) != 0) {
3572                 edit_group->apply (&Route::set_mute, yn, this);
3573         } else {
3574                 route.set_mute (yn, this);
3575         }
3576 }
3577                 
3578 void
3579 Editor::history_changed ()
3580 {
3581         string label;
3582
3583         if (undo_action && session) {
3584                 if (session->undo_depth() == 0) {
3585                         label = _("Undo");
3586                 } else {
3587                         label = string_compose(_("Undo (%1)"), session->next_undo());
3588                 }
3589                 undo_action->property_label() = label;
3590         }
3591
3592         if (redo_action && session) {
3593                 if (session->redo_depth() == 0) {
3594                         label = _("Redo");
3595                 } else {
3596                         label = string_compose(_("Redo (%1)"), session->next_redo());
3597                 }
3598                 redo_action->property_label() = label;
3599         }
3600 }
3601
3602 void
3603 Editor::duplicate_dialog (bool with_dialog)
3604 {
3605         float times = 1.0f;
3606
3607         if (mouse_mode == MouseRange) {
3608                 if (selection->time.length() == 0) {
3609                         return;
3610                 }
3611         }
3612
3613         RegionSelection rs;
3614         get_regions_for_action (rs);
3615         
3616         if (mouse_mode != MouseRange) {
3617
3618                 if (rs.empty()) {
3619                         return;
3620                 }
3621         }
3622
3623         if (with_dialog) {
3624
3625                 ArdourDialog win ("Duplication Dialog");
3626                 Label  label (_("Number of Duplications:"));
3627                 Adjustment adjustment (1.0, 1.0, 1000000.0, 1.0, 5.0);
3628                 SpinButton spinner (adjustment, 0.0, 1);
3629                 HBox hbox;
3630                 
3631                 win.get_vbox()->set_spacing (12);
3632                 win.get_vbox()->pack_start (hbox);
3633                 hbox.set_border_width (6);
3634                 hbox.pack_start (label, PACK_EXPAND_PADDING, 12);
3635                 
3636                 /* dialogs have ::add_action_widget() but that puts the spinner in the wrong
3637                    place, visually. so do this by hand.
3638                 */
3639                 
3640                 hbox.pack_start (spinner, PACK_EXPAND_PADDING, 12);
3641                 spinner.signal_activate().connect (sigc::bind (mem_fun (win, &ArdourDialog::response), RESPONSE_ACCEPT));
3642                 spinner.grab_focus();
3643
3644                 hbox.show ();
3645                 label.show ();
3646                 spinner.show ();
3647                 
3648                 win.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3649                 win.add_button (_("Duplicate"), RESPONSE_ACCEPT);
3650                 win.set_default_response (RESPONSE_ACCEPT);
3651                 
3652                 win.set_position (WIN_POS_MOUSE);
3653                 
3654                 spinner.grab_focus ();
3655                 
3656                 switch (win.run ()) {
3657                 case RESPONSE_ACCEPT:
3658                         break;
3659                 default:
3660                         return;
3661                 }
3662                 
3663                 times = adjustment.get_value();
3664         }
3665
3666         if (mouse_mode == MouseRange) {
3667                 duplicate_selection (times);
3668         } else {
3669                 duplicate_some_regions (rs, times);
3670         }
3671 }
3672
3673 void
3674 Editor::show_verbose_canvas_cursor ()
3675 {
3676         verbose_canvas_cursor->raise_to_top();
3677         verbose_canvas_cursor->show();
3678         verbose_cursor_visible = true;
3679 }
3680
3681 void
3682 Editor::hide_verbose_canvas_cursor ()
3683 {
3684         verbose_canvas_cursor->hide();
3685         verbose_cursor_visible = false;
3686 }
3687
3688 double
3689 Editor::clamp_verbose_cursor_x (double x)
3690 {
3691         if (x < 0) {
3692                 x = 0;
3693         } else {
3694                 x = min (canvas_width - 200.0, x);
3695         }
3696         return x;
3697 }
3698
3699 double
3700 Editor::clamp_verbose_cursor_y (double y)
3701 {
3702         if (y < canvas_timebars_vsize) {
3703                 y = canvas_timebars_vsize;
3704         } else {
3705                 y = min (canvas_height - 50, y);
3706         }
3707         return y;
3708 }
3709
3710 void
3711 Editor::set_verbose_canvas_cursor (const string & txt, double x, double y)
3712 {
3713         verbose_canvas_cursor->property_text() = txt.c_str();
3714         /* don't get too close to the edge */
3715         verbose_canvas_cursor->property_x() = clamp_verbose_cursor_x (x);
3716         verbose_canvas_cursor->property_y() = clamp_verbose_cursor_y (y);
3717 }
3718
3719 void
3720 Editor::set_verbose_canvas_cursor_text (const string & txt)
3721 {
3722         verbose_canvas_cursor->property_text() = txt.c_str();
3723 }
3724
3725 void
3726 Editor::set_edit_mode (EditMode m)
3727 {
3728         Config->set_edit_mode (m);
3729 }
3730
3731 void
3732 Editor::cycle_edit_mode ()
3733 {
3734         switch (Config->get_edit_mode()) {
3735         case Slide:
3736                 if (Profile->get_sae()) {
3737                         Config->set_edit_mode (Lock);
3738                 } else {
3739                         Config->set_edit_mode (Splice);
3740                 }
3741                 break;
3742         case Splice:
3743                 Config->set_edit_mode (Lock);
3744                 break;
3745         case Lock:
3746                 Config->set_edit_mode (Slide);
3747                 break;
3748         }
3749 }
3750
3751 void
3752 Editor::edit_mode_selection_done ()
3753 {
3754         if (session == 0) {
3755                 return;
3756         }
3757
3758         string choice = edit_mode_selector.get_active_text();
3759         EditMode mode = Slide;
3760
3761         if (choice == _("Splice Edit")) {
3762                 mode = Splice;
3763         } else if (choice == _("Slide Edit")) {
3764                 mode = Slide;
3765         } else if (choice == _("Lock Edit")) {
3766                 mode = Lock;
3767         }
3768
3769         Config->set_edit_mode (mode);
3770 }       
3771
3772 void
3773 Editor::snap_type_selection_done ()
3774 {
3775         string choice = snap_type_selector.get_active_text();
3776         SnapType snaptype = SnapToBeat;
3777
3778         if (choice == _("Beats/3")) {
3779                 snaptype = SnapToAThirdBeat;
3780         } else if (choice == _("Beats/4")) {
3781                 snaptype = SnapToAQuarterBeat;
3782         } else if (choice == _("Beats/8")) {
3783                 snaptype = SnapToAEighthBeat;
3784         } else if (choice == _("Beats/16")) {
3785                 snaptype = SnapToASixteenthBeat;
3786         } else if (choice == _("Beats/32")) {
3787                 snaptype = SnapToAThirtysecondBeat;
3788         } else if (choice == _("Beats")) {
3789                 snaptype = SnapToBeat;
3790         } else if (choice == _("Bars")) {
3791                 snaptype = SnapToBar;
3792         } else if (choice == _("Marks")) {
3793                 snaptype = SnapToMark;
3794         } else if (choice == _("Region starts")) {
3795                 snaptype = SnapToRegionStart;
3796         } else if (choice == _("Region ends")) {
3797                 snaptype = SnapToRegionEnd;
3798         } else if (choice == _("Region bounds")) {
3799                 snaptype = SnapToRegionBoundary;
3800         } else if (choice == _("Region syncs")) {
3801                 snaptype = SnapToRegionSync;
3802         } else if (choice == _("CD Frames")) {
3803                 snaptype = SnapToCDFrame;
3804         } else if (choice == _("SMPTE Frames")) {
3805                 snaptype = SnapToSMPTEFrame;
3806         } else if (choice == _("SMPTE Seconds")) {
3807                 snaptype = SnapToSMPTESeconds;
3808         } else if (choice == _("SMPTE Minutes")) {
3809                 snaptype = SnapToSMPTEMinutes;
3810         } else if (choice == _("Seconds")) {
3811                 snaptype = SnapToSeconds;
3812         } else if (choice == _("Minutes")) {
3813                 snaptype = SnapToMinutes;
3814         }
3815
3816         RefPtr<RadioAction> ract = snap_type_action (snaptype);
3817         if (ract) {
3818                 ract->set_active ();
3819         }
3820 }       
3821
3822 void
3823 Editor::snap_mode_selection_done ()
3824 {
3825         string choice = snap_mode_selector.get_active_text();
3826         SnapMode mode = SnapNormal;
3827
3828         if (choice == _("No Grid")) {
3829                 mode = SnapOff;
3830         } else if (choice == _("Grid")) {
3831                 mode = SnapNormal;
3832         } else if (choice == _("Magnetic")) {
3833                 mode = SnapMagnetic;
3834         }
3835
3836         RefPtr<RadioAction> ract = snap_mode_action (mode);
3837
3838         if (ract) {
3839                 ract->set_active (true);
3840         }
3841 }
3842
3843 void
3844 Editor::cycle_edit_point (bool with_marker)
3845 {
3846         switch (_edit_point) {
3847         case EditAtMouse:
3848                 set_edit_point_preference (EditAtPlayhead);
3849                 break;
3850         case EditAtPlayhead:
3851                 if (with_marker) {
3852                         set_edit_point_preference (EditAtSelectedMarker);
3853                 } else {
3854                         set_edit_point_preference (EditAtMouse);
3855                 }
3856                 break;
3857         case EditAtSelectedMarker:
3858                 set_edit_point_preference (EditAtMouse);
3859                 break;
3860         }
3861 }
3862
3863 void
3864 Editor::edit_point_selection_done ()
3865 {
3866         string choice = edit_point_selector.get_active_text();
3867         EditPoint ep = EditAtSelectedMarker;
3868
3869         if (choice == _("Marker")) {
3870                 set_edit_point_preference (EditAtSelectedMarker);
3871         } else if (choice == _("Playhead")) {
3872                 set_edit_point_preference (EditAtPlayhead);
3873         } else {
3874                 set_edit_point_preference (EditAtMouse);
3875         }
3876
3877         RefPtr<RadioAction> ract = edit_point_action (ep);
3878
3879         if (ract) {
3880                 ract->set_active (true);
3881         }
3882 }
3883
3884 void
3885 Editor::zoom_focus_selection_done ()
3886 {
3887         string choice = zoom_focus_selector.get_active_text();
3888         ZoomFocus focus_type = ZoomFocusLeft;
3889
3890         if (choice == _("Left")) {
3891                 focus_type = ZoomFocusLeft;
3892         } else if (choice == _("Right")) {
3893                 focus_type = ZoomFocusRight;
3894         } else if (choice == _("Center")) {
3895                 focus_type = ZoomFocusCenter;
3896         } else if (choice == _("Play")) {
3897                 focus_type = ZoomFocusPlayhead;
3898         } else if (choice == _("Edit")) {
3899                 focus_type = ZoomFocusEdit;
3900         } else if (choice == _("Active Mark")) {
3901                 focus_type = ZoomFocusEdit;
3902         } else if (choice == _("Active Mark")) {
3903                 focus_type = ZoomFocusEdit;
3904         } else {
3905                 focus_type = ZoomFocusMouse;
3906         } 
3907         
3908         RefPtr<RadioAction> ract = zoom_focus_action (focus_type);
3909
3910         if (ract) {
3911                 ract->set_active ();
3912         }
3913 }       
3914
3915 gint
3916 Editor::edit_controls_button_release (GdkEventButton* ev)
3917 {
3918         if (Keyboard::is_context_menu_event (ev)) {
3919                 ARDOUR_UI::instance()->add_route (this);
3920         }
3921         return TRUE;
3922 }
3923
3924 gint
3925 Editor::mouse_select_button_release (GdkEventButton* ev)
3926 {
3927         /* this handles just right-clicks */
3928
3929         if (ev->button != 3) {
3930                 return false;
3931         }
3932
3933         return true;
3934 }
3935
3936 Editor::TrackViewList *
3937 Editor::get_valid_views (TimeAxisView* track, RouteGroup* group)
3938 {
3939         TrackViewList *v;
3940         TrackViewList::iterator i;
3941
3942         v = new TrackViewList;
3943
3944         if (track == 0 && group == 0) {
3945
3946                 /* all views */
3947
3948                 for (i = track_views.begin(); i != track_views.end (); ++i) {
3949                         v->push_back (*i);
3950                 }
3951
3952         } else if ((track != 0 && group == 0) || (track != 0 && group != 0 && !group->is_active())) {
3953                 
3954                 /* just the view for this track
3955                  */
3956
3957                 v->push_back (track);
3958
3959         } else {
3960                 
3961                 /* views for all tracks in the edit group */
3962                 
3963                 for (i  = track_views.begin(); i != track_views.end (); ++i) {
3964
3965                         if (group == 0 || (*i)->edit_group() == group) {
3966                                 v->push_back (*i);
3967                         }
3968                 }
3969         }
3970         
3971         return v;
3972 }
3973
3974 void
3975 Editor::set_zoom_focus (ZoomFocus f)
3976 {
3977         string str = zoom_focus_strings[(int)f];
3978
3979         if (str != zoom_focus_selector.get_active_text()) {
3980                 zoom_focus_selector.set_active_text (str);
3981         }
3982         
3983         if (zoom_focus != f) {
3984                 zoom_focus = f;
3985
3986                 ZoomFocusChanged (); /* EMIT_SIGNAL */
3987
3988                 instant_save ();
3989         }
3990 }
3991
3992 void
3993 Editor::ensure_float (Window& win)
3994 {
3995         win.set_transient_for (*this);
3996 }
3997
3998 void 
3999 Editor::pane_allocation_handler (Allocation &alloc, Paned* which)
4000 {
4001         /* recover or initialize pane positions. do this here rather than earlier because
4002            we don't want the positions to change the child allocations, which they seem to do.
4003          */
4004
4005         int pos;
4006         XMLProperty* prop;
4007         char buf[32];
4008         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
4009         int width, height;
4010         static int32_t done;
4011         XMLNode* geometry;
4012
4013         width = default_width;
4014         height = default_height;
4015
4016         if ((geometry = find_named_node (*node, "geometry")) != 0) {
4017
4018                 if ((prop = geometry->property ("x_size")) == 0) {
4019                         prop = geometry->property ("x-size");
4020                 }
4021                 if (prop) {
4022                         width = atoi (prop->value());
4023                 }
4024                 if ((prop = geometry->property ("y_size")) == 0) {
4025                         prop = geometry->property ("y-size");
4026                 }
4027                 if (prop) {
4028                         height = atoi (prop->value());
4029                 }
4030         }
4031
4032         if (which == static_cast<Paned*> (&edit_pane)) {
4033
4034                 if (done) {
4035                         return;
4036                 }
4037
4038                 if (!geometry || (prop = geometry->property ("edit-pane-pos")) == 0) {
4039                         /* initial allocation is 90% to canvas, 10% to notebook */
4040                         pos = (int) floor (alloc.get_width() * 0.90f);
4041                         snprintf (buf, sizeof(buf), "%d", pos);
4042                 } else {
4043                         pos = atoi (prop->value());
4044                 }
4045
4046                 if ((done = GTK_WIDGET(edit_pane.gobj())->allocation.width > pos)) {
4047                         edit_pane.set_position (pos);
4048                         pre_maximal_pane_position = pos;
4049                 }
4050         }
4051 }
4052
4053 void
4054 Editor::detach_tearoff (Box* b, Window* w)
4055 {
4056         if (tools_tearoff->torn_off() && 
4057             mouse_mode_tearoff->torn_off()) {
4058                 top_hbox.remove (toolbar_frame);
4059         }
4060 }
4061
4062 void
4063 Editor::reattach_tearoff (Box* b, Window* w, int32_t n)
4064 {
4065         if (toolbar_frame.get_parent() == 0) {
4066                 top_hbox.pack_end (toolbar_frame);
4067         }
4068 }
4069
4070 void
4071 Editor::set_show_measures (bool yn)
4072 {
4073         if (_show_measures != yn) {
4074                 hide_measures ();
4075
4076                 if ((_show_measures = yn) == true) {
4077                         if (tempo_lines)
4078                                 tempo_lines->show();
4079                         draw_measures ();
4080                 }
4081                 instant_save ();
4082         }
4083 }
4084
4085 void
4086 Editor::toggle_follow_playhead ()
4087 {
4088         RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
4089         if (act) {
4090                 RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
4091                 set_follow_playhead (tact->get_active());
4092         }
4093 }
4094
4095 void
4096 Editor::set_follow_playhead (bool yn)
4097 {
4098         if (_follow_playhead != yn) {
4099                 if ((_follow_playhead = yn) == true) {
4100                         /* catch up */
4101                         update_current_screen ();
4102                 }
4103                 instant_save ();
4104         }
4105 }
4106
4107 void
4108 Editor::toggle_xfade_active (boost::weak_ptr<Crossfade> wxfade)
4109 {
4110         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
4111         if (xfade) {
4112                 xfade->set_active (!xfade->active());
4113         }
4114 }
4115
4116 void
4117 Editor::toggle_xfade_length (boost::weak_ptr<Crossfade> wxfade)
4118 {
4119         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
4120         if (xfade) {
4121                 xfade->set_follow_overlap (!xfade->following_overlap());
4122         }
4123 }
4124
4125 void
4126 Editor::edit_xfade (boost::weak_ptr<Crossfade> wxfade)
4127 {
4128         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
4129
4130         if (!xfade) {
4131                 return;
4132         }
4133
4134         CrossfadeEditor cew (*session, xfade, xfade->fade_in().get_min_y(), 1.0);
4135                 
4136         ensure_float (cew);
4137         
4138         switch (cew.run ()) {
4139         case RESPONSE_ACCEPT:
4140                 break;
4141         default:
4142                 return;
4143         }
4144         
4145         cew.apply ();
4146         xfade->StateChanged (Change (~0));
4147 }
4148
4149 PlaylistSelector&
4150 Editor::playlist_selector () const
4151 {
4152         return *_playlist_selector;
4153 }
4154
4155 nframes64_t
4156 Editor::get_nudge_distance (nframes64_t pos, nframes64_t& next)
4157 {
4158         nframes64_t ret;
4159
4160         ret = nudge_clock.current_duration (pos);
4161         next = ret + 1; /* XXXX fix me */
4162
4163         return ret;
4164 }
4165
4166 void
4167 Editor::end_location_changed (Location* location)
4168 {
4169         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::end_location_changed), location));
4170         //reset_scrolling_region ();
4171         nframes64_t session_span = location->start() + (nframes64_t) floorf (current_page_frames() * 0.10f);
4172         horizontal_adjustment.set_upper (session_span / frames_per_unit);
4173 }
4174
4175 int
4176 Editor::playlist_deletion_dialog (boost::shared_ptr<Playlist> pl)
4177 {
4178         ArdourDialog dialog ("playlist deletion dialog");
4179         Label  label (string_compose (_("Playlist %1 is currently unused.\n"
4180                                         "If left alone, no audio files used by it will be cleaned.\n"
4181                                         "If deleted, audio files used by it alone by will cleaned."),
4182                                       pl->name()));
4183         
4184         dialog.set_position (WIN_POS_CENTER);
4185         dialog.get_vbox()->pack_start (label);
4186
4187         label.show ();
4188
4189         dialog.add_button (_("Delete playlist"), RESPONSE_ACCEPT);
4190         dialog.add_button (_("Keep playlist"), RESPONSE_REJECT);
4191         dialog.add_button (_("Cancel"), RESPONSE_CANCEL);
4192
4193         switch (dialog.run ()) {
4194         case RESPONSE_ACCEPT:
4195                 /* delete the playlist */
4196                 return 0;
4197                 break;
4198
4199         case RESPONSE_REJECT:
4200                 /* keep the playlist */
4201                 return 1;
4202                 break;
4203
4204         default:
4205                 break;
4206         }
4207
4208         return -1;
4209 }
4210
4211 bool
4212 Editor::audio_region_selection_covers (nframes64_t where)
4213 {
4214         for (RegionSelection::iterator a = selection->regions.begin(); a != selection->regions.end(); ++a) {
4215                 if ((*a)->region()->covers (where)) {
4216                         return true;
4217                 }
4218         }
4219
4220         return false;
4221 }
4222
4223 void
4224 Editor::prepare_for_cleanup ()
4225 {
4226         cut_buffer->clear_regions ();
4227         cut_buffer->clear_playlists ();
4228
4229         selection->clear_regions ();
4230         selection->clear_playlists ();
4231
4232         no_region_list_redisplay = true;
4233 }
4234
4235 void
4236 Editor::finish_cleanup ()
4237 {
4238         no_region_list_redisplay = false;
4239         redisplay_regions ();
4240 }
4241
4242 Location*
4243 Editor::transport_loop_location()
4244 {
4245         if (session) {
4246                 return session->locations()->auto_loop_location();
4247         } else {
4248                 return 0;
4249         }
4250 }
4251
4252 Location*
4253 Editor::transport_punch_location()
4254 {
4255         if (session) {
4256                 return session->locations()->auto_punch_location();
4257         } else {
4258                 return 0;
4259         }
4260 }
4261
4262 bool
4263 Editor::control_layout_scroll (GdkEventScroll* ev)
4264 {
4265         switch (ev->direction) {
4266         case GDK_SCROLL_UP:
4267                 scroll_tracks_up_line ();
4268                 return true;
4269                 break;
4270
4271         case GDK_SCROLL_DOWN:
4272                 scroll_tracks_down_line ();
4273                 return true;
4274                 
4275         default:
4276                 /* no left/right handling yet */
4277                 break;
4278         }
4279
4280         return false;
4281 }
4282
4283
4284 /** A new snapshot has been selected.
4285  */
4286 void
4287 Editor::snapshot_display_selection_changed ()
4288 {
4289         if (snapshot_display.get_selection()->count_selected_rows() > 0) {
4290
4291                 TreeModel::iterator i = snapshot_display.get_selection()->get_selected();
4292                 
4293                 Glib::ustring snap_name = (*i)[snapshot_display_columns.real_name];
4294
4295                 if (snap_name.length() == 0) {
4296                         return;
4297                 }
4298                 
4299                 if (session->snap_name() == snap_name) {
4300                         return;
4301                 }
4302                 
4303                 ARDOUR_UI::instance()->load_session(session->path(), string (snap_name));
4304         }
4305 }
4306
4307 bool
4308 Editor::snapshot_display_button_press (GdkEventButton* ev)
4309 {
4310         if (ev->button == 3) {
4311                 /* Right-click on the snapshot list. Work out which snapshot it
4312                    was over. */
4313                 Gtk::TreeModel::Path path;
4314                 Gtk::TreeViewColumn* col;
4315                 int cx;
4316                 int cy;
4317                 snapshot_display.get_path_at_pos ((int) ev->x, (int) ev->y, path, col, cx, cy);
4318                 Gtk::TreeModel::iterator iter = snapshot_display_model->get_iter (path);
4319                 if (iter) {
4320                         Gtk::TreeModel::Row row = *iter;
4321                         popup_snapshot_context_menu (ev->button, ev->time, row[snapshot_display_columns.real_name]);
4322                 }
4323                 return true;
4324         }
4325
4326         return false;
4327 }
4328
4329
4330 /** Pop up the snapshot display context menu.
4331  * @param button Button used to open the menu.
4332  * @param time Menu open time.
4333  * @snapshot_name Name of the snapshot that the menu click was over.
4334  */
4335
4336 void
4337 Editor::popup_snapshot_context_menu (int button, int32_t time, Glib::ustring snapshot_name)
4338 {
4339         using namespace Menu_Helpers;
4340
4341         MenuList& items (snapshot_context_menu.items());
4342         items.clear ();
4343
4344         const bool modification_allowed = (session->snap_name() != snapshot_name && session->name() != snapshot_name);
4345
4346         add_item_with_sensitivity (items, MenuElem (_("Remove"), bind (mem_fun (*this, &Editor::remove_snapshot), snapshot_name)), modification_allowed);
4347
4348         add_item_with_sensitivity (items, MenuElem (_("Rename"), bind (mem_fun (*this, &Editor::rename_snapshot), snapshot_name)), modification_allowed);
4349
4350         snapshot_context_menu.popup (button, time);
4351 }
4352
4353 void
4354 Editor::rename_snapshot (Glib::ustring old_name)
4355 {
4356         ArdourPrompter prompter(true);
4357
4358         string new_name;
4359
4360         prompter.set_name ("Prompter");
4361         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
4362         prompter.set_prompt (_("New name of snapshot"));
4363         prompter.set_initial_text (old_name);
4364         
4365         if (prompter.run() == RESPONSE_ACCEPT) {
4366                 prompter.get_result (new_name);
4367                 if (new_name.length()) {
4368                         session->rename_state (old_name, new_name);
4369                         redisplay_snapshots ();
4370                 }
4371         }
4372 }
4373
4374
4375 void
4376 Editor::remove_snapshot (Glib::ustring name)
4377 {
4378         vector<string> choices;
4379
4380         std::string prompt  = string_compose (_("Do you really want to remove snapshot \"%1\" ?\n(cannot be undone)"), name);
4381
4382         choices.push_back (_("No, do nothing."));
4383         choices.push_back (_("Yes, remove it."));
4384
4385         Gtkmm2ext::Choice prompter (prompt, choices);
4386
4387         if (prompter.run () == 1) {
4388                 session->remove_state (name);
4389                 redisplay_snapshots ();
4390         }
4391 }
4392
4393 void
4394 Editor::redisplay_snapshots ()
4395 {
4396         if (session == 0) {
4397                 return;
4398         }
4399
4400         vector<sys::path> state_file_paths;
4401
4402         get_state_files_in_directory (session->session_directory().root_path(),
4403                         state_file_paths);
4404
4405         if (state_file_paths.empty()) return;
4406
4407         vector<string> state_file_names(get_file_names_no_extension(state_file_paths));
4408
4409         snapshot_display_model->clear ();
4410
4411         for (vector<string>::iterator i = state_file_names.begin();
4412                         i != state_file_names.end(); ++i)
4413         {
4414                 string statename = (*i);
4415                 TreeModel::Row row = *(snapshot_display_model->append());
4416                 
4417                 /* this lingers on in case we ever want to change the visible
4418                    name of the snapshot.
4419                 */
4420                 
4421                 string display_name;
4422                 display_name = statename;
4423
4424                 if (statename == session->snap_name()) {
4425                         snapshot_display.get_selection()->select(row);
4426                 } 
4427                 
4428                 row[snapshot_display_columns.visible_name] = display_name;
4429                 row[snapshot_display_columns.real_name] = statename;
4430         }
4431 }
4432
4433 void
4434 Editor::session_state_saved (string snap_name)
4435 {
4436         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::session_state_saved), snap_name));
4437         redisplay_snapshots ();
4438 }
4439
4440 void
4441 Editor::maximise_editing_space ()
4442 {
4443         mouse_mode_tearoff->set_visible (false);
4444         tools_tearoff->set_visible (false);
4445
4446         pre_maximal_pane_position = edit_pane.get_position();
4447         pre_maximal_editor_width = this->get_width();
4448
4449         if(post_maximal_pane_position == 0) {
4450                 post_maximal_pane_position = edit_pane.get_width();
4451         }
4452
4453         fullscreen();
4454
4455         if(post_maximal_editor_width) {
4456                 edit_pane.set_position (post_maximal_pane_position - 
4457                         abs(post_maximal_editor_width - pre_maximal_editor_width));
4458         } else {
4459                 edit_pane.set_position (post_maximal_pane_position);
4460         }
4461 }
4462
4463 void
4464 Editor::restore_editing_space ()
4465 {
4466         // user changed width of pane during fullscreen
4467
4468         if(post_maximal_pane_position != edit_pane.get_position()) {
4469                 post_maximal_pane_position = edit_pane.get_position();
4470         }
4471
4472         unfullscreen();
4473
4474         mouse_mode_tearoff->set_visible (true);
4475         tools_tearoff->set_visible (true);
4476         post_maximal_editor_width = this->get_width();
4477
4478         edit_pane.set_position (pre_maximal_pane_position + abs(this->get_width() - pre_maximal_editor_width));
4479 }
4480
4481 /**
4482  *  Make new playlists for a given track and also any others that belong
4483  *  to the same active edit group.
4484  *  @param v Track.
4485  */
4486
4487 void 
4488 Editor::new_playlists (TimeAxisView* v)
4489 {
4490         begin_reversible_command (_("new playlists"));
4491         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4492         session->get_playlists(playlists);
4493         mapover_tracks ( bind(mem_fun (*this, &Editor::mapped_use_new_playlist), playlists), v );
4494         commit_reversible_command ();
4495 }
4496
4497 /**
4498  *  Use a copy of the current playlist for a given track and also any others that belong
4499  *  to the same active edit group.
4500  *  @param v Track.
4501  */
4502
4503 void
4504 Editor::copy_playlists (TimeAxisView* v)
4505 {
4506         begin_reversible_command (_("copy playlists"));
4507         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4508         session->get_playlists(playlists);
4509         mapover_tracks ( bind(mem_fun (*this, &Editor::mapped_use_copy_playlist), playlists), v );
4510         commit_reversible_command ();
4511 }
4512
4513 /**
4514  *  Clear the current playlist for a given track and also any others that belong
4515  *  to the same active edit group.
4516  *  @param v Track.
4517  */
4518
4519 void 
4520 Editor::clear_playlists (TimeAxisView* v)
4521 {
4522         begin_reversible_command (_("clear playlists"));
4523         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4524         session->get_playlists(playlists);
4525         mapover_tracks ( mem_fun (*this, &Editor::mapped_clear_playlist), v );
4526         commit_reversible_command ();
4527 }
4528
4529 void 
4530 Editor::mapped_use_new_playlist (RouteTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4531 {
4532         atv.use_new_playlist (sz > 1 ? false : true, playlists);
4533 }
4534
4535 void
4536 Editor::mapped_use_copy_playlist (RouteTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4537 {
4538         atv.use_copy_playlist (sz > 1 ? false : true, playlists);
4539 }
4540
4541 void 
4542 Editor::mapped_clear_playlist (RouteTimeAxisView& atv, uint32_t sz)
4543 {
4544         atv.clear_playlist ();
4545 }
4546
4547 bool
4548 Editor::on_key_press_event (GdkEventKey* ev)
4549 {
4550         return key_press_focus_accelerator_handler (*this, ev);
4551 }
4552
4553 bool
4554 Editor::on_key_release_event (GdkEventKey* ev)
4555 {
4556         return Gtk::Window::on_key_release_event (ev);
4557         // return key_press_focus_accelerator_handler (*this, ev);
4558 }
4559
4560 void
4561 Editor::reset_x_origin (nframes64_t frame)
4562 {
4563         //cerr << "resetting x origin" << endl;
4564         queue_visual_change (frame);
4565 }
4566
4567 void
4568 Editor::reset_zoom (double fpu)
4569 {
4570         queue_visual_change (fpu);
4571 }
4572
4573 void
4574 Editor::reposition_and_zoom (nframes64_t frame, double fpu)
4575 {
4576         //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
4577         reset_x_origin (frame);
4578         reset_zoom (fpu);
4579
4580         if (!no_save_visual) {
4581                 undo_visual_stack.push_back (current_visual_state(false));
4582         }
4583 }
4584
4585 Editor::VisualState*
4586 Editor::current_visual_state (bool with_tracks)
4587 {
4588         VisualState* vs = new VisualState;
4589         vs->y_position = vertical_adjustment.get_value();
4590         vs->frames_per_unit = frames_per_unit;
4591         vs->leftmost_frame = leftmost_frame;
4592         vs->zoom_focus = zoom_focus;
4593         vs->zoomed_to_region = zoomed_to_region;
4594
4595         if (with_tracks) {
4596                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4597                         vs->track_states.push_back (TAVState ((*i), &(*i)->get_state()));
4598                 }
4599         }
4600         
4601         return vs;
4602 }
4603
4604 void
4605 Editor::undo_visual_state ()
4606 {
4607         if (undo_visual_stack.empty()) {
4608                 return;
4609         }
4610
4611         VisualState* vs = undo_visual_stack.back();
4612         undo_visual_stack.pop_back();
4613         use_visual_state (*vs);
4614         redo_visual_stack.push_back (vs);
4615 }
4616
4617 void
4618 Editor::redo_visual_state ()
4619 {
4620         if (redo_visual_stack.empty()) {
4621                 return;
4622         }
4623
4624         VisualState* vs = redo_visual_stack.back();
4625         redo_visual_stack.pop_back();
4626         use_visual_state (*vs);
4627         undo_visual_stack.push_back (vs);
4628 }
4629
4630 void
4631 Editor::swap_visual_state ()
4632 {
4633         if (undo_visual_stack.empty()) {
4634                 redo_visual_state ();
4635         } else {
4636                 undo_visual_state ();
4637         }
4638 }
4639
4640 void
4641 Editor::use_visual_state (VisualState& vs)
4642 {
4643         no_save_visual = true;
4644         no_route_list_redisplay = true;
4645
4646         vertical_adjustment.set_value (vs.y_position);
4647
4648         set_zoom_focus (vs.zoom_focus);
4649         reposition_and_zoom (vs.leftmost_frame, vs.frames_per_unit);
4650         zoomed_to_region = vs.zoomed_to_region;
4651         
4652         for (list<TAVState>::iterator i = vs.track_states.begin(); i != vs.track_states.end(); ++i) {
4653                 TrackViewList::iterator t;
4654
4655                 /* check if the track still exists - it could have been deleted */
4656
4657                 if ((t = find (track_views.begin(), track_views.end(), i->first)) != track_views.end()) {
4658                         (*t)->set_state (*(i->second));
4659                 }
4660         }
4661
4662
4663         if (!vs.track_states.empty()) {
4664                 update_route_visibility ();
4665         } 
4666
4667         no_route_list_redisplay = false;
4668         redisplay_route_list ();
4669
4670         no_save_visual = false;
4671 }
4672
4673 void
4674 Editor::set_frames_per_unit (double fpu)
4675 {
4676         /* this is the core function that controls the zoom level of the canvas. it is called
4677            whenever one or more calls are made to reset_zoom(). it executes in an idle handler.
4678         */
4679
4680         if (fpu == frames_per_unit) {
4681                 return;
4682         }
4683
4684         if (fpu < 2.0) {
4685                 fpu = 2.0;
4686         }
4687
4688         
4689         /* don't allow zooms that fit more than the maximum number
4690            of frames into an 800 pixel wide space.
4691         */
4692
4693         if (max_frames / fpu < 800.0) {
4694                 return;
4695         }
4696         
4697         if (tempo_lines)
4698                 tempo_lines->tempo_map_changed();
4699
4700         frames_per_unit = fpu;
4701         post_zoom ();
4702 }
4703
4704 void
4705 Editor::post_zoom ()
4706 {
4707         nframes64_t cef = 0;
4708
4709         // convert fpu to frame count
4710
4711         nframes64_t frames = (nframes64_t) floor (frames_per_unit * canvas_width);
4712
4713         if (frames_per_unit != zoom_range_clock.current_duration()) {
4714                 zoom_range_clock.set (frames);
4715         }
4716
4717         if (mouse_mode == MouseRange && selection->time.start () != selection->time.end_frame ()) {
4718                 if (!selection->tracks.empty()) {
4719                         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4720                                 (*i)->reshow_selection (selection->time);
4721                         }
4722                 } else {
4723                         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4724                                 (*i)->reshow_selection (selection->time);
4725                         }
4726                 }
4727         }
4728
4729
4730         ZoomChanged (); /* EMIT_SIGNAL */
4731
4732         reset_hscrollbar_stepping ();
4733
4734         if (session) {
4735                 cef = session->current_end_frame() + (current_page_frames() / 10);// Add a little extra so we can see the end marker
4736         }
4737         horizontal_adjustment.set_upper (cef / frames_per_unit);
4738
4739         //reset_scrolling_region ();
4740
4741         if (playhead_cursor) {
4742                 playhead_cursor->set_position (playhead_cursor->current_frame);
4743         }
4744
4745         instant_save ();
4746 }
4747
4748 void
4749 Editor::queue_visual_change (nframes64_t where)
4750 {
4751 //      pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::TimeOrigin);
4752 //      pending_visual_change.time_origin = where;
4753
4754         if (pending_visual_change.idle_handler_id < 0) {
4755                 pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::TimeOrigin);
4756                 pending_visual_change.time_origin = where;
4757                 pending_visual_change.idle_handler_id = g_idle_add (_idle_visual_changer, this);
4758         }
4759 }
4760
4761 void
4762 Editor::queue_visual_change (double fpu)
4763 {
4764         pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::ZoomLevel);
4765         pending_visual_change.frames_per_unit = fpu;
4766
4767         if (pending_visual_change.idle_handler_id < 0) {
4768                 pending_visual_change.idle_handler_id = g_idle_add ( _idle_visual_changer, this);
4769         }
4770         
4771 }
4772
4773 int
4774 Editor::_idle_visual_changer (void* arg)
4775 {
4776         return static_cast<Editor*>(arg)->idle_visual_changer ();
4777 }
4778
4779 int
4780 Editor::idle_visual_changer ()
4781 {
4782         VisualChange::Type p = pending_visual_change.pending;
4783         pending_visual_change.pending = (VisualChange::Type) 0;
4784
4785 #ifdef FIX_THIS_FOR_V3
4786         double last_time_origin = horizontal_adjustment.get_value();
4787 #endif
4788
4789         if (p & VisualChange::ZoomLevel) {
4790                 set_frames_per_unit (pending_visual_change.frames_per_unit);
4791
4792                 compute_fixed_ruler_scale ();
4793                 compute_current_bbt_points(pending_visual_change.time_origin, pending_visual_change.time_origin + current_page_frames());
4794                 compute_bbt_ruler_scale (pending_visual_change.time_origin, pending_visual_change.time_origin + current_page_frames());
4795                 update_tempo_based_rulers ();
4796         }
4797         if (p & VisualChange::TimeOrigin) {
4798                 horizontal_adjustment.set_value (pending_visual_change.time_origin / frames_per_unit);
4799         }
4800
4801         nframes64_t csf=0, cef=0;
4802         nframes64_t current_time_origin = (nframes64_t) floor (horizontal_adjustment.get_value() * frames_per_unit);
4803         
4804         if (session) {
4805                 csf = session->current_start_frame();
4806                 cef = session->current_end_frame();
4807         }
4808         
4809         /* if we seek beyond the current end of the canvas, move the end */
4810
4811 #ifdef FIX_THIS_FOR_V3
4812         if (last_time_origin == horizontal_adjustment.get_value() ) {
4813                 /* changed signal not emitted */
4814                 update_fixed_rulers ();
4815                 redisplay_tempo (true);
4816         }
4817 #endif
4818         
4819         if (current_time_origin != pending_visual_change.time_origin) {
4820                 cef += current_page_frames() / 10; // Add a little extra so we can see the end marker
4821                 horizontal_adjustment.set_upper (cef / frames_per_unit);
4822                 horizontal_adjustment.set_value (pending_visual_change.time_origin / frames_per_unit);
4823         } else {
4824                 update_fixed_rulers();
4825                 redisplay_tempo (true);
4826         }
4827         //cerr << "Editor::idle_visual_changer () called ha v:l:u:ps:fpu = " << horizontal_adjustment.get_value() << ":" << horizontal_adjustment.get_lower() << ":" << horizontal_adjustment.get_upper() << ":" << horizontal_adjustment.get_page_size() << ":" << frames_per_unit << endl;//DEBUG
4828         pending_visual_change.idle_handler_id = -1;
4829         return 0; /* this is always a one-shot call */
4830 }
4831
4832 struct EditorOrderTimeAxisSorter {
4833     bool operator() (const TimeAxisView* a, const TimeAxisView* b) const {
4834             return a->order < b->order;
4835     }
4836 };
4837         
4838 void
4839 Editor::sort_track_selection (TrackSelection* sel)
4840 {
4841         EditorOrderTimeAxisSorter cmp;
4842
4843         if (sel) {
4844                 sel->sort (cmp);
4845         } else {
4846                 selection->tracks.sort (cmp);
4847         }
4848 }
4849
4850 nframes64_t
4851 Editor::get_preferred_edit_position (bool ignore_playhead)
4852 {
4853         bool ignored;
4854         nframes64_t where = 0;
4855         EditPoint ep = _edit_point;
4856
4857         if (entered_marker) {
4858                 return entered_marker->position();
4859         }
4860
4861         if (ignore_playhead && ep == EditAtPlayhead) {
4862                 ep = EditAtSelectedMarker;
4863         }
4864
4865         switch (ep) {
4866         case EditAtPlayhead:
4867                 where = session->audible_frame();
4868                 break;
4869                 
4870         case EditAtSelectedMarker:
4871                 if (!selection->markers.empty()) {
4872                         bool is_start;
4873                         Location* loc = find_location_from_marker (selection->markers.front(), is_start);
4874                         if (loc) {
4875                                 if (is_start) {
4876                                         where =  loc->start();
4877                                 } else {
4878                                         where = loc->end();
4879                                 }
4880                                 break;
4881                         }
4882                 } 
4883                 /* fallthru */
4884                 
4885         default:
4886         case EditAtMouse:
4887                 if (!mouse_frame (where, ignored)) {
4888                         /* XXX not right but what can we do ? */
4889                         return 0;
4890                 }
4891                 snap_to (where);
4892                 break;
4893         }
4894
4895         return where;
4896 }
4897
4898 void
4899 Editor::set_loop_range (nframes64_t start, nframes64_t end, string cmd)
4900 {
4901         if (!session) return;
4902
4903         begin_reversible_command (cmd);
4904         
4905         Location* tll;
4906
4907         if ((tll = transport_loop_location()) == 0) {
4908                 Location* loc = new Location (start, end, _("Loop"),  Location::IsAutoLoop);
4909                 XMLNode &before = session->locations()->get_state();
4910                 session->locations()->add (loc, true);
4911                 session->set_auto_loop_location (loc);
4912                 XMLNode &after = session->locations()->get_state();
4913                 session->add_command (new MementoCommand<Locations>(*(session->locations()), &before, &after));
4914         } else {
4915                 XMLNode &before = tll->get_state();
4916                 tll->set_hidden (false, this);
4917                 tll->set (start, end);
4918                 XMLNode &after = tll->get_state();
4919                 session->add_command (new MementoCommand<Location>(*tll, &before, &after));
4920         }
4921         
4922         commit_reversible_command ();
4923 }
4924
4925 void
4926 Editor::set_punch_range (nframes64_t start, nframes64_t end, string cmd)
4927 {
4928         if (!session) return;
4929
4930         begin_reversible_command (cmd);
4931         
4932         Location* tpl;
4933
4934         if ((tpl = transport_punch_location()) == 0) {
4935                 Location* loc = new Location (start, end, _("Loop"),  Location::IsAutoPunch);
4936                 XMLNode &before = session->locations()->get_state();
4937                 session->locations()->add (loc, true);
4938                 session->set_auto_loop_location (loc);
4939                 XMLNode &after = session->locations()->get_state();
4940                 session->add_command (new MementoCommand<Locations>(*(session->locations()), &before, &after));
4941         }
4942         else {
4943                 XMLNode &before = tpl->get_state();
4944                 tpl->set_hidden (false, this);
4945                 tpl->set (start, end);
4946                 XMLNode &after = tpl->get_state();
4947                 session->add_command (new MementoCommand<Location>(*tpl, &before, &after));
4948         }
4949         
4950         commit_reversible_command ();
4951 }
4952
4953 void
4954 Editor::get_regions_at (RegionSelection& rs, nframes64_t where, const TrackSelection& ts) const
4955 {
4956         const TrackSelection* tracks;
4957
4958         if (ts.empty()) {
4959                 tracks = &track_views;
4960         } else {
4961                 tracks = &ts;
4962         }
4963
4964         for (TrackSelection::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
4965         
4966                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(*t);
4967
4968                 if (atv) {
4969                         boost::shared_ptr<Diskstream> ds;
4970                         boost::shared_ptr<Playlist> pl;
4971                         
4972                         if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()))) {
4973
4974                                 Playlist::RegionList* regions = pl->regions_at ((nframes64_t) floor ( (double)where * ds->speed()));
4975
4976                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
4977
4978                                         RegionView* rv = atv->audio_view()->find_view (*i);
4979
4980                                         if (rv) {
4981                                                 rs.add (rv);
4982                                         }
4983                                 }
4984
4985                                 delete regions;
4986                         }
4987                 }
4988         }
4989 }
4990
4991 void
4992 Editor::get_regions_after (RegionSelection& rs, nframes64_t where, const TrackSelection& ts) const
4993 {
4994         const TrackSelection* tracks;
4995
4996         if (ts.empty()) {
4997                 tracks = &track_views;
4998         } else {
4999                 tracks = &ts;
5000         }
5001
5002         for (TrackSelection::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
5003         
5004                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(*t);
5005
5006                 if (atv) {
5007                         boost::shared_ptr<Diskstream> ds;
5008                         boost::shared_ptr<Playlist> pl;
5009                         
5010                         if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()))) {
5011
5012                                 Playlist::RegionList* regions = pl->regions_touched ((nframes64_t) floor ( (double)where * ds->speed()), max_frames);
5013
5014                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
5015
5016                                         RegionView* rv = atv->audio_view()->find_view (*i);
5017
5018                                         if (rv) {
5019                                                 rs.push_back (rv);
5020                                         }
5021                                 }
5022
5023                                 delete regions;
5024                         }
5025                 }
5026         }
5027 }
5028
5029 void
5030 Editor::get_regions_for_action (RegionSelection& rs, bool allow_entered)
5031 {
5032         if (selection->regions.empty()) {
5033
5034                 if (selection->tracks.empty()) {
5035
5036                         /* no regions or tracks selected
5037                         */
5038                         
5039                         if (entered_regionview && mouse_mode == Editing::MouseObject) {
5040
5041                                 /*  entered regionview is valid and we're in object mode - 
5042                                     just use entered regionview
5043                                 */
5044
5045                                 rs.add (entered_regionview);
5046                         }
5047
5048                         return;
5049
5050                 } else {
5051
5052                         /* no regions selected, so get all regions at the edit point across
5053                            all selected tracks. 
5054                         */
5055
5056                         nframes64_t where = get_preferred_edit_position();
5057                         get_regions_at (rs, where, selection->tracks);
5058
5059                         /* if the entered regionview wasn't selected and neither was its track
5060                            then add it.
5061                         */
5062
5063                         if (entered_regionview != 0 &&
5064                             !selection->selected (entered_regionview) && 
5065                             !selection->selected (&entered_regionview->get_time_axis_view())) {
5066                                 rs.add (entered_regionview);
5067                         }
5068                 }
5069
5070         } else {
5071                 
5072                 /* just use the selected regions */
5073
5074                 rs = selection->regions;
5075
5076                 /* if the entered regionview wasn't selected and we allow this sort of thing,
5077                    then add it.
5078                 */
5079
5080                 if (allow_entered && entered_regionview && !selection->selected (entered_regionview)) {
5081                         rs.add (entered_regionview);
5082                 }
5083
5084         }
5085 }
5086
5087 void
5088 Editor::get_regions_corresponding_to (boost::shared_ptr<Region> region, vector<RegionView*>& regions)
5089 {
5090
5091         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5092                 
5093                 RouteTimeAxisView* tatv;
5094                 
5095                 if ((tatv = dynamic_cast<RouteTimeAxisView*> (*i)) != 0) {
5096                         
5097                         boost::shared_ptr<Playlist> pl;
5098                         vector<boost::shared_ptr<Region> > results;
5099                         RegionView* marv;
5100                         boost::shared_ptr<Diskstream> ds;
5101                         
5102                         if ((ds = tatv->get_diskstream()) == 0) {
5103                                 /* bus */
5104                                 continue;
5105                         }
5106                         
5107                         if ((pl = (ds->playlist())) != 0) {
5108                                 pl->get_region_list_equivalent_regions (region, results);
5109                         }
5110                         
5111                         for (vector<boost::shared_ptr<Region> >::iterator ir = results.begin(); ir != results.end(); ++ir) {
5112                                 if ((marv = tatv->view()->find_view (*ir)) != 0) {
5113                                         regions.push_back (marv);
5114                                 }
5115                         }
5116                         
5117                 }
5118         }
5119 }       
5120
5121 void
5122 Editor::show_rhythm_ferret ()
5123 {
5124         if (rhythm_ferret == 0) {
5125                 rhythm_ferret = new RhythmFerret(*this);
5126         }
5127
5128         rhythm_ferret->set_session (session);
5129         rhythm_ferret->show ();
5130         rhythm_ferret->present ();
5131 }
5132
5133 void
5134 Editor::first_idle ()
5135 {
5136         MessageDialog* dialog = 0;
5137
5138         if (track_views.size() > 1) { 
5139                 dialog = new MessageDialog (*this, 
5140                                             _("Please wait while Ardour loads visual data"),
5141                                             true,
5142                                             Gtk::MESSAGE_INFO,
5143                                             Gtk::BUTTONS_NONE);
5144                 dialog->present ();
5145                 ARDOUR_UI::instance()->flush_pending ();
5146         }
5147
5148         for (TrackViewList::iterator t = track_views.begin(); t != track_views.end(); ++t) {
5149                 (*t)->first_idle();
5150         }
5151
5152         // first idle adds route children (automation tracks), so we need to redisplay here
5153         redisplay_route_list();
5154         
5155         delete dialog;
5156
5157         _have_idled = true;
5158 }
5159
5160 void
5161 Editor::start_resize_line_ops ()
5162 {
5163 #if 0
5164         old_resize_line_y = -1;
5165         resize_line_y = -1;
5166         need_resize_line = true;
5167 #endif  
5168 }
5169
5170 void
5171 Editor::end_resize_line_ops ()
5172 {
5173 #if 0
5174         need_resize_line = false;
5175
5176         if (old_resize_line_y >= 0) {
5177                 Gdk::Rectangle r (0, old_resize_line_y, (int) canvas_width, 3);
5178                 Glib::RefPtr<Gdk::Window> win = get_window();
5179                 cerr << "Final invalidation at " << old_resize_line_y << endl;
5180                 win->invalidate_rect (r, false);
5181         }
5182 #endif
5183 }
5184
5185 void
5186 Editor::queue_draw_resize_line (int at)
5187 {
5188 #if 0   
5189         Glib::RefPtr<Gdk::Window> win = get_window();
5190
5191         resize_line_y = at;
5192
5193         if (win && canvas_width) {
5194
5195                 int controls_width = controls_layout.get_width();
5196                 int xroot, discard;
5197                 
5198                 controls_layout.get_window()->get_origin (xroot, discard);
5199
5200                 if (old_resize_line_y >= 0) {
5201                         
5202                         /* redraw where it used to be */
5203                         
5204                         
5205                         Gdk::Rectangle r (0, old_resize_line_y - 1, controls_width + (int) canvas_width, 3);
5206                         win->invalidate_rect (r, true);
5207                         cerr << "invalidate " << xroot << "," << old_resize_line_y - 1 << ' ' 
5208                              << controls_width + canvas_width << " x 3\n";
5209                 }
5210
5211                 /* draw where it is */
5212
5213                 Gdk::Rectangle r (0, at - 1, controls_width + (int) canvas_width, 3);
5214                 win->invalidate_rect (r, true);
5215         }
5216 #endif
5217 }
5218
5219 bool
5220 Editor::on_expose_event (GdkEventExpose* ev)
5221 {
5222         /* cerr << "+++ editor expose "
5223              << ev->area.x << ',' << ev->area.y
5224              << ' '
5225              << ev->area.width << " x " << ev->area.height
5226              << " need reize ? " << need_resize_line
5227              << endl;
5228         */
5229         bool ret = Window::on_expose_event (ev);
5230
5231 #if 0
5232         if (need_resize_line) {
5233                 
5234                 int xroot, yroot, discard;
5235                 int controls_width;
5236
5237                 /* Our root coordinates for drawing the line will be the left edge 
5238                    of the track controls, and the upper left edge of our own window.
5239                 */
5240
5241                 get_window()->get_origin (discard, yroot);
5242                 controls_layout.get_window()->get_origin (xroot, discard);
5243                 controls_width = controls_layout.get_width();
5244                 
5245                 GdkRectangle lr;
5246                 GdkRectangle intersection;
5247
5248                 lr.x = 0;
5249                 lr.y = resize_line_y;
5250                 lr.width = controls_width + (int) canvas_width;
5251                 lr.height = 3;
5252
5253                 if (gdk_rectangle_intersect (&lr, &ev->area, &intersection)) {
5254                         
5255                         Glib::RefPtr<Gtk::Style> style (get_style());
5256                         Glib::RefPtr<Gdk::GC> black_gc (style->get_black_gc ());
5257                         Glib::RefPtr<Gdk::GC> gc = wrap (black_gc->gobj_copy(), false);
5258
5259                         /* draw on root window */
5260
5261                         GdkWindow* win = gdk_get_default_root_window();
5262                         
5263                         gc->set_subwindow (Gdk::INCLUDE_INFERIORS);
5264                         gc->set_line_attributes (3, Gdk::LINE_SOLID, 
5265                                                  Gdk::CAP_NOT_LAST,
5266                                                  Gdk::JOIN_MITER);
5267                         
5268                         gdk_draw_line (win, gc->gobj(), 
5269                                        0,
5270                                        resize_line_y, 
5271                                        (int) canvas_width + controls_width,
5272                                        resize_line_y);
5273 #if 0
5274                         cerr << "drew line @ " << xroot << ", " << yroot + resize_line_y 
5275                              << " to " << xroot + (int) canvas_width + controls_width
5276                              << ", " << yroot + resize_line_y
5277                              << endl;
5278 #endif
5279                         old_resize_line_y = resize_line_y;
5280                         cerr << "NEXT EXPOSE SHOULD BE AT " << old_resize_line_y << endl;
5281                 } else {
5282                         cerr << "no intersect with "
5283                              << lr.x << ',' << lr.y
5284                              << ' '
5285                              << lr.width << " x " << lr.height
5286                              << endl;
5287                 }
5288         }
5289
5290         //cerr << "--- editor expose\n";
5291 #endif
5292
5293         return ret;
5294 }
5295
5296 static gboolean
5297 _idle_resizer (gpointer arg)
5298 {
5299         return ((Editor*)arg)->idle_resize ();
5300 }
5301
5302 void
5303 Editor::add_to_idle_resize (TimeAxisView* view, uint32_t h)
5304 {
5305         if (resize_idle_id < 0) {
5306                 resize_idle_id = g_idle_add (_idle_resizer, this);
5307         } 
5308
5309         resize_idle_target = h;
5310
5311         pending_resizes.push_back (view);
5312
5313         if (selection->selected (view) && !selection->tracks.empty()) {
5314                 pending_resizes.insert (pending_resizes.end(), selection->tracks.begin(), selection->tracks.end());
5315         }
5316 }
5317
5318 bool
5319 Editor::idle_resize ()
5320 {
5321         for (vector<TimeAxisView*>::iterator i = pending_resizes.begin(); i != pending_resizes.end(); ++i) {
5322                 (*i)->idle_resize (resize_idle_target);
5323         }
5324         pending_resizes.clear();
5325         flush_canvas ();
5326         resize_idle_id = -1;
5327         return false;
5328 }