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