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