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