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