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