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