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