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