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