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