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