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