fix ordering of track view list & route list resync in editor, to avoid clearing...
[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_recording = true;
297         first_action_message = 0;
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         _xfade_visibility = true;
314         editor_ruler_menu = 0;
315         no_ruler_shown_update = false;
316         edit_group_list_menu = 0;
317         route_list_menu = 0;
318         region_list_menu = 0;
319         marker_menu = 0;
320         start_end_marker_menu = 0;
321         range_marker_menu = 0;
322         marker_menu_item = 0;
323         tm_marker_menu = 0;
324         transport_marker_menu = 0;
325         new_transport_marker_menu = 0;
326         editor_mixer_strip_width = Wide;
327         show_editor_mixer_when_tracks_arrive = false;
328         region_edit_menu_split_item = 0;
329         temp_location = 0;
330         region_edit_menu_split_multichannel_item = 0;
331         leftmost_frame = 0;
332         ignore_mouse_mode_toggle = false;
333         current_stepping_trackview = 0;
334         entered_track = 0;
335         entered_regionview = 0;
336         entered_marker = 0;
337         clear_entered_track = false;
338         _new_regionviews_show_envelope = false;
339         current_timefx = 0;
340         in_edit_group_row_change = false;
341         playhead_cursor = 0;
342         button_release_can_deselect = true;
343         _dragging_playhead = false;
344         _dragging_edit_point = false;
345         _dragging_hscrollbar = false;
346         select_new_marker = false;
347         zoomed_to_region = 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 (clicked_regionview == rv) {
859                 clicked_regionview = 0;
860         }
861
862         if (entered_regionview == rv) {
863                 set_entered_regionview (0);
864         }
865 }
866
867 void
868 Editor::set_entered_regionview (RegionView* rv)
869 {
870         if (rv == entered_regionview) {
871                 return;
872         }
873
874         if (entered_regionview) {
875                 entered_regionview->exited ();
876         }
877
878         if ((entered_regionview = rv) != 0) {
879                 entered_regionview->entered ();
880         }
881 }
882
883 void
884 Editor::set_entered_track (TimeAxisView* tav)
885 {
886         if (entered_track) {
887                 entered_track->exited ();
888         }
889
890         if ((entered_track = tav) != 0) {
891                 entered_track->entered ();
892         }
893 }
894
895 void
896 Editor::show_window ()
897 {
898         if (! is_visible ()) {
899                 show_all ();
900
901                 /* now reset all audio_time_axis heights, because widgets might need
902                    to be re-hidden
903                 */
904         
905                 TimeAxisView *tv;
906         
907                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
908                         tv = (static_cast<TimeAxisView*>(*i));
909                         tv->reset_height ();
910                 }
911         }
912         present ();
913 }
914
915 void
916 Editor::instant_save ()
917 {
918         if (!constructed || !ARDOUR_UI::instance()->session_loaded) {
919                 return;
920         }
921
922         if (session) {
923                 session->add_instant_xml(get_state(), session->path());
924         } else {
925                 Config->add_instant_xml(get_state(), get_user_ardour_path());
926         }
927 }
928
929 void
930 Editor::edit_point_clock_changed()
931 {
932         if (_dragging_edit_point) {
933                 return;
934         }
935
936         if (selection->markers.empty()) {
937                 return;
938         }
939
940         bool ignored;
941         Location* loc = find_location_from_marker (selection->markers.front(), ignored);
942
943         if (!loc) {
944                 return;
945         }
946
947         loc->move_to (edit_point_clock.current_time());
948 }
949
950 void
951 Editor::zoom_adjustment_changed ()
952 {
953         if (session == 0) {
954                 return;
955         }
956
957         double fpu = zoom_range_clock.current_duration() / canvas_width;
958
959         if (fpu < 1.0) {
960                 fpu = 1.0;
961                 zoom_range_clock.set ((nframes64_t) floor (fpu * canvas_width));
962         } else if (fpu > session->current_end_frame() / canvas_width) {
963                 fpu = session->current_end_frame() / canvas_width;
964                 zoom_range_clock.set ((nframes64_t) floor (fpu * canvas_width));
965         }
966         
967         temporal_zoom (fpu);
968 }
969
970 void
971 Editor::control_scroll (float fraction)
972 {
973         ENSURE_GUI_THREAD(bind (mem_fun (*this, &Editor::control_scroll), fraction));
974
975         if (!session) {
976                 return;
977         }
978
979         double step = fraction * current_page_frames();
980
981         /*
982                 _control_scroll_target is an optional<T>
983         
984                 it acts like a pointer to an nframes64_t, with
985                 a operator conversion to boolean to check
986                 that it has a value could possibly use
987                 playhead_cursor->current_frame to store the
988                 value and a boolean in the class to know
989                 when it's out of date
990         */
991
992         if (!_control_scroll_target) {
993                 _control_scroll_target = session->transport_frame();
994                 _dragging_playhead = true;
995         }
996
997         if ((fraction < 0.0f) && (*_control_scroll_target < (nframes64_t) fabs(step))) {
998                 *_control_scroll_target = 0;
999         } else if ((fraction > 0.0f) && (max_frames - *_control_scroll_target < step)) {
1000                 *_control_scroll_target = max_frames - (current_page_frames()*2); // allow room for slop in where the PH is on the screen
1001         } else {
1002                 *_control_scroll_target += (nframes64_t) floor (step);
1003         }
1004
1005         /* move visuals, we'll catch up with it later */
1006
1007         playhead_cursor->set_position (*_control_scroll_target);
1008         UpdateAllTransportClocks (*_control_scroll_target);
1009         
1010         if (*_control_scroll_target > (current_page_frames() / 2)) {
1011                 /* try to center PH in window */
1012                 reset_x_origin (*_control_scroll_target - (current_page_frames()/2));
1013         } else {
1014                 reset_x_origin (0);
1015         }
1016
1017         /*
1018                 Now we do a timeout to actually bring the session to the right place
1019                 according to the playhead. This is to avoid reading disk buffers on every
1020                 call to control_scroll, which is driven by ScrollTimeline and therefore
1021                 probably by a control surface wheel which can generate lots of events.
1022         */
1023         /* cancel the existing timeout */
1024
1025         control_scroll_connection.disconnect ();
1026
1027         /* add the next timeout */
1028
1029         control_scroll_connection = Glib::signal_timeout().connect (bind (mem_fun (*this, &Editor::deferred_control_scroll), *_control_scroll_target), 250);
1030 }
1031
1032 bool
1033 Editor::deferred_control_scroll (nframes64_t target)
1034 {
1035         session->request_locate (*_control_scroll_target, session->transport_rolling());
1036         // reset for next stream
1037         _control_scroll_target = boost::none;
1038         _dragging_playhead = false;
1039         return false;
1040 }
1041
1042 void
1043 Editor::access_action (std::string action_group, std::string action_item)
1044 {
1045         if (!session) {
1046                 return;
1047         }
1048
1049         ENSURE_GUI_THREAD (bind (mem_fun (*this, &Editor::access_action), action_group, action_item));
1050
1051         RefPtr<Action> act;
1052         act = ActionManager::get_action( action_group.c_str(), action_item.c_str() );
1053
1054         if (act) {
1055                 act->activate();
1056         }
1057                 
1058
1059 }
1060
1061 void
1062 Editor::on_realize ()
1063 {
1064         Window::on_realize ();
1065         Realized ();
1066 }
1067
1068 void
1069 Editor::start_scrolling ()
1070 {
1071         scroll_connection = ARDOUR_UI::instance()->SuperRapidScreenUpdate.connect 
1072                 (mem_fun(*this, &Editor::update_current_screen));
1073
1074 }
1075
1076 void
1077 Editor::stop_scrolling ()
1078 {
1079         scroll_connection.disconnect ();
1080 }
1081
1082 void
1083 Editor::map_position_change (nframes64_t frame)
1084 {
1085         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::map_position_change), frame));
1086
1087         if (session == 0 || !_follow_playhead) {
1088                 return;
1089         }
1090
1091         center_screen (frame);
1092         playhead_cursor->set_position (frame);
1093 }       
1094
1095 void
1096 Editor::center_screen (nframes64_t frame)
1097 {
1098         double page = canvas_width * frames_per_unit;
1099
1100         /* if we're off the page, then scroll.
1101          */
1102         
1103         if (frame < leftmost_frame || frame >= leftmost_frame + page) {
1104                 center_screen_internal (frame, page);
1105         }
1106 }
1107
1108 void
1109 Editor::center_screen_internal (nframes64_t frame, float page)
1110 {
1111         page /= 2;
1112                 
1113         if (frame > page) {
1114                 frame -= (nframes64_t) page;
1115         } else {
1116                 frame = 0;
1117         }
1118
1119         reset_x_origin (frame);
1120 }
1121
1122 void
1123 Editor::handle_new_duration ()
1124 {
1125         if (!session) {
1126                 return;
1127         }
1128
1129         ENSURE_GUI_THREAD (mem_fun (*this, &Editor::handle_new_duration));
1130
1131         nframes64_t new_end = session->current_end_frame() + (nframes64_t) floorf (current_page_frames() * 0.10f);
1132
1133         horizontal_adjustment.set_upper (new_end / frames_per_unit);
1134         horizontal_adjustment.set_page_size (current_page_frames()/frames_per_unit);
1135         
1136         if (horizontal_adjustment.get_value() + canvas_width > horizontal_adjustment.get_upper()) {
1137                 horizontal_adjustment.set_value (horizontal_adjustment.get_upper() - canvas_width);
1138         }
1139         //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
1140 }
1141
1142 void
1143 Editor::update_title_s (const string & snap_name)
1144 {
1145         ENSURE_GUI_THREAD(bind (mem_fun(*this, &Editor::update_title_s), snap_name));
1146         
1147         update_title ();
1148 }
1149
1150 void
1151 Editor::update_title ()
1152 {
1153         ENSURE_GUI_THREAD (mem_fun(*this, &Editor::update_title));
1154
1155         if (session) {
1156                 bool dirty = session->dirty();
1157
1158                 string session_name;
1159
1160                 if (session->snap_name() != session->name()) {
1161                         session_name = session->snap_name();
1162                 } else {
1163                         session_name = session->name();
1164                 }
1165
1166                 if (dirty) {
1167                         session_name = "*" + session_name;
1168                 }
1169
1170                 WindowTitle title(session_name);
1171                 title += Glib::get_application_name();
1172                 set_title (title.get_string());
1173         }
1174 }
1175
1176 void
1177 Editor::connect_to_session (Session *t)
1178 {
1179         session = t;
1180
1181         /* there are never any selected regions at startup */
1182
1183         sensitize_the_right_region_actions (false);
1184
1185         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
1186         set_state (*node);
1187
1188         /* catch up with the playhead */
1189
1190         session->request_locate (playhead_cursor->current_frame);
1191
1192         if (first_action_message) {
1193                 first_action_message->hide();
1194         }
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 (_("Popup 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         items.push_back (MenuElem (_("Remove sync point"), mem_fun(*this, &Editor::remove_region_sync)));
1854         items.push_back (SeparatorElem());
1855
1856         items.push_back (MenuElem (_("Audition"), mem_fun(*this, &Editor::play_selected_region)));
1857         items.push_back (MenuElem (_("Export"), mem_fun(*this, &Editor::export_region)));
1858         items.push_back (MenuElem (_("Bounce"), mem_fun(*this, &Editor::bounce_region_selection)));
1859
1860 #ifdef FFT_ANALYSIS
1861         items.push_back (MenuElem (_("Spectral Analysis"), mem_fun(*this, &Editor::analyze_region_selection)));
1862 #endif
1863
1864         items.push_back (SeparatorElem());
1865
1866         sigc::connection fooc;
1867         boost::shared_ptr<Region> region_to_check;
1868
1869         if (region) {
1870                 region_to_check = region;
1871         } else {
1872                 region_to_check = selection->regions.front()->region();
1873         }
1874
1875         items.push_back (CheckMenuElem (_("Lock")));
1876         CheckMenuItem* region_lock_item = static_cast<CheckMenuItem*>(&items.back());
1877         if (region_to_check->locked()) {
1878                 region_lock_item->set_active();
1879         }
1880         region_lock_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_region_lock));
1881         
1882         items.push_back (CheckMenuElem (_("Glue to Bars&Beats")));
1883         CheckMenuItem* bbt_glue_item = static_cast<CheckMenuItem*>(&items.back());
1884         
1885         switch (region_to_check->positional_lock_style()) {
1886         case Region::MusicTime:
1887                 bbt_glue_item->set_active (true);
1888                 break;
1889         default:
1890                 bbt_glue_item->set_active (false);
1891                 break;
1892         }
1893         
1894         bbt_glue_item->signal_activate().connect (bind (mem_fun (*this, &Editor::set_region_lock_style), Region::MusicTime));
1895         
1896         items.push_back (CheckMenuElem (_("Mute")));
1897         CheckMenuItem* region_mute_item = static_cast<CheckMenuItem*>(&items.back());
1898         fooc = region_mute_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_region_mute));
1899         if (region_to_check->muted()) {
1900                 fooc.block (true);
1901                 region_mute_item->set_active();
1902                 fooc.block (false);
1903         }
1904         
1905         if (!Profile->get_sae()) {
1906                 items.push_back (CheckMenuElem (_("Opaque")));
1907                 CheckMenuItem* region_opaque_item = static_cast<CheckMenuItem*>(&items.back());
1908                 fooc = region_opaque_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_region_opaque));
1909                 if (region_to_check->opaque()) {
1910                         fooc.block (true);
1911                         region_opaque_item->set_active();
1912                         fooc.block (false);
1913                 }
1914         }
1915         
1916         items.push_back (CheckMenuElem (_("Original position"), mem_fun(*this, &Editor::naturalize)));
1917         if (region_to_check->at_natural_position()) {
1918                 items.back().set_sensitive (false);
1919         }
1920         
1921         items.push_back (SeparatorElem());
1922         
1923         if (ar) {
1924                 
1925                 RegionView* rv = sv->find_view (ar);
1926                 AudioRegionView* arv = dynamic_cast<AudioRegionView*>(rv);
1927                 
1928                 if (!Profile->get_sae()) {
1929                         items.push_back (MenuElem (_("Reset Envelope"), mem_fun(*this, &Editor::reset_region_gain_envelopes)));
1930
1931                         items.push_back (CheckMenuElem (_("Envelope Visible")));
1932                         CheckMenuItem* region_envelope_visible_item = static_cast<CheckMenuItem*> (&items.back());
1933                         fooc = region_envelope_visible_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_gain_envelope_visibility));
1934                         if (arv->envelope_visible()) {
1935                                 fooc.block (true);
1936                                 region_envelope_visible_item->set_active (true);
1937                                 fooc.block (false);
1938                         }
1939                 
1940                         items.push_back (CheckMenuElem (_("Envelope Active")));
1941                         CheckMenuItem* region_envelope_active_item = static_cast<CheckMenuItem*> (&items.back());
1942                         fooc = region_envelope_active_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_gain_envelope_active));
1943                         
1944                         if (ar->envelope_active()) {
1945                                 fooc.block (true);
1946                                 region_envelope_active_item->set_active (true);
1947                                 fooc.block (false);
1948                         }
1949
1950                         items.push_back (SeparatorElem());
1951                 }
1952
1953                 if (ar->scale_amplitude() != 1.0f) {
1954                         items.push_back (MenuElem (_("DeNormalize"), mem_fun(*this, &Editor::denormalize_region)));
1955                 } else {
1956                         items.push_back (MenuElem (_("Normalize"), mem_fun(*this, &Editor::normalize_region)));
1957                 }
1958         }
1959
1960         items.push_back (MenuElem (_("Reverse"), mem_fun(*this, &Editor::reverse_region)));
1961         items.push_back (SeparatorElem());
1962
1963         /* range related stuff */
1964
1965         items.push_back (MenuElem (_("Add Single Range"), mem_fun (*this, &Editor::add_location_from_audio_region)));
1966         items.push_back (MenuElem (_("Add Range Markers"), mem_fun (*this, &Editor::add_locations_from_audio_region)));
1967         if (selection->regions.size() < 2) {
1968                 items.back().set_sensitive (false);
1969         }
1970
1971         items.push_back (MenuElem (_("Set Range Selection"), mem_fun (*this, &Editor::set_selection_from_audio_region)));
1972         items.push_back (SeparatorElem());
1973                          
1974         /* Nudge region */
1975
1976         Menu *nudge_menu = manage (new Menu());
1977         MenuList& nudge_items = nudge_menu->items();
1978         nudge_menu->set_name ("ArdourContextMenu");
1979         
1980         nudge_items.push_back (MenuElem (_("Nudge fwd"), (bind (mem_fun(*this, &Editor::nudge_forward), false, false))));
1981         nudge_items.push_back (MenuElem (_("Nudge bwd"), (bind (mem_fun(*this, &Editor::nudge_backward), false, false))));
1982         nudge_items.push_back (MenuElem (_("Nudge fwd by capture offset"), (mem_fun(*this, &Editor::nudge_forward_capture_offset))));
1983         nudge_items.push_back (MenuElem (_("Nudge bwd by capture offset"), (mem_fun(*this, &Editor::nudge_backward_capture_offset))));
1984
1985         items.push_back (MenuElem (_("Nudge"), *nudge_menu));
1986         items.push_back (SeparatorElem());
1987
1988         Menu *trim_menu = manage (new Menu);
1989         MenuList& trim_items = trim_menu->items();
1990         trim_menu->set_name ("ArdourContextMenu");
1991         
1992         trim_items.push_back (MenuElem (_("Start to edit point"), mem_fun(*this, &Editor::trim_region_from_edit_point)));
1993         foo_item = &trim_items.back();
1994         if (_edit_point == EditAtMouse) {
1995                 foo_item->set_sensitive (false);
1996         }
1997         trim_items.push_back (MenuElem (_("Edit point to end"), mem_fun(*this, &Editor::trim_region_to_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 (_("Trim To Loop"), mem_fun(*this, &Editor::trim_region_to_loop)));
2003         trim_items.push_back (MenuElem (_("Trim To Punch"), mem_fun(*this, &Editor::trim_region_to_punch)));
2004                              
2005         items.push_back (MenuElem (_("Trim"), *trim_menu));
2006         items.push_back (SeparatorElem());
2007
2008         items.push_back (MenuElem (_("Split"), (mem_fun(*this, &Editor::split_region))));
2009         region_edit_menu_split_item = &items.back();
2010         
2011         if (_edit_point == EditAtMouse) {
2012                 region_edit_menu_split_item->set_sensitive (false);
2013         }
2014
2015         items.push_back (MenuElem (_("Make mono regions"), (mem_fun(*this, &Editor::split_multichannel_region))));
2016         region_edit_menu_split_multichannel_item = &items.back();
2017
2018         items.push_back (MenuElem (_("Duplicate"), (bind (mem_fun(*this, &Editor::duplicate_dialog), false))));
2019         items.push_back (MenuElem (_("Multi-Duplicate"), (bind (mem_fun(*this, &Editor::duplicate_dialog), true))));
2020         items.push_back (MenuElem (_("Fill Track"), (mem_fun(*this, &Editor::region_fill_track))));
2021         items.push_back (SeparatorElem());
2022         items.push_back (MenuElem (_("Remove"), mem_fun(*this, &Editor::remove_region)));
2023
2024         /* OK, stick the region submenu at the top of the list, and then add
2025            the standard items.
2026         */
2027
2028         /* we have to hack up the region name because "_" has a special
2029            meaning for menu titles.
2030         */
2031
2032         string::size_type pos = 0;
2033         string menu_item_name = (region) ? region->name() : _("Selected regions");
2034
2035         while ((pos = menu_item_name.find ("_", pos)) != string::npos) {
2036                 menu_item_name.replace (pos, 1, "__");
2037                 pos += 2;
2038         }
2039         
2040         edit_items.push_back (MenuElem (menu_item_name, *region_menu));
2041         edit_items.push_back (SeparatorElem());
2042 }
2043
2044 void
2045 Editor::add_selection_context_items (Menu_Helpers::MenuList& items)
2046 {
2047         using namespace Menu_Helpers;
2048
2049         items.push_back (MenuElem (_("Play range"), mem_fun(*this, &Editor::play_selection)));
2050         items.push_back (MenuElem (_("Loop range"), bind (mem_fun(*this, &Editor::set_loop_from_selection), true)));
2051
2052 #ifdef FFT_ANALYSIS
2053         items.push_back (SeparatorElem());
2054         items.push_back (MenuElem (_("Spectral Analysis"), mem_fun(*this, &Editor::analyze_range_selection)));
2055 #endif
2056         
2057         items.push_back (SeparatorElem());
2058         items.push_back (MenuElem (_("Extend Range to End of Region"), bind (mem_fun(*this, &Editor::extend_selection_to_end_of_region), false)));
2059         items.push_back (MenuElem (_("Extend Range to Start of Region"), bind (mem_fun(*this, &Editor::extend_selection_to_start_of_region), false)));
2060
2061         items.push_back (SeparatorElem());
2062         items.push_back (MenuElem (_("Convert to region in-place"), mem_fun(*this, &Editor::separate_region_from_selection)));
2063         items.push_back (MenuElem (_("Convert to region in region list"), mem_fun(*this, &Editor::new_region_from_selection)));
2064         
2065         items.push_back (SeparatorElem());
2066         items.push_back (MenuElem (_("Select all in range"), mem_fun(*this, &Editor::select_all_selectables_using_time_selection)));
2067
2068         items.push_back (SeparatorElem());
2069         items.push_back (MenuElem (_("Set loop from selection"), bind (mem_fun(*this, &Editor::set_loop_from_selection), false)));
2070         items.push_back (MenuElem (_("Set punch from selection"), mem_fun(*this, &Editor::set_punch_from_selection)));
2071         
2072         items.push_back (SeparatorElem());
2073         items.push_back (MenuElem (_("Add Range Markers"), mem_fun (*this, &Editor::add_location_from_selection)));
2074         items.push_back (SeparatorElem());
2075         items.push_back (MenuElem (_("Crop region to range"), mem_fun(*this, &Editor::crop_region_to_selection)));
2076         items.push_back (MenuElem (_("Fill range with region"), mem_fun(*this, &Editor::region_fill_selection)));
2077         items.push_back (MenuElem (_("Duplicate range"), bind (mem_fun(*this, &Editor::duplicate_dialog), false)));
2078         items.push_back (MenuElem (_("Create chunk from range"), mem_fun(*this, &Editor::create_named_selection)));
2079         items.push_back (SeparatorElem());
2080         items.push_back (MenuElem (_("Consolidate range"), bind (mem_fun(*this, &Editor::bounce_range_selection), true, false)));
2081         items.push_back (MenuElem (_("Consolidate range with processing"), bind (mem_fun(*this, &Editor::bounce_range_selection), true, true)));
2082         items.push_back (MenuElem (_("Bounce range to region list"), bind (mem_fun(*this, &Editor::bounce_range_selection), false, false)));
2083         items.push_back (MenuElem (_("Bounce range to region list with processing"), bind (mem_fun(*this, &Editor::bounce_range_selection), false, true)));
2084         items.push_back (MenuElem (_("Export range"), mem_fun(*this, &Editor::export_selection)));
2085 }
2086
2087 void
2088 Editor::add_dstream_context_items (Menu_Helpers::MenuList& edit_items)
2089 {
2090         using namespace Menu_Helpers;
2091
2092         /* Playback */
2093
2094         Menu *play_menu = manage (new Menu);
2095         MenuList& play_items = play_menu->items();
2096         play_menu->set_name ("ArdourContextMenu");
2097         
2098         play_items.push_back (MenuElem (_("Play from edit point"), mem_fun(*this, &Editor::play_from_edit_point)));
2099         play_items.push_back (MenuElem (_("Play from start"), mem_fun(*this, &Editor::play_from_start)));
2100         play_items.push_back (MenuElem (_("Play region"), mem_fun(*this, &Editor::play_selected_region)));
2101         play_items.push_back (SeparatorElem());
2102         play_items.push_back (MenuElem (_("Loop Region"), mem_fun(*this, &Editor::loop_selected_region)));
2103         
2104         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2105
2106         /* Selection */
2107
2108         Menu *select_menu = manage (new Menu);
2109         MenuList& select_items = select_menu->items();
2110         select_menu->set_name ("ArdourContextMenu");
2111         
2112         select_items.push_back (MenuElem (_("Select All in track"), bind (mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2113         select_items.push_back (MenuElem (_("Select All"), bind (mem_fun(*this, &Editor::select_all), Selection::Set)));
2114         select_items.push_back (MenuElem (_("Invert selection in track"), mem_fun(*this, &Editor::invert_selection_in_track)));
2115         select_items.push_back (MenuElem (_("Invert selection"), mem_fun(*this, &Editor::invert_selection)));
2116         select_items.push_back (SeparatorElem());
2117         select_items.push_back (MenuElem (_("Set range to loop range"), mem_fun(*this, &Editor::set_selection_from_loop)));
2118         select_items.push_back (MenuElem (_("Set range to punch range"), mem_fun(*this, &Editor::set_selection_from_punch)));
2119         select_items.push_back (SeparatorElem());
2120         select_items.push_back (MenuElem (_("Select All After Edit Point"), bind (mem_fun(*this, &Editor::select_all_selectables_using_edit), true)));
2121         select_items.push_back (MenuElem (_("Select All Before Edit Point"), bind (mem_fun(*this, &Editor::select_all_selectables_using_edit), false)));
2122         select_items.push_back (MenuElem (_("Select All After Playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2123         select_items.push_back (MenuElem (_("Select All Before Playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2124         select_items.push_back (MenuElem (_("Select All Between Playhead & Edit Point"), bind (mem_fun(*this, &Editor::select_all_selectables_between), false)));
2125         select_items.push_back (MenuElem (_("Select All Within Playhead & Edit Point"), bind (mem_fun(*this, &Editor::select_all_selectables_between), true)));
2126         select_items.push_back (MenuElem (_("Select Range Between Playhead & Edit Point"), mem_fun(*this, &Editor::select_range_between)));
2127
2128         select_items.push_back (SeparatorElem());
2129
2130         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2131
2132         /* Cut-n-Paste */
2133
2134         Menu *cutnpaste_menu = manage (new Menu);
2135         MenuList& cutnpaste_items = cutnpaste_menu->items();
2136         cutnpaste_menu->set_name ("ArdourContextMenu");
2137         
2138         cutnpaste_items.push_back (MenuElem (_("Cut"), mem_fun(*this, &Editor::cut)));
2139         cutnpaste_items.push_back (MenuElem (_("Copy"), mem_fun(*this, &Editor::copy)));
2140         cutnpaste_items.push_back (MenuElem (_("Paste"), bind (mem_fun(*this, &Editor::paste), 1.0f)));
2141
2142         cutnpaste_items.push_back (SeparatorElem());
2143
2144         cutnpaste_items.push_back (MenuElem (_("Align"), bind (mem_fun(*this, &Editor::align), ARDOUR::SyncPoint)));
2145         cutnpaste_items.push_back (MenuElem (_("Align Relative"), bind (mem_fun(*this, &Editor::align_relative), ARDOUR::SyncPoint)));
2146
2147         cutnpaste_items.push_back (SeparatorElem());
2148
2149         cutnpaste_items.push_back (MenuElem (_("Insert chunk"), bind (mem_fun(*this, &Editor::paste_named_selection), 1.0f)));
2150
2151         edit_items.push_back (MenuElem (_("Edit"), *cutnpaste_menu));
2152
2153         /* Adding new material */
2154         
2155         edit_items.push_back (SeparatorElem());
2156         edit_items.push_back (MenuElem (_("Insert Selected Region"), bind (mem_fun(*this, &Editor::insert_region_list_selection), 1.0f)));
2157         edit_items.push_back (MenuElem (_("Insert Existing Audio"), bind (mem_fun(*this, &Editor::add_external_audio_action), ImportToTrack)));
2158
2159         /* Nudge track */
2160
2161         Menu *nudge_menu = manage (new Menu());
2162         MenuList& nudge_items = nudge_menu->items();
2163         nudge_menu->set_name ("ArdourContextMenu");
2164         
2165         edit_items.push_back (SeparatorElem());
2166         nudge_items.push_back (MenuElem (_("Nudge entire track fwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, true))));
2167         nudge_items.push_back (MenuElem (_("Nudge track after edit point fwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, true))));
2168         nudge_items.push_back (MenuElem (_("Nudge entire track bwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, false))));
2169         nudge_items.push_back (MenuElem (_("Nudge track after edit point bwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, false))));
2170
2171         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2172 }
2173
2174 void
2175 Editor::add_bus_context_items (Menu_Helpers::MenuList& edit_items)
2176 {
2177         using namespace Menu_Helpers;
2178
2179         /* Playback */
2180
2181         Menu *play_menu = manage (new Menu);
2182         MenuList& play_items = play_menu->items();
2183         play_menu->set_name ("ArdourContextMenu");
2184         
2185         play_items.push_back (MenuElem (_("Play from edit point"), mem_fun(*this, &Editor::play_from_edit_point)));
2186         play_items.push_back (MenuElem (_("Play from start"), mem_fun(*this, &Editor::play_from_start)));
2187         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2188
2189         /* Selection */
2190
2191         Menu *select_menu = manage (new Menu);
2192         MenuList& select_items = select_menu->items();
2193         select_menu->set_name ("ArdourContextMenu");
2194         
2195         select_items.push_back (MenuElem (_("Select All in track"), bind (mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2196         select_items.push_back (MenuElem (_("Select All"), bind (mem_fun(*this, &Editor::select_all), Selection::Set)));
2197         select_items.push_back (MenuElem (_("Invert selection in track"), mem_fun(*this, &Editor::invert_selection_in_track)));
2198         select_items.push_back (MenuElem (_("Invert selection"), mem_fun(*this, &Editor::invert_selection)));
2199         select_items.push_back (SeparatorElem());
2200         select_items.push_back (MenuElem (_("Select all after edit point"), bind (mem_fun(*this, &Editor::select_all_selectables_using_edit), true)));
2201         select_items.push_back (MenuElem (_("Select all before edit point"), bind (mem_fun(*this, &Editor::select_all_selectables_using_edit), false)));
2202         select_items.push_back (MenuElem (_("Select all after playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2203         select_items.push_back (MenuElem (_("Select all before playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2204
2205         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2206
2207         /* Cut-n-Paste */
2208
2209         Menu *cutnpaste_menu = manage (new Menu);
2210         MenuList& cutnpaste_items = cutnpaste_menu->items();
2211         cutnpaste_menu->set_name ("ArdourContextMenu");
2212         
2213         cutnpaste_items.push_back (MenuElem (_("Cut"), mem_fun(*this, &Editor::cut)));
2214         cutnpaste_items.push_back (MenuElem (_("Copy"), mem_fun(*this, &Editor::copy)));
2215         cutnpaste_items.push_back (MenuElem (_("Paste"), bind (mem_fun(*this, &Editor::paste), 1.0f)));
2216
2217         Menu *nudge_menu = manage (new Menu());
2218         MenuList& nudge_items = nudge_menu->items();
2219         nudge_menu->set_name ("ArdourContextMenu");
2220         
2221         edit_items.push_back (SeparatorElem());
2222         nudge_items.push_back (MenuElem (_("Nudge entire track fwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, true))));
2223         nudge_items.push_back (MenuElem (_("Nudge track after edit point fwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, true))));
2224         nudge_items.push_back (MenuElem (_("Nudge entire track bwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, false))));
2225         nudge_items.push_back (MenuElem (_("Nudge track after edit point bwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, false))));
2226
2227         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2228 }
2229
2230 void
2231 Editor::set_snap_to (SnapType st)
2232 {
2233         unsigned int snap_ind = (unsigned int)st;
2234         snap_type = st;
2235         
2236         if (snap_ind > snap_type_strings.size() - 1) {
2237                 snap_ind = 0;
2238                 snap_type = (SnapType)snap_ind;
2239         }
2240         
2241         string str = snap_type_strings[snap_ind];
2242
2243         if (str != snap_type_selector.get_active_text()) {
2244                 snap_type_selector.set_active_text (str);
2245         }
2246
2247         instant_save ();
2248
2249         switch (snap_type) {
2250         case SnapToAThirtysecondBeat:
2251         case SnapToASixteenthBeat:
2252         case SnapToAEighthBeat:
2253         case SnapToAQuarterBeat:
2254         case SnapToAThirdBeat:
2255                 update_tempo_based_rulers ();
2256                 break;
2257
2258         case SnapToRegionStart:
2259         case SnapToRegionEnd:
2260         case SnapToRegionSync:
2261         case SnapToRegionBoundary:
2262                 build_region_boundary_cache ();
2263                 break;
2264
2265         default:
2266                 /* relax */
2267                 break;
2268     }
2269 }
2270
2271 void
2272 Editor::set_snap_mode (SnapMode mode)
2273 {
2274         snap_mode = mode;
2275         string str = snap_mode_strings[(int)mode];
2276
2277         if (str != snap_mode_selector.get_active_text ()) {
2278                 snap_mode_selector.set_active_text (str);
2279         }
2280
2281         instant_save ();
2282 }
2283 void
2284 Editor::set_edit_point_preference (EditPoint ep, bool force)
2285 {
2286         bool changed = (_edit_point != ep);
2287
2288         _edit_point = ep;
2289         string str = edit_point_strings[(int)ep];
2290
2291         if (str != edit_point_selector.get_active_text ()) {
2292                 edit_point_selector.set_active_text (str);
2293         }
2294
2295         set_canvas_cursor ();
2296
2297         if (!force && !changed) {
2298                 return;
2299         }
2300
2301         switch (zoom_focus) {
2302         case ZoomFocusMouse:
2303         case ZoomFocusPlayhead:
2304         case ZoomFocusEdit:
2305                 switch (_edit_point) {
2306                 case EditAtMouse:
2307                         set_zoom_focus (ZoomFocusMouse);
2308                         break;
2309                 case EditAtPlayhead:
2310                         set_zoom_focus (ZoomFocusPlayhead);
2311                         break;
2312                 case EditAtSelectedMarker:
2313                         set_zoom_focus (ZoomFocusEdit);
2314                         break;
2315                 }
2316                 break;
2317         default:
2318                 break;
2319         }
2320
2321         const char* action=NULL;
2322
2323         switch (_edit_point) {
2324         case EditAtPlayhead:
2325                 action = "edit-at-playhead";
2326                 break;
2327         case EditAtSelectedMarker:
2328                 action = "edit-at-marker";
2329                 break;
2330         case EditAtMouse:
2331                 action = "edit-at-mouse";
2332                 break;
2333         }
2334
2335         Glib::RefPtr<Action> act = ActionManager::get_action ("Editor", action);
2336         if (act) {
2337                 Glib::RefPtr<RadioAction>::cast_dynamic(act)->set_active (true);
2338         }
2339
2340         nframes64_t foo;
2341         bool in_track_canvas;
2342
2343         if (!mouse_frame (foo, in_track_canvas)) {
2344                 in_track_canvas = false;
2345         }
2346
2347         reset_canvas_action_sensitivity (in_track_canvas);
2348
2349         instant_save ();
2350 }
2351
2352 int
2353 Editor::set_state (const XMLNode& node)
2354 {
2355         const XMLProperty* prop;
2356         XMLNode* geometry;
2357         int x, y, xoff, yoff;
2358         Gdk::Geometry g;
2359
2360         if ((prop = node.property ("id")) != 0) {
2361                 _id = prop->value ();
2362         }
2363
2364         g.base_width = default_width;
2365         g.base_height = default_height;
2366         x = 1;
2367         y = 1;
2368         xoff = 0;
2369         yoff = 21;
2370
2371         if ((geometry = find_named_node (node, "geometry")) != 0) {
2372
2373                 XMLProperty* prop;
2374
2375                 if ((prop = geometry->property("x_size")) == 0) {
2376                         prop = geometry->property ("x-size");
2377                 }
2378                 if (prop) {
2379                         g.base_width = atoi(prop->value());
2380                 }
2381                 if ((prop = geometry->property("y_size")) == 0) {
2382                         prop = geometry->property ("y-size");
2383                 }
2384                 if (prop) {
2385                         g.base_height = atoi(prop->value());
2386                 }
2387
2388                 if ((prop = geometry->property ("x_pos")) == 0) {
2389                         prop = geometry->property ("x-pos");
2390                 }
2391                 if (prop) {
2392                         x = atoi (prop->value());
2393
2394                 }
2395                 if ((prop = geometry->property ("y_pos")) == 0) {
2396                         prop = geometry->property ("y-pos");
2397                 }
2398                 if (prop) {
2399                         y = atoi (prop->value());
2400                 }
2401
2402                 if ((prop = geometry->property ("x_off")) == 0) {
2403                         prop = geometry->property ("x-off");
2404                 }
2405                 if (prop) {
2406                         xoff = atoi (prop->value());
2407                 }
2408                 if ((prop = geometry->property ("y_off")) == 0) {
2409                         prop = geometry->property ("y-off");
2410                 }
2411                 if (prop) {
2412                         yoff = atoi (prop->value());
2413                 }
2414
2415         }
2416
2417         set_default_size (g.base_width, g.base_height);
2418         move (x, y);
2419
2420         if (session && (prop = node.property ("playhead"))) {
2421                 nframes64_t pos = atol (prop->value().c_str());
2422                 playhead_cursor->set_position (pos);
2423         } else {
2424                 playhead_cursor->set_position (0);
2425
2426                 /* reset_x_origin() doesn't work right here, since the old
2427                    position may be zero already, and it does nothing in such
2428                    circumstances.
2429                 */
2430                 
2431                 leftmost_frame = 0;
2432                 horizontal_adjustment.set_value (0);
2433         }
2434
2435         if ((prop = node.property ("mixer-width"))) {
2436                 editor_mixer_strip_width = Width (string_2_enum (prop->value(), editor_mixer_strip_width));
2437         }
2438
2439         if ((prop = node.property ("zoom-focus"))) {
2440                 set_zoom_focus ((ZoomFocus) atoi (prop->value()));
2441         }
2442
2443         if ((prop = node.property ("zoom"))) {
2444                 reset_zoom (PBD::atof (prop->value()));
2445         }
2446
2447         if ((prop = node.property ("snap-to"))) {
2448                 set_snap_to ((SnapType) atoi (prop->value()));
2449         }
2450
2451         if ((prop = node.property ("snap-mode"))) {
2452                 set_snap_mode ((SnapMode) atoi (prop->value()));
2453         }
2454
2455         if ((prop = node.property ("edit-point"))) {
2456                 set_edit_point_preference ((EditPoint) string_2_enum (prop->value(), _edit_point), true);
2457         }
2458
2459         if ((prop = node.property ("mouse-mode"))) {
2460                 MouseMode m = str2mousemode(prop->value());
2461                 mouse_mode = MouseMode ((int) m + 1); /* lie, force mode switch */
2462                 set_mouse_mode (m, true);
2463         } else {
2464                 mouse_mode = MouseGain; /* lie, to force the mode switch */
2465                 set_mouse_mode (MouseObject, true);
2466         }
2467
2468         if ((prop = node.property ("show-waveforms"))) {
2469                 bool yn = (prop->value() == "yes");
2470                 _show_waveforms = !yn;
2471                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-waveform-visible"));
2472                 if (act) {
2473                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2474                         /* do it twice to force the change */
2475                         tact->set_active (!yn);
2476                         tact->set_active (yn);
2477                 }
2478         }
2479
2480         if ((prop = node.property ("show-waveforms-recording"))) {
2481                 bool yn = (prop->value() == "yes");
2482                 _show_waveforms_recording = !yn;
2483                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleWaveformsWhileRecording"));
2484                 if (act) {
2485                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2486                         /* do it twice to force the change */
2487                         tact->set_active (!yn);
2488                         tact->set_active (yn);
2489                 }
2490         }
2491         
2492         if ((prop = node.property ("show-measures"))) {
2493                 bool yn = (prop->value() == "yes");
2494                 _show_measures = !yn;
2495                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleMeasureVisibility"));
2496                 if (act) {
2497                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2498                         /* do it twice to force the change */
2499                         tact->set_active (!yn);
2500                         tact->set_active (yn);
2501                 }
2502         }
2503
2504         if ((prop = node.property ("follow-playhead"))) {
2505                 bool yn = (prop->value() == "yes");
2506                 set_follow_playhead (yn);
2507                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
2508                 if (act) {
2509                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2510                         if (tact->get_active() != yn) {
2511                                 tact->set_active (yn);
2512                         }
2513                 }
2514         }
2515
2516         if ((prop = node.property ("region-list-sort-type"))) {
2517                 region_list_sort_type = (Editing::RegionListSortType) -1; // force change 
2518                 reset_region_list_sort_type(str2regionlistsorttype(prop->value()));
2519         }
2520
2521         if ((prop = node.property ("xfades-visible"))) {
2522                 bool yn = (prop->value() == "yes");
2523                 _xfade_visibility = !yn;
2524                 // set_xfade_visibility (yn);
2525         }
2526
2527         if ((prop = node.property ("show-editor-mixer"))) {
2528
2529                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2530                 if (act) {
2531
2532                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2533                         bool yn = (prop->value() == X_("yes"));
2534
2535                         /* do it twice to force the change */
2536                         
2537                         tact->set_active (!yn);
2538                         tact->set_active (yn);
2539                 }
2540         }
2541
2542
2543         return 0;
2544 }
2545
2546 XMLNode&
2547 Editor::get_state ()
2548 {
2549         XMLNode* node = new XMLNode ("Editor");
2550         char buf[32];
2551
2552         _id.print (buf, sizeof (buf));
2553         node->add_property ("id", buf);
2554         
2555         if (is_realized()) {
2556                 Glib::RefPtr<Gdk::Window> win = get_window();
2557                 
2558                 int x, y, xoff, yoff, width, height;
2559                 win->get_root_origin(x, y);
2560                 win->get_position(xoff, yoff);
2561                 win->get_size(width, height);
2562                 
2563                 XMLNode* geometry = new XMLNode ("geometry");
2564
2565                 snprintf(buf, sizeof(buf), "%d", width);
2566                 geometry->add_property("x_size", string(buf));
2567                 snprintf(buf, sizeof(buf), "%d", height);
2568                 geometry->add_property("y_size", string(buf));
2569                 snprintf(buf, sizeof(buf), "%d", x);
2570                 geometry->add_property("x_pos", string(buf));
2571                 snprintf(buf, sizeof(buf), "%d", y);
2572                 geometry->add_property("y_pos", string(buf));
2573                 snprintf(buf, sizeof(buf), "%d", xoff);
2574                 geometry->add_property("x_off", string(buf));
2575                 snprintf(buf, sizeof(buf), "%d", yoff);
2576                 geometry->add_property("y_off", string(buf));
2577                 snprintf(buf,sizeof(buf), "%d",gtk_paned_get_position (static_cast<Paned*>(&edit_pane)->gobj()));
2578                 geometry->add_property("edit_pane_pos", string(buf));
2579
2580                 node->add_child_nocopy (*geometry);
2581         }
2582
2583         maybe_add_mixer_strip_width (*node);
2584         
2585         snprintf (buf, sizeof(buf), "%d", (int) zoom_focus);
2586         node->add_property ("zoom-focus", buf);
2587         snprintf (buf, sizeof(buf), "%f", frames_per_unit);
2588         node->add_property ("zoom", buf);
2589         snprintf (buf, sizeof(buf), "%d", (int) snap_type);
2590         node->add_property ("snap-to", buf);
2591         snprintf (buf, sizeof(buf), "%d", (int) snap_mode);
2592         node->add_property ("snap-mode", buf);
2593
2594         node->add_property ("edit-point", enum_2_string (_edit_point));
2595
2596         snprintf (buf, sizeof (buf), "%" PRIi64, playhead_cursor->current_frame);
2597         node->add_property ("playhead", buf);
2598
2599         node->add_property ("show-waveforms", _show_waveforms ? "yes" : "no");
2600         node->add_property ("show-waveforms-recording", _show_waveforms_recording ? "yes" : "no");
2601         node->add_property ("show-measures", _show_measures ? "yes" : "no");
2602         node->add_property ("follow-playhead", _follow_playhead ? "yes" : "no");
2603         node->add_property ("xfades-visible", _xfade_visibility ? "yes" : "no");
2604         node->add_property ("region-list-sort-type", enum2str(region_list_sort_type));
2605         node->add_property ("mouse-mode", enum2str(mouse_mode));
2606         
2607         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2608         if (act) {
2609                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2610                 node->add_property (X_("show-editor-mixer"), tact->get_active() ? "yes" : "no");
2611         }
2612
2613         return *node;
2614 }
2615
2616
2617
2618 TimeAxisView *
2619 Editor::trackview_by_y_position (double y)
2620 {
2621         for (TrackViewList::iterator iter = track_views.begin(); iter != track_views.end(); ++iter) {
2622
2623                 TimeAxisView *tv;
2624
2625                 if ((tv = (*iter)->covers_y_position (y)) != 0) {
2626                         return tv;
2627                 }
2628         }
2629
2630         return 0;
2631 }
2632
2633 void
2634 Editor::snap_to (nframes64_t& start, int32_t direction, bool for_mark)
2635 {
2636         if (!session || snap_mode == SnapOff) {
2637                 return;
2638         }
2639
2640         snap_to_internal (start, direction, for_mark);
2641 }
2642
2643 void
2644 Editor::snap_to_internal (nframes64_t& start, int32_t direction, bool for_mark)
2645 {
2646         Location* before = 0;
2647         Location* after = 0;
2648
2649         const nframes64_t one_second = session->frame_rate();
2650         const nframes64_t one_minute = session->frame_rate() * 60;
2651         const nframes64_t one_smpte_second = (nframes64_t)(rint(session->smpte_frames_per_second()) * session->frames_per_smpte_frame());
2652         nframes64_t one_smpte_minute = (nframes64_t)(rint(session->smpte_frames_per_second()) * session->frames_per_smpte_frame() * 60);
2653         nframes64_t presnap = start;
2654
2655         switch (snap_type) {
2656         case SnapToCDFrame:
2657                 if (((direction == 0) && (start % (one_second/75) > (one_second/75) / 2)) || (direction > 0)) {
2658                         start = (nframes64_t) ceil ((double) start / (one_second / 75)) * (one_second / 75);
2659                 } else {
2660                         start = (nframes64_t) floor ((double) start / (one_second / 75)) * (one_second / 75);
2661                 }
2662                 break;
2663
2664         case SnapToSMPTEFrame:
2665                 if (((direction == 0) && (fmod((double)start, (double)session->frames_per_smpte_frame()) > (session->frames_per_smpte_frame() / 2))) || (direction > 0)) {
2666                         start = (nframes64_t) (ceil ((double) start / session->frames_per_smpte_frame()) * session->frames_per_smpte_frame());
2667                 } else {
2668                         start = (nframes64_t) (floor ((double) start / session->frames_per_smpte_frame()) *  session->frames_per_smpte_frame());
2669                 }
2670                 break;
2671
2672         case SnapToSMPTESeconds:
2673                 if (session->smpte_offset_negative())
2674                 {
2675                         start += session->smpte_offset ();
2676                 } else {
2677                         start -= session->smpte_offset ();
2678                 }    
2679                 if (((direction == 0) && (start % one_smpte_second > one_smpte_second / 2)) || direction > 0) {
2680                         start = (nframes64_t) ceil ((double) start / one_smpte_second) * one_smpte_second;
2681                 } else {
2682                         start = (nframes64_t) floor ((double) start / one_smpte_second) * one_smpte_second;
2683                 }
2684                 
2685                 if (session->smpte_offset_negative())
2686                 {
2687                         start -= session->smpte_offset ();
2688                 } else {
2689                         start += session->smpte_offset ();
2690                 }
2691                 break;
2692                 
2693         case SnapToSMPTEMinutes:
2694                 if (session->smpte_offset_negative())
2695                 {
2696                         start += session->smpte_offset ();
2697                 } else {
2698                         start -= session->smpte_offset ();
2699                 }
2700                 if (((direction == 0) && (start % one_smpte_minute > one_smpte_minute / 2)) || direction > 0) {
2701                         start = (nframes64_t) ceil ((double) start / one_smpte_minute) * one_smpte_minute;
2702                 } else {
2703                         start = (nframes64_t) floor ((double) start / one_smpte_minute) * one_smpte_minute;
2704                 }
2705                 if (session->smpte_offset_negative())
2706                 {
2707                         start -= session->smpte_offset ();
2708                 } else {
2709                         start += session->smpte_offset ();
2710                 }
2711                 break;
2712                 
2713         case SnapToSeconds:
2714                 if (((direction == 0) && (start % one_second > one_second / 2)) || (direction > 0)) {
2715                         start = (nframes64_t) ceil ((double) start / one_second) * one_second;
2716                 } else {
2717                         start = (nframes64_t) floor ((double) start / one_second) * one_second;
2718                 }
2719                 break;
2720                 
2721         case SnapToMinutes:
2722                 if (((direction == 0) && (start % one_minute > one_minute / 2)) || (direction > 0)) {
2723                         start = (nframes64_t) ceil ((double) start / one_minute) * one_minute;
2724                 } else {
2725                         start = (nframes64_t) floor ((double) start / one_minute) * one_minute;
2726                 }
2727                 break;
2728
2729         case SnapToBar:
2730                 start = session->tempo_map().round_to_bar (start, direction);
2731                 break;
2732
2733         case SnapToBeat:
2734                 start = session->tempo_map().round_to_beat (start, direction);
2735                 break;
2736
2737         case SnapToAThirtysecondBeat:
2738                 start = session->tempo_map().round_to_beat_subdivision (start, 32);
2739                 break;
2740
2741         case SnapToASixteenthBeat:
2742                 start = session->tempo_map().round_to_beat_subdivision (start, 16);
2743                 break;
2744
2745         case SnapToAEighthBeat:
2746                 start = session->tempo_map().round_to_beat_subdivision (start, 8);
2747                 break;
2748
2749         case SnapToAQuarterBeat:
2750                 start = session->tempo_map().round_to_beat_subdivision (start, 4);
2751                 break;
2752
2753         case SnapToAThirdBeat:
2754                 start = session->tempo_map().round_to_beat_subdivision (start, 3);
2755                 break;
2756
2757         case SnapToMark:
2758                 if (for_mark) {
2759                         return;
2760                 }
2761
2762                 before = session->locations()->first_location_before (start);
2763                 after = session->locations()->first_location_after (start);
2764
2765                 if (direction < 0) {
2766                         if (before) {
2767                                 start = before->start();
2768                         } else {
2769                                 start = 0;
2770                         }
2771                 } else if (direction > 0) {
2772                         if (after) {
2773                                 start = after->start();
2774                         } else {
2775                                 start = session->current_end_frame();
2776                         }
2777                 } else {
2778                         if (before) {
2779                                 if (after) {
2780                                         /* find nearest of the two */
2781                                         if ((start - before->start()) < (after->start() - start)) {
2782                                                 start = before->start();
2783                                         } else {
2784                                                 start = after->start();
2785                                         }
2786                                 } else {
2787                                         start = before->start();
2788                                 }
2789                         } else if (after) {
2790                                 start = after->start();
2791                         } else {
2792                                 /* relax */
2793                         }
2794                 }
2795                 break;
2796
2797         case SnapToRegionStart:
2798         case SnapToRegionEnd:
2799         case SnapToRegionSync:
2800         case SnapToRegionBoundary:
2801                 if (!region_boundary_cache.empty()) {
2802                         vector<nframes64_t>::iterator i;
2803
2804                         if (direction > 0) {
2805                                 i = std::upper_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2806                         } else {
2807                                 i = std::lower_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2808                         }
2809                         
2810                         if (i != region_boundary_cache.end()) {
2811
2812                                 /* lower bound doesn't quite to the right thing for our purposes */
2813
2814                                 if (direction < 0 && i != region_boundary_cache.begin()) {
2815                                         --i;
2816                                 }
2817
2818                                 start = *i;
2819
2820                         } else {
2821                                 start = region_boundary_cache.back();
2822                         }
2823                 } 
2824                 break;
2825         }
2826
2827         switch (snap_mode) {
2828         case SnapNormal:
2829                 return;                 
2830                 
2831         case SnapMagnetic:
2832                 
2833                 if (presnap > start) {
2834                         if (presnap > (start + unit_to_frame(snap_threshold))) {
2835                                 start = presnap;
2836                         }
2837                         
2838                 } else if (presnap < start) {
2839                         if (presnap < (start - unit_to_frame(snap_threshold))) {
2840                                 start = presnap;
2841                         }
2842                 }
2843                 
2844         default:
2845                 /* handled at entry */
2846                 return;
2847                 
2848         }
2849 }
2850
2851 void
2852 Editor::setup_toolbar ()
2853 {
2854         string pixmap_path;
2855
2856 #ifdef GTKOSX
2857         const guint32 FUDGE = 38; // Combo's are stupid - they steal space from the entry for the button
2858 #else
2859         const guint32 FUDGE = 24; // Combo's are stupid - they steal space from the entry for the button
2860 #endif
2861
2862         /* Mode Buttons (tool selection) */
2863
2864         vector<ToggleButton *> mouse_mode_buttons;
2865
2866         mouse_move_button.add (*(manage (new Image (::get_icon("tool_object")))));
2867         mouse_move_button.set_relief(Gtk::RELIEF_NONE);
2868         mouse_mode_buttons.push_back (&mouse_move_button);
2869
2870         if (!Profile->get_sae()) {
2871                 mouse_select_button.add (*(manage (new Image (get_xpm("tool_range.xpm")))));
2872                 mouse_select_button.set_relief(Gtk::RELIEF_NONE);
2873                 mouse_mode_buttons.push_back (&mouse_select_button);
2874
2875                 mouse_gain_button.add (*(manage (new Image (::get_icon("tool_gain")))));
2876                 mouse_gain_button.set_relief(Gtk::RELIEF_NONE);
2877                 mouse_mode_buttons.push_back (&mouse_gain_button);
2878         }
2879
2880         mouse_zoom_button.add (*(manage (new Image (::get_icon("tool_zoom")))));
2881         mouse_zoom_button.set_relief(Gtk::RELIEF_NONE);
2882         mouse_mode_buttons.push_back (&mouse_zoom_button);
2883         mouse_timefx_button.add (*(manage (new Image (::get_icon("tool_stretch")))));
2884         mouse_timefx_button.set_relief(Gtk::RELIEF_NONE);
2885         mouse_mode_buttons.push_back (&mouse_timefx_button);
2886         mouse_audition_button.add (*(manage (new Image (::get_icon("tool_audition")))));
2887         mouse_audition_button.set_relief(Gtk::RELIEF_NONE);
2888         mouse_mode_buttons.push_back (&mouse_audition_button);
2889         
2890         mouse_mode_button_set = new GroupedButtons (mouse_mode_buttons);
2891
2892         HBox* mode_box = manage(new HBox);
2893         mode_box->set_border_width (2);
2894         mode_box->set_spacing(4);
2895         mouse_mode_button_box.set_spacing(1);
2896         mouse_mode_button_box.pack_start(mouse_move_button, true, true);
2897         if (!Profile->get_sae()) {
2898                 mouse_mode_button_box.pack_start(mouse_select_button, true, true);
2899         }
2900         mouse_mode_button_box.pack_start(mouse_zoom_button, true, true);
2901         if (!Profile->get_sae()) {
2902                 mouse_mode_button_box.pack_start(mouse_gain_button, true, true);
2903         }
2904         mouse_mode_button_box.pack_start(mouse_timefx_button, true, true);
2905         mouse_mode_button_box.pack_start(mouse_audition_button, true, true);
2906         mouse_mode_button_box.set_homogeneous(true);
2907
2908         vector<string> edit_mode_strings;
2909         edit_mode_strings.push_back (edit_mode_to_string (Slide));
2910         if (!Profile->get_sae()) {
2911                 edit_mode_strings.push_back (edit_mode_to_string (Splice));
2912         }
2913         edit_mode_strings.push_back (edit_mode_to_string (Lock));
2914
2915         edit_mode_selector.set_name ("EditModeSelector");
2916         Gtkmm2ext::set_size_request_to_display_given_text (edit_mode_selector, edit_mode_strings, 7+FUDGE, 10);
2917         set_popdown_strings (edit_mode_selector, edit_mode_strings);
2918         edit_mode_selector.signal_changed().connect (mem_fun(*this, &Editor::edit_mode_selection_done));
2919
2920         mode_box->pack_start(edit_mode_selector);
2921         mode_box->pack_start(mouse_mode_button_box);
2922         
2923         mouse_mode_tearoff = manage (new TearOff (*mode_box));
2924         mouse_mode_tearoff->set_name ("MouseModeBase");
2925
2926         if (Profile->get_sae()) {
2927                 mouse_mode_tearoff->set_can_be_torn_off (false);
2928         }
2929
2930         mouse_mode_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2931                                                   &mouse_mode_tearoff->tearoff_window()));
2932         mouse_mode_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2933                                                   &mouse_mode_tearoff->tearoff_window(), 1));
2934         mouse_mode_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2935                                                   &mouse_mode_tearoff->tearoff_window()));
2936         mouse_mode_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2937                                                    &mouse_mode_tearoff->tearoff_window(), 1));
2938
2939         mouse_move_button.set_name ("MouseModeButton");
2940         mouse_select_button.set_name ("MouseModeButton");
2941         mouse_gain_button.set_name ("MouseModeButton");
2942         mouse_zoom_button.set_name ("MouseModeButton");
2943         mouse_timefx_button.set_name ("MouseModeButton");
2944         mouse_audition_button.set_name ("MouseModeButton");
2945
2946         ARDOUR_UI::instance()->tooltips().set_tip (mouse_move_button, _("Select/Move Objects"));
2947         ARDOUR_UI::instance()->tooltips().set_tip (mouse_select_button, _("Select/Move Ranges"));
2948         ARDOUR_UI::instance()->tooltips().set_tip (mouse_gain_button, _("Draw Gain Automation"));
2949         ARDOUR_UI::instance()->tooltips().set_tip (mouse_zoom_button, _("Select Zoom Range"));
2950         ARDOUR_UI::instance()->tooltips().set_tip (mouse_timefx_button, _("Stretch/Shrink Regions"));
2951         ARDOUR_UI::instance()->tooltips().set_tip (mouse_audition_button, _("Listen to Specific Regions"));
2952
2953         mouse_move_button.unset_flags (CAN_FOCUS);
2954         mouse_select_button.unset_flags (CAN_FOCUS);
2955         mouse_gain_button.unset_flags (CAN_FOCUS);
2956         mouse_zoom_button.unset_flags (CAN_FOCUS);
2957         mouse_timefx_button.unset_flags (CAN_FOCUS);
2958         mouse_audition_button.unset_flags (CAN_FOCUS);
2959
2960         mouse_select_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseRange));
2961         mouse_select_button.signal_button_release_event().connect (mem_fun(*this, &Editor::mouse_select_button_release));
2962
2963         mouse_move_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseObject));
2964         mouse_gain_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseGain));
2965         mouse_zoom_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseZoom));
2966         mouse_timefx_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseTimeFX));
2967         mouse_audition_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseAudition));
2968
2969         // mouse_move_button.set_active (true);
2970         
2971
2972         /* Zoom */
2973         
2974         zoom_box.set_spacing (1);
2975         zoom_box.set_border_width (0);
2976
2977         zoom_in_button.set_name ("EditorTimeButton");
2978         zoom_in_button.set_size_request(-1,16);
2979         zoom_in_button.add (*(manage (new Image (::get_icon("zoom_in")))));
2980         zoom_in_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::temporal_zoom_step), false));
2981         ARDOUR_UI::instance()->tooltips().set_tip (zoom_in_button, _("Zoom In"));
2982         
2983         zoom_out_button.set_name ("EditorTimeButton");
2984         zoom_out_button.set_size_request(-1,16);
2985         zoom_out_button.add (*(manage (new Image (::get_icon("zoom_out")))));
2986         zoom_out_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::temporal_zoom_step), true));
2987         ARDOUR_UI::instance()->tooltips().set_tip (zoom_out_button, _("Zoom Out"));
2988
2989         zoom_out_full_button.set_name ("EditorTimeButton");
2990         zoom_out_full_button.set_size_request(-1,16);
2991         zoom_out_full_button.add (*(manage (new Image (::get_icon("zoom_full")))));
2992         zoom_out_full_button.signal_clicked().connect (mem_fun(*this, &Editor::temporal_zoom_session));
2993         ARDOUR_UI::instance()->tooltips().set_tip (zoom_out_full_button, _("Zoom to Session"));
2994
2995         zoom_focus_selector.set_name ("ZoomFocusSelector");
2996         Gtkmm2ext::set_size_request_to_display_given_text (zoom_focus_selector, zoom_focus_strings, 2+FUDGE, 10);
2997         set_popdown_strings (zoom_focus_selector, zoom_focus_strings);
2998         zoom_focus_selector.signal_changed().connect (mem_fun(*this, &Editor::zoom_focus_selection_done));
2999         ARDOUR_UI::instance()->tooltips().set_tip (zoom_focus_selector, _("Zoom focus"));
3000
3001         zoom_box.pack_start (zoom_focus_selector, true, true);
3002         zoom_box.pack_start (zoom_out_button, false, false);
3003         zoom_box.pack_start (zoom_in_button, false, false);
3004         zoom_box.pack_start (zoom_out_full_button, false, false);
3005
3006         snap_box.set_spacing (1);
3007         snap_box.set_border_width (2);
3008
3009         snap_type_selector.set_name ("SnapTypeSelector");
3010         Gtkmm2ext::set_size_request_to_display_given_text (snap_type_selector, snap_type_strings, 7+FUDGE, 10);
3011         set_popdown_strings (snap_type_selector, snap_type_strings);
3012         snap_type_selector.signal_changed().connect (mem_fun(*this, &Editor::snap_type_selection_done));
3013         ARDOUR_UI::instance()->tooltips().set_tip (snap_type_selector, _("Snap/Grid Units"));
3014
3015         snap_mode_selector.set_name ("SnapModeSelector");
3016         Gtkmm2ext::set_size_request_to_display_given_text (snap_mode_selector, snap_mode_strings, 7+FUDGE, 10);
3017         set_popdown_strings (snap_mode_selector, snap_mode_strings);
3018         snap_mode_selector.signal_changed().connect (mem_fun(*this, &Editor::snap_mode_selection_done));
3019         ARDOUR_UI::instance()->tooltips().set_tip (snap_mode_selector, _("Snap/Grid Mode"));
3020
3021         edit_point_selector.set_name ("EditPointSelector");
3022         Gtkmm2ext::set_size_request_to_display_given_text (edit_point_selector, edit_point_strings, 7+FUDGE, 10);
3023         set_popdown_strings (edit_point_selector, edit_point_strings);
3024         edit_point_selector.signal_changed().connect (mem_fun(*this, &Editor::edit_point_selection_done));
3025         ARDOUR_UI::instance()->tooltips().set_tip (edit_point_selector, _("Edit point"));
3026
3027         snap_box.pack_start (edit_point_clock, false, false);
3028         snap_box.pack_start (snap_mode_selector, false, false);
3029         snap_box.pack_start (snap_type_selector, false, false);
3030         snap_box.pack_start (edit_point_selector, false, false);
3031
3032         /* Nudge */
3033
3034         HBox *nudge_box = manage (new HBox);
3035         nudge_box->set_spacing(1);
3036         nudge_box->set_border_width (2);
3037
3038         nudge_forward_button.signal_button_release_event().connect (mem_fun(*this, &Editor::nudge_forward_release), false);
3039         nudge_backward_button.signal_button_release_event().connect (mem_fun(*this, &Editor::nudge_backward_release), false);
3040
3041         nudge_box->pack_start (nudge_backward_button, false, false);
3042         nudge_box->pack_start (nudge_forward_button, false, false);
3043         nudge_box->pack_start (nudge_clock, false, false);
3044
3045
3046         /* Pack everything in... */
3047
3048         HBox* hbox = new HBox;
3049         hbox->set_spacing(10);
3050
3051         tools_tearoff = new TearOff (*hbox);
3052         tools_tearoff->set_name ("MouseModeBase");
3053
3054         if (Profile->get_sae()) {
3055                 tools_tearoff->set_can_be_torn_off (false);
3056         }
3057
3058         tools_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
3059                                              &tools_tearoff->tearoff_window()));
3060         tools_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
3061                                              &tools_tearoff->tearoff_window(), 0));
3062         tools_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
3063                                              &tools_tearoff->tearoff_window()));
3064         tools_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
3065                                               &tools_tearoff->tearoff_window(), 0));
3066
3067         toolbar_hbox.set_spacing (10);
3068         toolbar_hbox.set_border_width (1);
3069
3070         toolbar_hbox.pack_start (*mouse_mode_tearoff, false, false);
3071         toolbar_hbox.pack_start (*tools_tearoff, false, false);
3072
3073         
3074         hbox->pack_start (snap_box, false, false);
3075         // hbox->pack_start (zoom_box, false, false); 
3076         hbox->pack_start (*nudge_box, false, false);
3077
3078         hbox->show_all ();
3079         
3080         toolbar_base.set_name ("ToolBarBase");
3081         toolbar_base.add (toolbar_hbox);
3082
3083         toolbar_frame.set_shadow_type (SHADOW_OUT);
3084         toolbar_frame.set_name ("BaseFrame");
3085         toolbar_frame.add (toolbar_base);
3086 }
3087
3088 int
3089 Editor::convert_drop_to_paths (vector<ustring>& paths, 
3090                                const RefPtr<Gdk::DragContext>& context,
3091                                gint                x,
3092                                gint                y,
3093                                const SelectionData& data,
3094                                guint               info,
3095                                guint               time)                               
3096
3097 {       
3098         if (session == 0) {
3099                 return -1;
3100         }
3101
3102         vector<ustring> uris = data.get_uris();
3103
3104         if (uris.empty()) {
3105
3106                 /* This is seriously fucked up. Nautilus doesn't say that its URI lists
3107                    are actually URI lists. So do it by hand.
3108                 */
3109
3110                 if (data.get_target() != "text/plain") {
3111                         return -1;
3112                 }
3113   
3114                 /* Parse the "uri-list" format that Nautilus provides, 
3115                    where each pathname is delimited by \r\n.
3116
3117                    THERE MAY BE NO NULL TERMINATING CHAR!!!
3118                 */
3119
3120                 ustring txt = data.get_text();
3121                 const char* p;
3122                 const char* q;
3123
3124                 p = (const char *) malloc (txt.length() + 1);
3125                 txt.copy ((char *) p, txt.length(), 0);
3126                 ((char*)p)[txt.length()] = '\0';
3127
3128                 while (p)
3129                 {
3130                         if (*p != '#')
3131                         {
3132                                 while (g_ascii_isspace (*p))
3133                                         p++;
3134                                 
3135                                 q = p;
3136                                 while (*q && (*q != '\n') && (*q != '\r')) {
3137                                         q++;
3138                                 }
3139                                 
3140                                 if (q > p)
3141                                 {
3142                                         q--;
3143                                         while (q > p && g_ascii_isspace (*q))
3144                                                 q--;
3145                                         
3146                                         if (q > p)
3147                                         {
3148                                                 uris.push_back (ustring (p, q - p + 1));
3149                                         }
3150                                 }
3151                         }
3152                         p = strchr (p, '\n');
3153                         if (p)
3154                                 p++;
3155                 }
3156
3157                 free ((void*)p);
3158                 
3159                 if (uris.empty()) {
3160                         return -1;
3161                 }
3162         }
3163         
3164         for (vector<ustring>::iterator i = uris.begin(); i != uris.end(); ++i) {
3165
3166                 if ((*i).substr (0,7) == "file://") {
3167
3168                         
3169                         ustring p = *i;
3170                         PBD::url_decode (p);
3171
3172                         // scan forward past three slashes
3173                         
3174                         ustring::size_type slashcnt = 0;
3175                         ustring::size_type n = 0;
3176                         ustring::iterator x = p.begin();
3177
3178                         while (slashcnt < 3 && x != p.end()) {
3179                                 if ((*x) == '/') {
3180                                         slashcnt++;
3181                                 } else if (slashcnt == 3) {
3182                                         break;
3183                                 }
3184                                 ++n;
3185                                 ++x;
3186                         }
3187
3188                         if (slashcnt != 3 || x == p.end()) {
3189                                 error << _("malformed URL passed to drag-n-drop code") << endmsg;
3190                                 continue;
3191                         }
3192
3193                         paths.push_back (p.substr (n - 1));
3194                 }
3195         }
3196
3197         return 0;
3198 }
3199
3200 void
3201 Editor::new_tempo_section ()
3202
3203 {
3204 }
3205
3206 void
3207 Editor::map_transport_state ()
3208 {
3209         ENSURE_GUI_THREAD (mem_fun(*this, &Editor::map_transport_state));
3210
3211         if (session->transport_stopped()) {
3212                 have_pending_keyboard_selection = false;
3213         }
3214
3215         update_loop_range_view (true);
3216 }
3217
3218 /* UNDO/REDO */
3219
3220 Editor::State::State ()
3221 {
3222         selection = new Selection;
3223 }
3224
3225 Editor::State::~State ()
3226 {
3227         delete selection;
3228 }
3229
3230 UndoAction
3231 Editor::get_memento () const
3232 {
3233         State *state = new State;
3234
3235         store_state (*state);
3236         return bind (mem_fun (*(const_cast<Editor*>(this)), &Editor::restore_state), state);
3237 }
3238
3239 void
3240 Editor::store_state (State& state) const
3241 {
3242         *state.selection = *selection;
3243 }
3244
3245 void
3246 Editor::restore_state (State *state)
3247 {
3248         if (*selection == *state->selection) {
3249                 return;
3250         }
3251
3252         *selection = *state->selection;
3253         time_selection_changed ();
3254         region_selection_changed ();   
3255
3256         /* XXX other selection change handlers? */
3257 }
3258
3259 void
3260 Editor::begin_reversible_command (string name)
3261 {
3262         if (session) {
3263                 // before = &get_state();
3264                 session->begin_reversible_command (name);
3265         }
3266 }
3267
3268 void
3269 Editor::commit_reversible_command ()
3270 {
3271         if (session) {
3272                 // session->commit_reversible_command (new MementoCommand<Editor>(*this, before, &get_state()));
3273                 session->commit_reversible_command ();
3274         }
3275 }
3276
3277 void
3278 Editor::set_edit_group_solo (Route& route, bool yn)
3279 {
3280         RouteGroup *edit_group;
3281
3282         if ((edit_group = route.edit_group()) != 0) {
3283                 edit_group->apply (&Route::set_solo, yn, this);
3284         } else {
3285                 route.set_solo (yn, this);
3286         }
3287 }
3288
3289 void
3290 Editor::set_edit_group_mute (Route& route, bool yn)
3291 {
3292         RouteGroup *edit_group = 0;
3293
3294         if ((edit_group == route.edit_group()) != 0) {
3295                 edit_group->apply (&Route::set_mute, yn, this);
3296         } else {
3297                 route.set_mute (yn, this);
3298         }
3299 }
3300                 
3301 void
3302 Editor::history_changed ()
3303 {
3304         string label;
3305
3306         if (undo_action && session) {
3307                 if (session->undo_depth() == 0) {
3308                         label = _("Undo");
3309                 } else {
3310                         label = string_compose(_("Undo (%1)"), session->next_undo());
3311                 }
3312                 undo_action->property_label() = label;
3313         }
3314
3315         if (redo_action && session) {
3316                 if (session->redo_depth() == 0) {
3317                         label = _("Redo");
3318                 } else {
3319                         label = string_compose(_("Redo (%1)"), session->next_redo());
3320                 }
3321                 redo_action->property_label() = label;
3322         }
3323 }
3324
3325 void
3326 Editor::duplicate_dialog (bool with_dialog)
3327 {
3328         float times = 1.0f;
3329
3330         if (mouse_mode == MouseRange) {
3331                 if (selection->time.length() == 0) {
3332                         return;
3333                 }
3334         }
3335
3336         RegionSelection rs;
3337         get_regions_for_action (rs);
3338         
3339         if (mouse_mode != MouseRange) {
3340
3341                 if (rs.empty()) {
3342                         return;
3343                 }
3344         }
3345
3346         if (with_dialog) {
3347
3348                 ArdourDialog win ("Duplication Dialog");
3349                 Label  label (_("Number of Duplications:"));
3350                 Adjustment adjustment (1.0, 1.0, 1000000.0, 1.0, 5.0);
3351                 SpinButton spinner (adjustment, 0.0, 1);
3352                 HBox hbox;
3353                 
3354                 win.get_vbox()->set_spacing (12);
3355                 win.get_vbox()->pack_start (hbox);
3356                 hbox.set_border_width (6);
3357                 hbox.pack_start (label, PACK_EXPAND_PADDING, 12);
3358                 
3359                 /* dialogs have ::add_action_widget() but that puts the spinner in the wrong
3360                    place, visually. so do this by hand.
3361                 */
3362                 
3363                 hbox.pack_start (spinner, PACK_EXPAND_PADDING, 12);
3364                 spinner.signal_activate().connect (sigc::bind (mem_fun (win, &ArdourDialog::response), RESPONSE_ACCEPT));
3365                 spinner.grab_focus();
3366
3367                 hbox.show ();
3368                 label.show ();
3369                 spinner.show ();
3370                 
3371                 win.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3372                 win.add_button (_("Duplicate"), RESPONSE_ACCEPT);
3373                 win.set_default_response (RESPONSE_ACCEPT);
3374                 
3375                 win.set_position (WIN_POS_MOUSE);
3376                 
3377                 spinner.grab_focus ();
3378                 
3379                 switch (win.run ()) {
3380                 case RESPONSE_ACCEPT:
3381                         break;
3382                 default:
3383                         return;
3384                 }
3385                 
3386                 times = adjustment.get_value();
3387         }
3388
3389         if (mouse_mode == MouseRange) {
3390                 duplicate_selection (times);
3391         } else {
3392                 duplicate_some_regions (rs, times);
3393         }
3394 }
3395
3396 void
3397 Editor::show_verbose_canvas_cursor ()
3398 {
3399         verbose_canvas_cursor->raise_to_top();
3400         verbose_canvas_cursor->show();
3401         verbose_cursor_visible = true;
3402 }
3403
3404 void
3405 Editor::hide_verbose_canvas_cursor ()
3406 {
3407         verbose_canvas_cursor->hide();
3408         verbose_cursor_visible = false;
3409 }
3410
3411 double
3412 Editor::clamp_verbose_cursor_x (double x)
3413 {
3414         if (x < 0) {
3415                 x = 0;
3416         } else {
3417                 x = min (canvas_width - 200.0, x);
3418         }
3419         return x;
3420 }
3421
3422 double
3423 Editor::clamp_verbose_cursor_y (double y)
3424 {
3425         if (y < canvas_timebars_vsize) {
3426                 y = canvas_timebars_vsize;
3427         } else {
3428                 y = min (canvas_height - 50, y);
3429         }
3430         return y;
3431 }
3432
3433 void
3434 Editor::set_verbose_canvas_cursor (const string & txt, double x, double y)
3435 {
3436         verbose_canvas_cursor->property_text() = txt.c_str();
3437         /* don't get too close to the edge */
3438         verbose_canvas_cursor->property_x() = clamp_verbose_cursor_x (x);
3439         verbose_canvas_cursor->property_y() = clamp_verbose_cursor_y (y);
3440 }
3441
3442 void
3443 Editor::set_verbose_canvas_cursor_text (const string & txt)
3444 {
3445         verbose_canvas_cursor->property_text() = txt.c_str();
3446 }
3447
3448 void
3449 Editor::set_edit_mode (EditMode m)
3450 {
3451         Config->set_edit_mode (m);
3452 }
3453
3454 void
3455 Editor::cycle_edit_mode ()
3456 {
3457         switch (Config->get_edit_mode()) {
3458         case Slide:
3459                 if (Profile->get_sae()) {
3460                         Config->set_edit_mode (Lock);
3461                 } else {
3462                         Config->set_edit_mode (Splice);
3463                 }
3464                 break;
3465         case Splice:
3466                 Config->set_edit_mode (Lock);
3467                 break;
3468         case Lock:
3469                 Config->set_edit_mode (Slide);
3470                 break;
3471         }
3472 }
3473
3474 void
3475 Editor::edit_mode_selection_done ()
3476 {
3477         if (session == 0) {
3478                 return;
3479         }
3480
3481         string choice = edit_mode_selector.get_active_text();
3482         EditMode mode = Slide;
3483
3484         if (choice == _("Splice Edit")) {
3485                 mode = Splice;
3486         } else if (choice == _("Slide Edit")) {
3487                 mode = Slide;
3488         } else if (choice == _("Lock Edit")) {
3489                 mode = Lock;
3490         }
3491
3492         Config->set_edit_mode (mode);
3493 }       
3494
3495 void
3496 Editor::snap_type_selection_done ()
3497 {
3498         string choice = snap_type_selector.get_active_text();
3499         SnapType snaptype = SnapToBeat;
3500
3501         if (choice == _("Beats/3")) {
3502                 snaptype = SnapToAThirdBeat;
3503         } else if (choice == _("Beats/4")) {
3504                 snaptype = SnapToAQuarterBeat;
3505         } else if (choice == _("Beats/8")) {
3506                 snaptype = SnapToAEighthBeat;
3507         } else if (choice == _("Beats/16")) {
3508                 snaptype = SnapToASixteenthBeat;
3509         } else if (choice == _("Beats/32")) {
3510                 snaptype = SnapToAThirtysecondBeat;
3511         } else if (choice == _("Beats")) {
3512                 snaptype = SnapToBeat;
3513         } else if (choice == _("Bars")) {
3514                 snaptype = SnapToBar;
3515         } else if (choice == _("Marks")) {
3516                 snaptype = SnapToMark;
3517         } else if (choice == _("Region starts")) {
3518                 snaptype = SnapToRegionStart;
3519         } else if (choice == _("Region ends")) {
3520                 snaptype = SnapToRegionEnd;
3521         } else if (choice == _("Region bounds")) {
3522                 snaptype = SnapToRegionBoundary;
3523         } else if (choice == _("Region syncs")) {
3524                 snaptype = SnapToRegionSync;
3525         } else if (choice == _("CD Frames")) {
3526                 snaptype = SnapToCDFrame;
3527         } else if (choice == _("SMPTE Frames")) {
3528                 snaptype = SnapToSMPTEFrame;
3529         } else if (choice == _("SMPTE Seconds")) {
3530                 snaptype = SnapToSMPTESeconds;
3531         } else if (choice == _("SMPTE Minutes")) {
3532                 snaptype = SnapToSMPTEMinutes;
3533         } else if (choice == _("Seconds")) {
3534                 snaptype = SnapToSeconds;
3535         } else if (choice == _("Minutes")) {
3536                 snaptype = SnapToMinutes;
3537         }
3538
3539         RefPtr<RadioAction> ract = snap_type_action (snaptype);
3540         if (ract) {
3541                 ract->set_active ();
3542         }
3543 }       
3544
3545 void
3546 Editor::snap_mode_selection_done ()
3547 {
3548         string choice = snap_mode_selector.get_active_text();
3549         SnapMode mode = SnapNormal;
3550
3551         if (choice == _("No Grid")) {
3552                 mode = SnapOff;
3553         } else if (choice == _("Grid")) {
3554                 mode = SnapNormal;
3555         } else if (choice == _("Magnetic")) {
3556                 mode = SnapMagnetic;
3557         }
3558
3559         RefPtr<RadioAction> ract = snap_mode_action (mode);
3560
3561         if (ract) {
3562                 ract->set_active (true);
3563         }
3564 }
3565
3566 void
3567 Editor::cycle_edit_point (bool with_marker)
3568 {
3569         switch (_edit_point) {
3570         case EditAtMouse:
3571                 set_edit_point_preference (EditAtPlayhead);
3572                 break;
3573         case EditAtPlayhead:
3574                 if (with_marker) {
3575                         set_edit_point_preference (EditAtSelectedMarker);
3576                 } else {
3577                         set_edit_point_preference (EditAtMouse);
3578                 }
3579                 break;
3580         case EditAtSelectedMarker:
3581                 set_edit_point_preference (EditAtMouse);
3582                 break;
3583         }
3584 }
3585
3586 void
3587 Editor::edit_point_selection_done ()
3588 {
3589         string choice = edit_point_selector.get_active_text();
3590         EditPoint ep = EditAtSelectedMarker;
3591
3592         if (choice == _("Marker")) {
3593                 set_edit_point_preference (EditAtSelectedMarker);
3594         } else if (choice == _("Playhead")) {
3595                 set_edit_point_preference (EditAtPlayhead);
3596         } else {
3597                 set_edit_point_preference (EditAtMouse);
3598         }
3599
3600         RefPtr<RadioAction> ract = edit_point_action (ep);
3601
3602         if (ract) {
3603                 ract->set_active (true);
3604         }
3605 }
3606
3607 void
3608 Editor::zoom_focus_selection_done ()
3609 {
3610         string choice = zoom_focus_selector.get_active_text();
3611         ZoomFocus focus_type = ZoomFocusLeft;
3612
3613         if (choice == _("Left")) {
3614                 focus_type = ZoomFocusLeft;
3615         } else if (choice == _("Right")) {
3616                 focus_type = ZoomFocusRight;
3617         } else if (choice == _("Center")) {
3618                 focus_type = ZoomFocusCenter;
3619         } else if (choice == _("Playhead")) {
3620                 focus_type = ZoomFocusPlayhead;
3621         } else if (choice == _("Mouse")) {
3622                 focus_type = ZoomFocusMouse;
3623         } else if (choice == _("Active Mark")) {
3624                 focus_type = ZoomFocusEdit;
3625         } 
3626         
3627         RefPtr<RadioAction> ract = zoom_focus_action (focus_type);
3628
3629         if (ract) {
3630                 ract->set_active ();
3631         }
3632 }       
3633
3634 gint
3635 Editor::edit_controls_button_release (GdkEventButton* ev)
3636 {
3637         if (Keyboard::is_context_menu_event (ev)) {
3638                 ARDOUR_UI::instance()->add_route (this);
3639         }
3640         return TRUE;
3641 }
3642
3643 gint
3644 Editor::mouse_select_button_release (GdkEventButton* ev)
3645 {
3646         /* this handles just right-clicks */
3647
3648         if (ev->button != 3) {
3649                 return false;
3650         }
3651
3652         return true;
3653 }
3654
3655 Editor::TrackViewList *
3656 Editor::get_valid_views (TimeAxisView* track, RouteGroup* group)
3657 {
3658         TrackViewList *v;
3659         TrackViewList::iterator i;
3660
3661         v = new TrackViewList;
3662
3663         if (track == 0 && group == 0) {
3664
3665                 /* all views */
3666
3667                 for (i = track_views.begin(); i != track_views.end (); ++i) {
3668                         v->push_back (*i);
3669                 }
3670
3671         } else if ((track != 0 && group == 0) || (track != 0 && group != 0 && !group->is_active())) {
3672                 
3673                 /* just the view for this track
3674                  */
3675
3676                 v->push_back (track);
3677
3678         } else {
3679                 
3680                 /* views for all tracks in the edit group */
3681                 
3682                 for (i  = track_views.begin(); i != track_views.end (); ++i) {
3683
3684                         if (group == 0 || (*i)->edit_group() == group) {
3685                                 v->push_back (*i);
3686                         }
3687                 }
3688         }
3689         
3690         return v;
3691 }
3692
3693 void
3694 Editor::set_zoom_focus (ZoomFocus f)
3695 {
3696         string str = zoom_focus_strings[(int)f];
3697
3698         if (str != zoom_focus_selector.get_active_text()) {
3699                 zoom_focus_selector.set_active_text (str);
3700         }
3701         
3702         if (zoom_focus != f) {
3703                 zoom_focus = f;
3704
3705                 ZoomFocusChanged (); /* EMIT_SIGNAL */
3706
3707                 instant_save ();
3708         }
3709 }
3710
3711 void
3712 Editor::ensure_float (Window& win)
3713 {
3714         win.set_transient_for (*this);
3715 }
3716
3717 void 
3718 Editor::pane_allocation_handler (Allocation &alloc, Paned* which)
3719 {
3720         /* recover or initialize pane positions. do this here rather than earlier because
3721            we don't want the positions to change the child allocations, which they seem to do.
3722          */
3723
3724         int pos;
3725         XMLProperty* prop;
3726         char buf[32];
3727         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
3728         int width, height;
3729         static int32_t done;
3730         XMLNode* geometry;
3731
3732         width = default_width;
3733         height = default_height;
3734
3735         if ((geometry = find_named_node (*node, "geometry")) != 0) {
3736
3737                 if ((prop = geometry->property ("x_size")) == 0) {
3738                         prop = geometry->property ("x-size");
3739                 }
3740                 if (prop) {
3741                         width = atoi (prop->value());
3742                 }
3743                 if ((prop = geometry->property ("y_size")) == 0) {
3744                         prop = geometry->property ("y-size");
3745                 }
3746                 if (prop) {
3747                         height = atoi (prop->value());
3748                 }
3749         }
3750
3751         if (which == static_cast<Paned*> (&edit_pane)) {
3752
3753                 if (done) {
3754                         return;
3755                 }
3756
3757                 if (!geometry || (prop = geometry->property ("edit_pane_pos")) == 0) {
3758                         /* initial allocation is 90% to canvas, 10% to notebook */
3759                         pos = (int) floor (alloc.get_width() * 0.90f);
3760                         snprintf (buf, sizeof(buf), "%d", pos);
3761                 } else {
3762                         pos = atoi (prop->value());
3763                 }
3764                 
3765                 if ((done = GTK_WIDGET(edit_pane.gobj())->allocation.width > pos)) {
3766                         edit_pane.set_position (pos);
3767                         pre_maximal_pane_position = pos;
3768                 }
3769         }
3770 }
3771
3772 void
3773 Editor::detach_tearoff (Box* b, Window* w)
3774 {
3775         if (tools_tearoff->torn_off() && 
3776             mouse_mode_tearoff->torn_off()) {
3777                 top_hbox.remove (toolbar_frame);
3778         }
3779 }
3780
3781 void
3782 Editor::reattach_tearoff (Box* b, Window* w, int32_t n)
3783 {
3784         if (toolbar_frame.get_parent() == 0) {
3785                 top_hbox.pack_end (toolbar_frame);
3786         }
3787 }
3788
3789 void
3790 Editor::set_show_measures (bool yn)
3791 {
3792         if (_show_measures != yn) {
3793                 hide_measures ();
3794
3795                 if ((_show_measures = yn) == true) {
3796                         if (tempo_lines) {
3797                                 tempo_lines->show();
3798                         }
3799                         draw_measures ();
3800                 }
3801                 instant_save ();
3802         }
3803 }
3804
3805 void
3806 Editor::toggle_follow_playhead ()
3807 {
3808         RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
3809         if (act) {
3810                 RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
3811                 set_follow_playhead (tact->get_active());
3812         }
3813 }
3814
3815 void
3816 Editor::set_follow_playhead (bool yn)
3817 {
3818         if (_follow_playhead != yn) {
3819                 if ((_follow_playhead = yn) == true) {
3820                         /* catch up */
3821                         update_current_screen ();
3822                 }
3823                 instant_save ();
3824         }
3825 }
3826
3827 void
3828 Editor::toggle_xfade_active (boost::weak_ptr<Crossfade> wxfade)
3829 {
3830         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3831         if (xfade) {
3832                 xfade->set_active (!xfade->active());
3833         }
3834 }
3835
3836 void
3837 Editor::toggle_xfade_length (boost::weak_ptr<Crossfade> wxfade)
3838 {
3839         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3840         if (xfade) {
3841                 xfade->set_follow_overlap (!xfade->following_overlap());
3842         }
3843 }
3844
3845 void
3846 Editor::edit_xfade (boost::weak_ptr<Crossfade> wxfade)
3847 {
3848         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3849
3850         if (!xfade) {
3851                 return;
3852         }
3853
3854         CrossfadeEditor cew (*session, xfade, xfade->fade_in().get_min_y(), 1.0);
3855                 
3856         ensure_float (cew);
3857         
3858         switch (cew.run ()) {
3859         case RESPONSE_ACCEPT:
3860                 break;
3861         default:
3862                 return;
3863         }
3864         
3865         cew.apply ();
3866         xfade->StateChanged (Change (~0));
3867 }
3868
3869 PlaylistSelector&
3870 Editor::playlist_selector () const
3871 {
3872         return *_playlist_selector;
3873 }
3874
3875 nframes64_t
3876 Editor::get_nudge_distance (nframes64_t pos, nframes64_t& next)
3877 {
3878         nframes64_t ret;
3879
3880         ret = nudge_clock.current_duration (pos);
3881         next = ret + 1; /* XXXX fix me */
3882
3883         return ret;
3884 }
3885
3886 void
3887 Editor::end_location_changed (Location* location)
3888 {
3889         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::end_location_changed), location));
3890         //reset_scrolling_region ();
3891         nframes64_t session_span = location->start() + (nframes64_t) floorf (current_page_frames() * 0.10f);
3892         horizontal_adjustment.set_upper (session_span / frames_per_unit);
3893 }
3894
3895 int
3896 Editor::playlist_deletion_dialog (boost::shared_ptr<Playlist> pl)
3897 {
3898         ArdourDialog dialog ("playlist deletion dialog");
3899         Label  label (string_compose (_("Playlist %1 is currently unused.\n"
3900                                         "If left alone, no audio files used by it will be cleaned.\n"
3901                                         "If deleted, audio files used by it alone by will cleaned."),
3902                                       pl->name()));
3903         
3904         dialog.set_position (WIN_POS_CENTER);
3905         dialog.get_vbox()->pack_start (label);
3906
3907         label.show ();
3908
3909         dialog.add_button (_("Delete playlist"), RESPONSE_ACCEPT);
3910         dialog.add_button (_("Keep playlist"), RESPONSE_REJECT);
3911         dialog.add_button (_("Cancel"), RESPONSE_CANCEL);
3912
3913         switch (dialog.run ()) {
3914         case RESPONSE_ACCEPT:
3915                 /* delete the playlist */
3916                 return 0;
3917                 break;
3918
3919         case RESPONSE_REJECT:
3920                 /* keep the playlist */
3921                 return 1;
3922                 break;
3923
3924         default:
3925                 break;
3926         }
3927
3928         return -1;
3929 }
3930
3931 bool
3932 Editor::audio_region_selection_covers (nframes64_t where)
3933 {
3934         for (RegionSelection::iterator a = selection->regions.begin(); a != selection->regions.end(); ++a) {
3935                 if ((*a)->region()->covers (where)) {
3936                         return true;
3937                 }
3938         }
3939
3940         return false;
3941 }
3942
3943 void
3944 Editor::prepare_for_cleanup ()
3945 {
3946         cut_buffer->clear_regions ();
3947         cut_buffer->clear_playlists ();
3948
3949         selection->clear_regions ();
3950         selection->clear_playlists ();
3951
3952         no_region_list_redisplay = true;
3953 }
3954
3955 void
3956 Editor::finish_cleanup ()
3957 {
3958         no_region_list_redisplay = false;
3959         redisplay_regions ();
3960 }
3961
3962 Location*
3963 Editor::transport_loop_location()
3964 {
3965         if (session) {
3966                 return session->locations()->auto_loop_location();
3967         } else {
3968                 return 0;
3969         }
3970 }
3971
3972 Location*
3973 Editor::transport_punch_location()
3974 {
3975         if (session) {
3976                 return session->locations()->auto_punch_location();
3977         } else {
3978                 return 0;
3979         }
3980 }
3981
3982 bool
3983 Editor::control_layout_scroll (GdkEventScroll* ev)
3984 {
3985         switch (ev->direction) {
3986         case GDK_SCROLL_UP:
3987                 scroll_tracks_up_line ();
3988                 return true;
3989                 break;
3990
3991         case GDK_SCROLL_DOWN:
3992                 scroll_tracks_down_line ();
3993                 return true;
3994                 
3995         default:
3996                 /* no left/right handling yet */
3997                 break;
3998         }
3999
4000         return false;
4001 }
4002
4003
4004 /** A new snapshot has been selected.
4005  */
4006 void
4007 Editor::snapshot_display_selection_changed ()
4008 {
4009         if (snapshot_display.get_selection()->count_selected_rows() > 0) {
4010
4011                 TreeModel::iterator i = snapshot_display.get_selection()->get_selected();
4012                 
4013                 Glib::ustring snap_name = (*i)[snapshot_display_columns.real_name];
4014
4015                 if (snap_name.length() == 0) {
4016                         return;
4017                 }
4018                 
4019                 if (session->snap_name() == snap_name) {
4020                         return;
4021                 }
4022                 
4023                 ARDOUR_UI::instance()->load_session(session->path(), string (snap_name));
4024         }
4025 }
4026
4027 bool
4028 Editor::snapshot_display_button_press (GdkEventButton* ev)
4029 {
4030         if (ev->button == 3) {
4031                 /* Right-click on the snapshot list. Work out which snapshot it
4032                    was over. */
4033                 Gtk::TreeModel::Path path;
4034                 Gtk::TreeViewColumn* col;
4035                 int cx;
4036                 int cy;
4037                 snapshot_display.get_path_at_pos ((int) ev->x, (int) ev->y, path, col, cx, cy);
4038                 Gtk::TreeModel::iterator iter = snapshot_display_model->get_iter (path);
4039                 if (iter) {
4040                         Gtk::TreeModel::Row row = *iter;
4041                         popup_snapshot_context_menu (ev->button, ev->time, row[snapshot_display_columns.real_name]);
4042                 }
4043                 return true;
4044         }
4045
4046         return false;
4047 }
4048
4049
4050 /** Pop up the snapshot display context menu.
4051  * @param button Button used to open the menu.
4052  * @param time Menu open time.
4053  * @snapshot_name Name of the snapshot that the menu click was over.
4054  */
4055
4056 void
4057 Editor::popup_snapshot_context_menu (int button, int32_t time, Glib::ustring snapshot_name)
4058 {
4059         using namespace Menu_Helpers;
4060
4061         MenuList& items (snapshot_context_menu.items());
4062         items.clear ();
4063
4064         const bool modification_allowed = (session->snap_name() != snapshot_name && session->name() != snapshot_name);
4065
4066         items.push_back (MenuElem (_("Remove"), bind (mem_fun (*this, &Editor::remove_snapshot), snapshot_name)));
4067         if (!modification_allowed) {
4068                 items.back().set_sensitive (false);
4069         }
4070
4071         items.push_back (MenuElem (_("Rename"), bind (mem_fun (*this, &Editor::rename_snapshot), snapshot_name)));
4072         if (!modification_allowed) {
4073                 items.back().set_sensitive (false);
4074         }
4075
4076         snapshot_context_menu.popup (button, time);
4077 }
4078
4079 void
4080 Editor::rename_snapshot (Glib::ustring old_name)
4081 {
4082         ArdourPrompter prompter(true);
4083
4084         string new_name;
4085
4086         prompter.set_name ("Prompter");
4087         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
4088         prompter.set_prompt (_("New name of snapshot"));
4089         prompter.set_initial_text (old_name);
4090         
4091         if (prompter.run() == RESPONSE_ACCEPT) {
4092                 prompter.get_result (new_name);
4093                 if (new_name.length()) {
4094                         session->rename_state (old_name, new_name);
4095                         redisplay_snapshots ();
4096                 }
4097         }
4098 }
4099
4100
4101 void
4102 Editor::remove_snapshot (Glib::ustring name)
4103 {
4104         vector<string> choices;
4105
4106         std::string prompt  = string_compose (_("Do you really want to remove snapshot \"%1\" ?\n(cannot be undone)"), name);
4107
4108         choices.push_back (_("No, do nothing."));
4109         choices.push_back (_("Yes, remove it."));
4110
4111         Gtkmm2ext::Choice prompter (prompt, choices);
4112
4113         if (prompter.run () == 1) {
4114                 session->remove_state (name);
4115                 redisplay_snapshots ();
4116         }
4117 }
4118
4119 void
4120 Editor::redisplay_snapshots ()
4121 {
4122         if (session == 0) {
4123                 return;
4124         }
4125
4126         vector<string*>* states;
4127
4128         if ((states = session->possible_states()) == 0) {
4129                 return;
4130         }
4131
4132         snapshot_display_model->clear ();
4133
4134         for (vector<string*>::iterator i = states->begin(); i != states->end(); ++i) {
4135                 string statename = *(*i);
4136                 TreeModel::Row row = *(snapshot_display_model->append());
4137                 
4138                 /* this lingers on in case we ever want to change the visible
4139                    name of the snapshot.
4140                 */
4141                 
4142                 string display_name;
4143                 display_name = statename;
4144
4145                 if (statename == session->snap_name()) {
4146                         snapshot_display.get_selection()->select(row);
4147                 } 
4148                 
4149                 row[snapshot_display_columns.visible_name] = display_name;
4150                 row[snapshot_display_columns.real_name] = statename;
4151         }
4152
4153         delete states;
4154 }
4155
4156 void
4157 Editor::session_state_saved (string snap_name)
4158 {
4159         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::session_state_saved), snap_name));
4160         redisplay_snapshots ();
4161 }
4162
4163 void
4164 Editor::maximise_editing_space ()
4165 {
4166         mouse_mode_tearoff->set_visible (false);
4167         tools_tearoff->set_visible (false);
4168
4169         pre_maximal_pane_position = edit_pane.get_position();
4170         pre_maximal_editor_width = this->get_width();
4171
4172         if(post_maximal_pane_position == 0) {
4173                 post_maximal_pane_position = edit_pane.get_width();
4174         }
4175
4176         fullscreen();
4177
4178         if(post_maximal_editor_width) {
4179                 edit_pane.set_position (post_maximal_pane_position - 
4180                         abs(post_maximal_editor_width - pre_maximal_editor_width));
4181         } else {
4182                 edit_pane.set_position (post_maximal_pane_position);
4183         }
4184 }
4185
4186 void
4187 Editor::restore_editing_space ()
4188 {
4189         // user changed width of pane during fullscreen
4190         if(post_maximal_pane_position != edit_pane.get_position()) {
4191                 post_maximal_pane_position = edit_pane.get_position();
4192         }
4193
4194         unfullscreen();
4195
4196         mouse_mode_tearoff->set_visible (true);
4197         tools_tearoff->set_visible (true);
4198         post_maximal_editor_width = this->get_width();
4199
4200
4201         edit_pane.set_position (
4202                 pre_maximal_pane_position + abs(this->get_width() - pre_maximal_editor_width)
4203         );
4204 }
4205
4206 /**
4207  *  Make new playlists for a given track and also any others that belong
4208  *  to the same active edit group.
4209  *  @param v Track.
4210  */
4211
4212 void 
4213 Editor::new_playlists (TimeAxisView* v)
4214 {
4215         begin_reversible_command (_("new playlists"));
4216         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4217         session->get_playlists(playlists);
4218         mapover_audio_tracks ( bind(mem_fun (*this, &Editor::mapped_use_new_playlist), playlists), v );
4219         commit_reversible_command ();
4220 }
4221
4222
4223 /**
4224  *  Use a copy of the current playlist for a given track and also any others that belong
4225  *  to the same active edit group.
4226  *  @param v Track.
4227  */
4228
4229 void
4230 Editor::copy_playlists (TimeAxisView* v)
4231 {
4232         begin_reversible_command (_("copy playlists"));
4233         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4234         session->get_playlists(playlists);
4235         mapover_audio_tracks ( bind(mem_fun (*this, &Editor::mapped_use_copy_playlist), playlists), v );
4236         commit_reversible_command ();
4237 }
4238
4239
4240 /**
4241  *  Clear the current playlist for a given track and also any others that belong
4242  *  to the same active edit group.
4243  *  @param v Track.
4244  */
4245
4246 void 
4247 Editor::clear_playlists (TimeAxisView* v)
4248 {
4249         begin_reversible_command (_("clear playlists"));
4250         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4251         session->get_playlists(playlists);
4252         mapover_audio_tracks ( mem_fun (*this, &Editor::mapped_clear_playlist), v );
4253         commit_reversible_command ();
4254 }
4255
4256 void 
4257 Editor::mapped_use_new_playlist (AudioTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4258 {
4259         atv.use_new_playlist (sz > 1 ? false : true, playlists);
4260 }
4261
4262 void
4263 Editor::mapped_use_copy_playlist (AudioTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4264 {
4265         atv.use_copy_playlist (sz > 1 ? false : true, playlists);
4266 }
4267
4268 void 
4269 Editor::mapped_clear_playlist (AudioTimeAxisView& atv, uint32_t sz)
4270 {
4271         atv.clear_playlist ();
4272 }
4273
4274 bool
4275 Editor::on_key_press_event (GdkEventKey* ev)
4276 {
4277         return key_press_focus_accelerator_handler (*this, ev);
4278 }
4279
4280 bool
4281 Editor::on_key_release_event (GdkEventKey* ev)
4282 {
4283         return Gtk::Window::on_key_release_event (ev);
4284         // return key_press_focus_accelerator_handler (*this, ev);
4285 }
4286
4287 void
4288 Editor::reset_x_origin (nframes64_t frame)
4289 {
4290         //cerr << "resetting x origin" << endl;
4291         queue_visual_change (frame);
4292 }
4293
4294 void
4295 Editor::reset_zoom (double fpu)
4296 {
4297         queue_visual_change (fpu);
4298 }
4299
4300 void
4301 Editor::reposition_and_zoom (nframes64_t frame, double fpu)
4302 {
4303         //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
4304         reset_x_origin (frame);
4305         reset_zoom (fpu);
4306
4307         if (!no_save_visual) {
4308                 undo_visual_stack.push_back (current_visual_state(false));
4309         }
4310 }
4311
4312 Editor::VisualState*
4313 Editor::current_visual_state (bool with_tracks)
4314 {
4315         VisualState* vs = new VisualState;
4316         vs->y_position = vertical_adjustment.get_value();
4317         vs->frames_per_unit = frames_per_unit;
4318         vs->leftmost_frame = leftmost_frame;
4319         vs->zoom_focus = zoom_focus;
4320         vs->zoomed_to_region = zoomed_to_region;
4321
4322         if (with_tracks) {
4323                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4324                         vs->track_states.push_back (TAVState ((*i), &(*i)->get_state()));
4325                 }
4326         }
4327         
4328         return vs;
4329 }
4330
4331 void
4332 Editor::undo_visual_state ()
4333 {
4334         if (undo_visual_stack.empty()) {
4335                 return;
4336         }
4337
4338         VisualState* vs = undo_visual_stack.back();
4339         undo_visual_stack.pop_back();
4340         use_visual_state (*vs);
4341         redo_visual_stack.push_back (vs);
4342 }
4343
4344 void
4345 Editor::redo_visual_state ()
4346 {
4347         if (redo_visual_stack.empty()) {
4348                 return;
4349         }
4350
4351         VisualState* vs = redo_visual_stack.back();
4352         redo_visual_stack.pop_back();
4353         use_visual_state (*vs);
4354         undo_visual_stack.push_back (vs);
4355 }
4356
4357 void
4358 Editor::swap_visual_state ()
4359 {
4360         if (undo_visual_stack.empty()) {
4361                 redo_visual_state ();
4362         } else {
4363                 undo_visual_state ();
4364         }
4365 }
4366
4367 void
4368 Editor::use_visual_state (VisualState& vs)
4369 {
4370         no_save_visual = true;
4371         no_route_list_redisplay = true;
4372
4373         vertical_adjustment.set_value (vs.y_position);
4374
4375         set_zoom_focus (vs.zoom_focus);
4376         reposition_and_zoom (vs.leftmost_frame, vs.frames_per_unit);
4377         zoomed_to_region = vs.zoomed_to_region;
4378         
4379         for (list<TAVState>::iterator i = vs.track_states.begin(); i != vs.track_states.end(); ++i) {
4380                 TrackViewList::iterator t;
4381
4382                 /* check if the track still exists - it could have been deleted */
4383
4384                 if ((t = find (track_views.begin(), track_views.end(), i->first)) != track_views.end()) {
4385                         (*t)->set_state (*(i->second));
4386                 }
4387         }
4388
4389         if (!vs.track_states.empty()) {
4390                 update_route_visibility ();
4391         } 
4392
4393         no_route_list_redisplay = false;
4394         redisplay_route_list ();
4395
4396         no_save_visual = false;
4397 }
4398
4399 void
4400 Editor::set_frames_per_unit (double fpu)
4401 {
4402         /* this is the core function that controls the zoom level of the canvas. it is called
4403            whenever one or more calls are made to reset_zoom(). it executes in an idle handler.
4404         */
4405
4406         if (fpu == frames_per_unit) {
4407                 return;
4408         }
4409
4410         if (fpu < 2.0) {
4411                 fpu = 2.0;
4412         }
4413
4414         
4415         /* don't allow zooms that fit more than the maximum number
4416            of frames into an 800 pixel wide space.
4417         */
4418
4419         if (max_frames / fpu < 800.0) {
4420                 return;
4421         }
4422
4423         if (tempo_lines) {
4424                 tempo_lines->tempo_map_changed();
4425         }
4426
4427         frames_per_unit = fpu;
4428         post_zoom ();
4429 }
4430
4431 void
4432 Editor::post_zoom ()
4433 {
4434         nframes64_t cef = 0;
4435 /*
4436         // convert fpu to frame count
4437
4438         nframes64_t frames = (nframes64_t) floor (frames_per_unit * canvas_width);
4439         
4440         if (frames_per_unit != zoom_range_clock.current_duration()) {
4441                 zoom_range_clock.set (frames);
4442         }
4443 */
4444         if (mouse_mode == MouseRange && selection->time.start () != selection->time.end_frame ()) {
4445                 if (!selection->tracks.empty()) {
4446                         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4447                                 (*i)->reshow_selection (selection->time);
4448                         }
4449                 } else {
4450                         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4451                                 (*i)->reshow_selection (selection->time);
4452                         }
4453                 }
4454         }
4455         update_loop_range_view (false);
4456         update_punch_range_view (false);
4457
4458         if (playhead_cursor) {
4459                 playhead_cursor->set_position (playhead_cursor->current_frame);
4460         }
4461
4462         ZoomChanged (); /* EMIT_SIGNAL */
4463
4464         reset_hscrollbar_stepping ();
4465
4466         if (session) {
4467                 cef = session->current_end_frame() + (current_page_frames() / 10);// Add a little extra so we can see the end marker
4468         }
4469         horizontal_adjustment.set_upper (cef / frames_per_unit);
4470
4471         //reset_scrolling_region ();
4472
4473         instant_save ();
4474 }
4475
4476 void
4477 Editor::queue_visual_change (nframes64_t where)
4478 {
4479 //      pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::TimeOrigin);
4480 //      pending_visual_change.time_origin = where;
4481
4482         if (pending_visual_change.idle_handler_id < 0) {
4483                 pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::TimeOrigin);
4484                 pending_visual_change.time_origin = where;
4485                 pending_visual_change.idle_handler_id = g_idle_add (_idle_visual_changer, this);
4486         }
4487 }
4488
4489 void
4490 Editor::queue_visual_change (double fpu)
4491 {
4492         pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::ZoomLevel);
4493         pending_visual_change.frames_per_unit = fpu;
4494
4495         if (pending_visual_change.idle_handler_id < 0) {
4496                 pending_visual_change.idle_handler_id = g_idle_add_full (G_PRIORITY_HIGH_IDLE, _idle_visual_changer, this, 0);
4497         }
4498 }
4499
4500 int
4501 Editor::_idle_visual_changer (void* arg)
4502 {
4503         return static_cast<Editor*>(arg)->idle_visual_changer ();
4504 }
4505
4506 int
4507 Editor::idle_visual_changer ()
4508 {
4509         VisualChange::Type p = pending_visual_change.pending;
4510         pending_visual_change.pending = (VisualChange::Type) 0;
4511
4512         double last_time_origin = horizontal_adjustment.get_value();
4513         if (p & VisualChange::ZoomLevel) {
4514                 set_frames_per_unit (pending_visual_change.frames_per_unit);
4515         }
4516
4517         if (p & VisualChange::TimeOrigin) {
4518                 horizontal_adjustment.set_value (pending_visual_change.time_origin / frames_per_unit);
4519         }
4520
4521         if (last_time_origin == horizontal_adjustment.get_value() ) {
4522                 /* changed signal not emitted */
4523                 update_fixed_rulers ();
4524                 redisplay_tempo (true);
4525         }
4526         //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
4527         pending_visual_change.idle_handler_id = -1;
4528         return 0; /* this is always a one-shot call */
4529 }
4530
4531 struct EditorOrderTimeAxisSorter {
4532     bool operator() (const TimeAxisView* a, const TimeAxisView* b) const {
4533             return a->order < b->order;
4534     }
4535 };
4536         
4537 void
4538 Editor::sort_track_selection (TrackSelection* sel)
4539 {
4540         EditorOrderTimeAxisSorter cmp;
4541
4542         if (sel) {
4543                 sel->sort (cmp);
4544         } else {
4545                 selection->tracks.sort (cmp);
4546         }
4547 }
4548
4549 nframes64_t
4550 Editor::get_preferred_edit_position (bool ignore_playhead)
4551 {
4552         bool ignored;
4553         nframes64_t where = 0;
4554         EditPoint ep = _edit_point;
4555
4556         if (entered_marker) {
4557                 return entered_marker->position();
4558         }
4559
4560         if (ignore_playhead && ep == EditAtPlayhead) {
4561                 ep = EditAtSelectedMarker;
4562         }
4563
4564         switch (ep) {
4565         case EditAtPlayhead:
4566                 where = session->audible_frame();
4567                 break;
4568                 
4569         case EditAtSelectedMarker:
4570                 if (!selection->markers.empty()) {
4571                         bool is_start;
4572                         Location* loc = find_location_from_marker (selection->markers.front(), is_start);
4573                         if (loc) {
4574                                 if (is_start) {
4575                                         where =  loc->start();
4576                                 } else {
4577                                         where = loc->end();
4578                                 }
4579                                 break;
4580                         }
4581                 } 
4582                 /* fallthru */
4583                 
4584         default:
4585         case EditAtMouse:
4586                 if (!mouse_frame (where, ignored)) {
4587                         /* XXX not right but what can we do ? */
4588                         return 0;
4589                 }
4590                 snap_to (where);
4591                 break;
4592         }
4593
4594         return where;
4595 }
4596
4597 void
4598 Editor::set_loop_range (nframes64_t start, nframes64_t end, string cmd)
4599 {
4600         if (!session) return;
4601
4602         begin_reversible_command (cmd);
4603         
4604         Location* tll;
4605
4606         if ((tll = transport_loop_location()) == 0) {
4607                 Location* loc = new Location (start, end, _("Loop"),  Location::IsAutoLoop);
4608                 XMLNode &before = session->locations()->get_state();
4609                 session->locations()->add (loc, true);
4610                 session->set_auto_loop_location (loc);
4611                 XMLNode &after = session->locations()->get_state();
4612                 session->add_command (new MementoCommand<Locations>(*(session->locations()), &before, &after));
4613         } else {
4614                 XMLNode &before = tll->get_state();
4615                 tll->set_hidden (false, this);
4616                 tll->set (start, end);
4617                 XMLNode &after = tll->get_state();
4618                 session->add_command (new MementoCommand<Location>(*tll, &before, &after));
4619         }
4620         
4621         commit_reversible_command ();
4622 }
4623
4624 void
4625 Editor::set_punch_range (nframes64_t start, nframes64_t end, string cmd)
4626 {
4627         if (!session) return;
4628
4629         begin_reversible_command (cmd);
4630         
4631         Location* tpl;
4632
4633         if ((tpl = transport_punch_location()) == 0) {
4634                 Location* loc = new Location (start, end, _("Loop"),  Location::IsAutoPunch);
4635                 XMLNode &before = session->locations()->get_state();
4636                 session->locations()->add (loc, true);
4637                 session->set_auto_loop_location (loc);
4638                 XMLNode &after = session->locations()->get_state();
4639                 session->add_command (new MementoCommand<Locations>(*(session->locations()), &before, &after));
4640         }
4641         else {
4642                 XMLNode &before = tpl->get_state();
4643                 tpl->set_hidden (false, this);
4644                 tpl->set (start, end);
4645                 XMLNode &after = tpl->get_state();
4646                 session->add_command (new MementoCommand<Location>(*tpl, &before, &after));
4647         }
4648         
4649         commit_reversible_command ();
4650 }
4651
4652 void
4653 Editor::get_regions_at (RegionSelection& rs, nframes64_t where, const TrackSelection& ts) const
4654 {
4655         const TrackSelection* tracks;
4656
4657         if (ts.empty()) {
4658                 tracks = &track_views;
4659         } else {
4660                 tracks = &ts;
4661         }
4662
4663         for (TrackSelection::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
4664         
4665                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(*t);
4666
4667                 if (atv) {
4668                         boost::shared_ptr<Diskstream> ds;
4669                         boost::shared_ptr<Playlist> pl;
4670                         
4671                         if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()))) {
4672
4673                                 Playlist::RegionList* regions = pl->regions_at ((nframes64_t) floor ( (double)where * ds->speed()));
4674
4675                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
4676
4677                                         RegionView* rv = atv->audio_view()->find_view (*i);
4678
4679                                         if (rv) {
4680                                                 rs.add (rv);
4681                                         }
4682                                 }
4683
4684                                 delete regions;
4685                         }
4686                 }
4687         }
4688 }
4689
4690 void
4691 Editor::get_regions_after (RegionSelection& rs, nframes64_t where, const TrackSelection& ts) const
4692 {
4693         const TrackSelection* tracks;
4694
4695         if (ts.empty()) {
4696                 tracks = &track_views;
4697         } else {
4698                 tracks = &ts;
4699         }
4700
4701         for (TrackSelection::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
4702         
4703                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(*t);
4704
4705                 if (atv) {
4706                         boost::shared_ptr<Diskstream> ds;
4707                         boost::shared_ptr<Playlist> pl;
4708                         
4709                         if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()))) {
4710
4711                                 Playlist::RegionList* regions = pl->regions_touched ((nframes64_t) floor ( (double)where * ds->speed()), max_frames);
4712
4713                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
4714
4715                                         RegionView* rv = atv->audio_view()->find_view (*i);
4716
4717                                         if (rv) {
4718                                                 rs.push_back (rv);
4719                                         }
4720                                 }
4721
4722                                 delete regions;
4723                         }
4724                 }
4725         }
4726 }
4727
4728 void
4729 Editor::get_regions_for_action (RegionSelection& rs, bool allow_entered)
4730 {
4731         if (selection->regions.empty()) {
4732
4733                 if (selection->tracks.empty()) {
4734
4735                         /* no regions or tracks selected
4736                         */
4737                         
4738                         if (entered_regionview && mouse_mode == Editing::MouseObject) {
4739
4740                                 /*  entered regionview is valid and we're in object mode - 
4741                                     just use entered regionview
4742                                 */
4743
4744                                 rs.add (entered_regionview);
4745                         }
4746
4747                         return;
4748
4749                 } else {
4750
4751                         /* no regions selected, so get all regions at the edit point across
4752                            all selected tracks. 
4753                         */
4754
4755                         nframes64_t where = get_preferred_edit_position();
4756                         get_regions_at (rs, where, selection->tracks);
4757
4758                         /* if the entered regionview wasn't selected and neither was its track
4759                            then add it.
4760                         */
4761
4762                         if (entered_regionview != 0 &&
4763                             !selection->selected (entered_regionview) && 
4764                             !selection->selected (&entered_regionview->get_time_axis_view())) {
4765                                 rs.add (entered_regionview);
4766                         }
4767                 }
4768
4769         } else {
4770                 
4771                 /* just use the selected regions */
4772
4773                 rs = selection->regions;
4774
4775                 /* if the entered regionview wasn't selected and we allow this sort of thing,
4776                    then add it.
4777                 */
4778
4779                 if (allow_entered && entered_regionview && !selection->selected (entered_regionview)) {
4780                         rs.add (entered_regionview);
4781                 }
4782
4783         }
4784 }
4785
4786 void
4787 Editor::get_regions_corresponding_to (boost::shared_ptr<Region> region, vector<RegionView*>& regions)
4788 {
4789
4790         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4791                 
4792                 RouteTimeAxisView* tatv;
4793                 
4794                 if ((tatv = dynamic_cast<RouteTimeAxisView*> (*i)) != 0) {
4795                         
4796                         boost::shared_ptr<Playlist> pl;
4797                         vector<boost::shared_ptr<Region> > results;
4798                         RegionView* marv;
4799                         boost::shared_ptr<Diskstream> ds;
4800                         
4801                         if ((ds = tatv->get_diskstream()) == 0) {
4802                                 /* bus */
4803                                 continue;
4804                         }
4805                         
4806                         if ((pl = (ds->playlist())) != 0) {
4807                                 pl->get_region_list_equivalent_regions (region, results);
4808                         }
4809                         
4810                         for (vector<boost::shared_ptr<Region> >::iterator ir = results.begin(); ir != results.end(); ++ir) {
4811                                 if ((marv = tatv->view()->find_view (*ir)) != 0) {
4812                                         regions.push_back (marv);
4813                                 }
4814                         }
4815                         
4816                 }
4817         }
4818 }       
4819
4820 void
4821 Editor::show_rhythm_ferret ()
4822 {
4823         if (rhythm_ferret == 0) {
4824                 rhythm_ferret = new RhythmFerret(*this);
4825         }
4826
4827         rhythm_ferret->set_session (session);
4828         rhythm_ferret->show ();
4829         rhythm_ferret->present ();
4830 }
4831
4832 void
4833 Editor::first_idle ()
4834 {
4835         MessageDialog* dialog = 0;
4836
4837         if (track_views.size() > 1) { 
4838                 dialog = new MessageDialog (*this, 
4839                                             _("Please wait while Ardour loads visual data"),
4840                                             true,
4841                                             Gtk::MESSAGE_INFO,
4842                                             Gtk::BUTTONS_NONE);
4843                 dialog->present ();
4844                 ARDOUR_UI::instance()->flush_pending ();
4845         }
4846
4847         for (TrackViewList::iterator t = track_views.begin(); t != track_views.end(); ++t) {
4848                 (*t)->first_idle();
4849         }
4850
4851         // first idle adds route children (automation tracks), so we need to redisplay here
4852         redisplay_route_list();
4853         
4854         if (dialog) {
4855                 delete dialog;
4856         }
4857
4858         _have_idled = true;
4859 }
4860
4861 void
4862 Editor::start_resize_line_ops ()
4863 {
4864 #if 0
4865         old_resize_line_y = -1;
4866         resize_line_y = -1;
4867         need_resize_line = true;
4868 #endif  
4869 }
4870
4871 void
4872 Editor::end_resize_line_ops ()
4873 {
4874 #if 0
4875         need_resize_line = false;
4876
4877         if (old_resize_line_y >= 0) {
4878                 Gdk::Rectangle r (0, old_resize_line_y, (int) canvas_width, 3);
4879                 Glib::RefPtr<Gdk::Window> win = get_window();
4880                 cerr << "Final invalidation at " << old_resize_line_y << endl;
4881                 win->invalidate_rect (r, false);
4882         }
4883 #endif
4884 }
4885
4886 void
4887 Editor::queue_draw_resize_line (int at)
4888 {
4889 #if 0   
4890         Glib::RefPtr<Gdk::Window> win = get_window();
4891
4892         resize_line_y = at;
4893
4894         if (win && canvas_width) {
4895
4896                 int controls_width = controls_layout.get_width();
4897                 int xroot, discard;
4898                 
4899                 controls_layout.get_window()->get_origin (xroot, discard);
4900
4901                 if (old_resize_line_y >= 0) {
4902                         
4903                         /* redraw where it used to be */
4904                         
4905                         
4906                         Gdk::Rectangle r (0, old_resize_line_y - 1, controls_width + (int) canvas_width, 3);
4907                         win->invalidate_rect (r, true);
4908                         cerr << "invalidate " << xroot << "," << old_resize_line_y - 1 << ' ' 
4909                              << controls_width + canvas_width << " x 3\n";
4910                 }
4911
4912                 /* draw where it is */
4913
4914                 Gdk::Rectangle r (0, at - 1, controls_width + (int) canvas_width, 3);
4915                 win->invalidate_rect (r, true);
4916         }
4917 #endif
4918 }
4919
4920 bool
4921 Editor::on_expose_event (GdkEventExpose* ev)
4922 {
4923         /* cerr << "+++ editor expose "
4924              << ev->area.x << ',' << ev->area.y
4925              << ' '
4926              << ev->area.width << " x " << ev->area.height
4927              << " need reize ? " << need_resize_line
4928              << endl;
4929         */
4930         bool ret = Window::on_expose_event (ev);
4931
4932 #if 0
4933         if (need_resize_line) {
4934                 
4935                 int xroot, yroot, discard;
4936                 int controls_width;
4937
4938                 /* Our root coordinates for drawing the line will be the left edge 
4939                    of the track controls, and the upper left edge of our own window.
4940                 */
4941
4942                 get_window()->get_origin (discard, yroot);
4943                 controls_layout.get_window()->get_origin (xroot, discard);
4944                 controls_width = controls_layout.get_width();
4945                 
4946                 GdkRectangle lr;
4947                 GdkRectangle intersection;
4948
4949                 lr.x = 0;
4950                 lr.y = resize_line_y;
4951                 lr.width = controls_width + (int) canvas_width;
4952                 lr.height = 3;
4953
4954                 if (gdk_rectangle_intersect (&lr, &ev->area, &intersection)) {
4955                         
4956                         Glib::RefPtr<Gtk::Style> style (get_style());
4957                         Glib::RefPtr<Gdk::GC> black_gc (style->get_black_gc ());
4958                         Glib::RefPtr<Gdk::GC> gc = wrap (black_gc->gobj_copy(), false);
4959
4960                         /* draw on root window */
4961
4962                         GdkWindow* win = gdk_get_default_root_window();
4963                         
4964                         gc->set_subwindow (Gdk::INCLUDE_INFERIORS);
4965                         gc->set_line_attributes (3, Gdk::LINE_SOLID, 
4966                                                  Gdk::CAP_NOT_LAST,
4967                                                  Gdk::JOIN_MITER);
4968                         
4969                         gdk_draw_line (win, gc->gobj(), 
4970                                        0,
4971                                        resize_line_y, 
4972                                        (int) canvas_width + controls_width,
4973                                        resize_line_y);
4974 #if 0
4975                         cerr << "drew line @ " << xroot << ", " << yroot + resize_line_y 
4976                              << " to " << xroot + (int) canvas_width + controls_width
4977                              << ", " << yroot + resize_line_y
4978                              << endl;
4979 #endif
4980                         old_resize_line_y = resize_line_y;
4981                         cerr << "NEXT EXPOSE SHOULD BE AT " << old_resize_line_y << endl;
4982                 } else {
4983                         cerr << "no intersect with "
4984                              << lr.x << ',' << lr.y
4985                              << ' '
4986                              << lr.width << " x " << lr.height
4987                              << endl;
4988                 }
4989         }
4990
4991         //cerr << "--- editor expose\n";
4992 #endif
4993
4994         return ret;
4995 }
4996
4997 static gboolean
4998 _idle_resizer (gpointer arg)
4999 {
5000         return ((Editor*)arg)->idle_resize ();
5001 }
5002
5003 void
5004 Editor::add_to_idle_resize (TimeAxisView* view, uint32_t h)
5005 {
5006         if (resize_idle_id < 0) {
5007                 resize_idle_id = g_idle_add (_idle_resizer, this);
5008         } 
5009
5010         resize_idle_target = h;
5011
5012         pending_resizes.push_back (view);
5013
5014         if (selection->selected (view) && !selection->tracks.empty()) {
5015                 pending_resizes.insert (pending_resizes.end(), selection->tracks.begin(), selection->tracks.end());
5016         }
5017 }
5018
5019 bool
5020 Editor::idle_resize ()
5021 {
5022         for (vector<TimeAxisView*>::iterator i = pending_resizes.begin(); i != pending_resizes.end(); ++i) {
5023                 (*i)->idle_resize (resize_idle_target);
5024         }
5025         pending_resizes.clear();
5026         flush_canvas ();
5027         resize_idle_id = -1;
5028         return false;
5029 }