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