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