Compiles, but doesn't link. The link errors are mostly expected and are
[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 #include <pbd/memento_command.h>
32
33 #include <gtkmm/image.h>
34 #include <gdkmm/color.h>
35 #include <gdkmm/bitmap.h>
36
37 #include <gtkmm2ext/gtk_ui.h>
38 #include <gtkmm2ext/tearoff.h>
39 #include <gtkmm2ext/utils.h>
40
41 #include <ardour/audio_track.h>
42 #include <ardour/audio_diskstream.h>
43 #include <ardour/plugin_manager.h>
44 #include <ardour/location.h>
45 #include <ardour/audioplaylist.h>
46 #include <ardour/audioregion.h>
47 #include <ardour/region.h>
48 #include <ardour/session_route.h>
49 #include <ardour/tempo.h>
50 #include <ardour/utils.h>
51
52 #include <control_protocol/control_protocol.h>
53
54 #include "ardour_ui.h"
55 #include "editor.h"
56 #include "grouped_buttons.h"
57 #include "keyboard.h"
58 #include "marker.h"
59 #include "playlist_selector.h"
60 #include "regionview.h"
61 #include "rgb_macros.h"
62 #include "selection.h"
63 #include "streamview.h"
64 #include "time_axis_view.h"
65 #include "utils.h"
66 #include "crossfade_view.h"
67 #include "editing.h"
68 #include "public_editor.h"
69 #include "crossfade_edit.h"
70 #include "audio_time_axis.h"
71 #include "canvas_impl.h"
72 #include "actions.h"
73 #include "gui_thread.h"
74
75 #ifdef FFT_ANALYSIS
76 #include "analysis_window.h"
77 #endif
78
79 #include "i18n.h"
80
81 /* <CMT Additions> */
82 #include "imageframe_socket_handler.h"
83 /* </CMT Additions> */
84
85 using namespace std;
86 using namespace sigc;
87 using namespace ARDOUR;
88 using namespace PBD;
89 using namespace Gtk;
90 using namespace Glib;
91 using namespace Gtkmm2ext;
92 using namespace Editing;
93
94 using PBD::internationalize;
95 using PBD::atoi;
96
97 const double Editor::timebar_height = 15.0;
98
99 #include "editor_xpms"
100
101 static const int32_t slide_index = 0;
102 static const int32_t splice_index = 1;
103
104 static const gchar *edit_mode_strings[] = {
105         N_("Slide"),
106         N_("Splice"),
107         0
108 };
109
110 static const gchar *snap_type_strings[] = {
111         N_("None"),
112         N_("CD Frames"),
113         N_("SMPTE Frames"),
114         N_("SMPTE Seconds"),
115         N_("SMPTE Minutes"),
116         N_("Seconds"),
117         N_("Minutes"),
118         N_("Beats/32"),
119         N_("Beats/16"),
120         N_("Beats/8"),
121         N_("Beats/4"),
122         N_("Beats/3"),
123         N_("Beats"),
124         N_("Bars"),
125         N_("Marks"),
126         N_("Edit Cursor"),
127         N_("Region starts"),
128         N_("Region ends"),
129         N_("Region syncs"),
130         N_("Region bounds"),
131         0
132 };
133
134 static const gchar *snap_mode_strings[] = {
135         N_("Normal"),
136         N_("Magnetic"),
137         0
138 };
139
140 static const gchar *zoom_focus_strings[] = {
141         N_("Left"),
142         N_("Right"),
143         N_("Center"),
144         N_("Playhead"),
145         N_("Edit Cursor"),
146         0
147 };
148
149 /* Soundfile  drag-n-drop */
150
151 Gdk::Cursor* Editor::cross_hair_cursor = 0;
152 Gdk::Cursor* Editor::selector_cursor = 0;
153 Gdk::Cursor* Editor::trimmer_cursor = 0;
154 Gdk::Cursor* Editor::grabber_cursor = 0;
155 Gdk::Cursor* Editor::zoom_cursor = 0;
156 Gdk::Cursor* Editor::time_fx_cursor = 0;
157 Gdk::Cursor* Editor::fader_cursor = 0;
158 Gdk::Cursor* Editor::speaker_cursor = 0;
159 Gdk::Cursor* Editor::wait_cursor = 0;
160 Gdk::Cursor* Editor::timebar_cursor = 0;
161
162 void
163 show_me_the_size (Requisition* r, const char* what)
164 {
165         cerr << "size of " << what << " = " << r->width << " x " << r->height << endl;
166 }
167
168 void 
169 check_adjustment (Gtk::Adjustment* adj)
170 {
171         cerr << "CHANGE adj  = " 
172              << adj->get_lower () <<  ' '
173              << adj->get_upper () <<  ' '
174              << adj->get_value () <<  ' '
175              << adj->get_step_increment () <<  ' '
176              << adj->get_page_increment () <<  ' '
177              << adj->get_page_size () <<  ' '
178              << endl;
179
180 }
181
182 Editor::Editor (AudioEngine& eng) 
183         : engine (eng),
184
185           /* time display buttons */
186
187           minsec_label (_("Mins:Secs")),
188           bbt_label (_("Bars:Beats")),
189           smpte_label (_("SMPTE")),
190           frame_label (_("Frames")),
191           tempo_label (_("Tempo")),
192           meter_label (_("Meter")),
193           mark_label (_("Location Markers")),
194           range_mark_label (_("Range Markers")),
195           transport_mark_label (_("Loop/Punch Ranges")),
196
197           edit_packer (3, 3, false),
198
199           /* the values here don't matter: layout widgets
200              reset them as needed.
201           */
202
203           vertical_adjustment (0.0, 0.0, 10.0, 400.0),
204           horizontal_adjustment (0.0, 0.0, 20.0, 1200.0),
205
206           /* tool bar related */
207
208           selection_start_clock (X_("SelectionStartClock"), true),
209           selection_end_clock (X_("SelectionEndClock"), true),
210           edit_cursor_clock (X_("EditCursorClock"), true),
211           zoom_range_clock (X_("ZoomRangeClock"), true, true),
212           
213           toolbar_selection_clock_table (2,3),
214           
215           mouse_mode_button_table (2, 3),
216
217           mouse_select_button (_("range")),
218           mouse_move_button (_("object")),
219           mouse_gain_button (_("gain")),
220           mouse_zoom_button (_("zoom")),
221           mouse_timefx_button (_("timefx")),
222           mouse_audition_button (_("listen")),
223
224           automation_mode_button (_("mode")),
225           global_automation_button (_("automation")),
226
227           edit_mode_label (_("Edit Mode")),
228           snap_type_label (_("Snap To")),
229           snap_mode_label(_("Snap Mode")),
230           zoom_focus_label (_("Zoom Focus")),
231
232           /* <CMT Additions> */
233           image_socket_listener(0),
234           /* </CMT Additions> */
235
236           /* nudge */
237
238           nudge_label (_("Nudge")),
239           nudge_clock (X_("NudgeClock"), true, true)
240
241 {
242         constructed = false;
243
244         /* we are a singleton */
245
246         PublicEditor::_instance = this;
247
248         session = 0;
249
250         selection = new Selection;
251         cut_buffer = new Selection;
252
253         selection->TimeChanged.connect (mem_fun(*this, &Editor::time_selection_changed));
254         selection->TracksChanged.connect (mem_fun(*this, &Editor::track_selection_changed));
255         selection->RegionsChanged.connect (mem_fun(*this, &Editor::region_selection_changed));
256         selection->PointsChanged.connect (mem_fun(*this, &Editor::point_selection_changed));
257
258         clicked_regionview = 0;
259         clicked_trackview = 0;
260         clicked_audio_trackview = 0;
261         clicked_crossfadeview = 0;
262         clicked_control_point = 0;
263         latest_regionview = 0;
264         last_update_frame = 0;
265         drag_info.item = 0;
266         last_audition_region = 0;
267         current_mixer_strip = 0;
268         current_bbt_points = 0;
269
270         snap_type = SnapToFrame;
271         set_snap_to (snap_type);
272         snap_mode = SnapNormal;
273         set_snap_mode (snap_mode);
274         snap_threshold = 5.0;
275         bbt_beat_subdivision = 4;
276         canvas_width = 0;
277         canvas_height = 0;
278         autoscroll_timeout_tag = -1;
279         interthread_progress_window = 0;
280
281 #ifdef FFT_ANALYSIS
282         analysis_window = 0;
283 #endif
284
285         current_interthread_info = 0;
286         _show_measures = true;
287         _show_waveforms = true;
288         _show_waveforms_recording = true;
289         first_action_message = 0;
290         export_dialog = 0;
291         show_gain_after_trim = false;
292         no_zoom_repos_update = false;
293         ignore_route_list_reorder = false;
294         no_route_list_redisplay = false;
295         verbose_cursor_on = true;
296         route_removal = false;
297         track_spacing = 0;
298         show_automatic_regions_in_region_list = true;
299         region_list_sort_type = (Editing::RegionListSortType) 0; 
300         have_pending_keyboard_selection = false;
301         _follow_playhead = true;
302         _xfade_visibility = true;
303         editor_ruler_menu = 0;
304         no_ruler_shown_update = false;
305         edit_hscroll_dragging = false;
306         edit_group_list_menu = 0;
307         route_list_menu = 0;
308         region_list_menu = 0;
309         marker_menu = 0;
310         range_marker_menu = 0;
311         marker_menu_item = 0;
312         tm_marker_menu = 0;
313         transport_marker_menu = 0;
314         new_transport_marker_menu = 0;
315         editor_mixer_strip_width = Wide;
316         repos_zoom_queued = false;
317         region_edit_menu_split_item = 0;
318         temp_location = 0;
319         region_edit_menu_split_multichannel_item = 0;
320         leftmost_frame = 0;
321         ignore_mouse_mode_toggle = false;
322         current_stepping_trackview = 0;
323         entered_track = 0;
324         entered_regionview = 0;
325         clear_entered_track = false;
326         _new_regionviews_show_envelope = false;
327         current_timestretch = 0;
328         in_edit_group_row_change = false;
329         last_canvas_frame = 0;
330         edit_cursor = 0;
331         playhead_cursor = 0;
332         button_release_can_deselect = true;
333
334         location_marker_color = color_map[cLocationMarker];
335         location_range_color = color_map[cLocationRange];
336         location_cd_marker_color = color_map[cLocationCDMarker];
337         location_loop_color = color_map[cLocationLoop];
338         location_punch_color = color_map[cLocationPunch];
339
340         range_marker_drag_rect = 0;
341         marker_drag_line = 0;
342         
343         set_mouse_mode (MouseObject, true);
344
345         frames_per_unit = 2048; /* too early to use set_frames_per_unit */
346         reset_hscrollbar_stepping ();
347         
348         zoom_focus = ZoomFocusLeft;
349         zoom_range_clock.ValueChanged.connect (mem_fun(*this, &Editor::zoom_adjustment_changed));
350
351         initialize_rulers ();
352         initialize_canvas ();
353
354         edit_controls_vbox.set_spacing (0);
355         horizontal_adjustment.signal_value_changed().connect (mem_fun(*this, &Editor::canvas_horizontally_scrolled));
356         vertical_adjustment.signal_value_changed().connect (mem_fun(*this, &Editor::tie_vertical_scrolling));
357         
358         track_canvas.set_hadjustment (horizontal_adjustment);
359         track_canvas.set_vadjustment (vertical_adjustment);
360         time_canvas.set_hadjustment (horizontal_adjustment);
361
362         track_canvas.signal_map_event().connect (mem_fun (*this, &Editor::track_canvas_map_handler));
363         time_canvas.signal_map_event().connect (mem_fun (*this, &Editor::time_canvas_map_handler));
364         
365         controls_layout.add (edit_controls_vbox);
366         controls_layout.set_name ("EditControlsBase");
367         controls_layout.add_events (Gdk::SCROLL_MASK);
368         controls_layout.signal_scroll_event().connect (mem_fun(*this, &Editor::control_layout_scroll), false);
369         
370         controls_layout.add_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK|Gdk::ENTER_NOTIFY_MASK|Gdk::LEAVE_NOTIFY_MASK);
371         controls_layout.signal_button_release_event().connect (mem_fun(*this, &Editor::edit_controls_button_release));
372         controls_layout.signal_size_request().connect (mem_fun (*this, &Editor::controls_layout_size_request));
373
374         edit_vscrollbar.set_adjustment (vertical_adjustment);
375         edit_hscrollbar.set_adjustment (horizontal_adjustment);
376
377         edit_hscrollbar.signal_button_press_event().connect (mem_fun(*this, &Editor::hscrollbar_button_press));
378         edit_hscrollbar.signal_button_release_event().connect (mem_fun(*this, &Editor::hscrollbar_button_release));
379         edit_hscrollbar.signal_size_allocate().connect (mem_fun(*this, &Editor::hscrollbar_allocate));
380
381         build_cursors ();
382         setup_toolbar ();
383
384         edit_cursor_clock.ValueChanged.connect (mem_fun(*this, &Editor::edit_cursor_clock_changed));
385         
386         time_canvas_vbox.pack_start (*minsec_ruler, false, false);
387         time_canvas_vbox.pack_start (*smpte_ruler, false, false);
388         time_canvas_vbox.pack_start (*frames_ruler, false, false);
389         time_canvas_vbox.pack_start (*bbt_ruler, false, false);
390         time_canvas_vbox.pack_start (time_canvas, true, true);
391         time_canvas_vbox.set_size_request (-1, (int)(timebar_height * visible_timebars));
392
393         bbt_label.set_name ("EditorTimeButton");
394         bbt_label.set_size_request (-1, (int)timebar_height);
395         bbt_label.set_alignment (1.0, 0.5);
396         bbt_label.set_padding (5,0);
397         minsec_label.set_name ("EditorTimeButton");
398         minsec_label.set_size_request (-1, (int)timebar_height);
399         minsec_label.set_alignment (1.0, 0.5);
400         minsec_label.set_padding (5,0);
401         smpte_label.set_name ("EditorTimeButton");
402         smpte_label.set_size_request (-1, (int)timebar_height);
403         smpte_label.set_alignment (1.0, 0.5);
404         smpte_label.set_padding (5,0);
405         frame_label.set_name ("EditorTimeButton");
406         frame_label.set_size_request (-1, (int)timebar_height);
407         frame_label.set_alignment (1.0, 0.5);
408         frame_label.set_padding (5,0);
409         tempo_label.set_name ("EditorTimeButton");
410         tempo_label.set_size_request (-1, (int)timebar_height);
411         tempo_label.set_alignment (1.0, 0.5);
412         tempo_label.set_padding (5,0);
413         meter_label.set_name ("EditorTimeButton");
414         meter_label.set_size_request (-1, (int)timebar_height);
415         meter_label.set_alignment (1.0, 0.5);
416         meter_label.set_padding (5,0);
417         mark_label.set_name ("EditorTimeButton");
418         mark_label.set_size_request (-1, (int)timebar_height);
419         mark_label.set_alignment (1.0, 0.5);
420         mark_label.set_padding (5,0);
421         range_mark_label.set_name ("EditorTimeButton");
422         range_mark_label.set_size_request (-1, (int)timebar_height);
423         range_mark_label.set_alignment (1.0, 0.5);
424         range_mark_label.set_padding (5,0);
425         transport_mark_label.set_name ("EditorTimeButton");
426         transport_mark_label.set_size_request (-1, (int)timebar_height);
427         transport_mark_label.set_alignment (1.0, 0.5);
428         transport_mark_label.set_padding (5,0);
429         
430         time_button_vbox.pack_start (minsec_label, false, false);
431         time_button_vbox.pack_start (smpte_label, false, false);
432         time_button_vbox.pack_start (frame_label, false, false);
433         time_button_vbox.pack_start (bbt_label, false, false);
434         time_button_vbox.pack_start (meter_label, false, false);
435         time_button_vbox.pack_start (tempo_label, false, false);
436         time_button_vbox.pack_start (mark_label, false, false);
437
438         time_button_event_box.add (time_button_vbox);
439         
440         time_button_event_box.set_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK);
441         time_button_event_box.set_name ("TimebarLabelBase");
442         time_button_event_box.signal_button_release_event().connect (mem_fun(*this, &Editor::ruler_label_button_release));
443
444         /* these enable us to have a dedicated window (for cursor setting, etc.) 
445            for the canvas areas.
446         */
447
448         track_canvas_event_box.add (track_canvas);
449
450         time_canvas_event_box.add (time_canvas_vbox);
451         time_canvas_event_box.set_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK|Gdk::POINTER_MOTION_MASK);
452         
453         edit_packer.set_col_spacings (0);
454         edit_packer.set_row_spacings (0);
455         edit_packer.set_homogeneous (false);
456         edit_packer.set_border_width (0);
457         edit_packer.set_name ("EditorWindow");
458         
459         edit_packer.attach (edit_vscrollbar,         0, 1, 1, 3,    FILL,        FILL|EXPAND, 0, 0);
460
461         edit_packer.attach (time_button_event_box,   1, 2, 0, 1,    FILL,        FILL, 0, 0);
462         edit_packer.attach (time_canvas_event_box,   2, 3, 0, 1,    FILL|EXPAND, FILL, 0, 0);
463
464         edit_packer.attach (controls_layout,         1, 2, 1, 2,    FILL,        FILL|EXPAND, 0, 0);
465         edit_packer.attach (track_canvas_event_box,  2, 3, 1, 2,    FILL|EXPAND, FILL|EXPAND, 0, 0);
466
467         edit_packer.attach (edit_hscrollbar,         2, 3, 2, 3,    FILL|EXPAND,  FILL, 0, 0);
468
469         zoom_in_button.set_name ("EditorTimeButton");
470         zoom_out_button.set_name ("EditorTimeButton");
471         ARDOUR_UI::instance()->tooltips().set_tip (zoom_in_button, _("Zoom in"));
472         ARDOUR_UI::instance()->tooltips().set_tip (zoom_out_button, _("Zoom out"));
473
474         zoom_out_full_button.set_name ("EditorTimeButton");
475         ARDOUR_UI::instance()->tooltips().set_tip (zoom_out_full_button, _("Zoom to session"));
476
477         zoom_in_button.add (*(manage (new Image (Stock::ZOOM_IN, ICON_SIZE_BUTTON))));
478         zoom_out_button.add (*(manage (new Image (Stock::ZOOM_OUT, ICON_SIZE_BUTTON))));
479         zoom_out_full_button.add (*(manage (new Image (Stock::ZOOM_FIT, ICON_SIZE_BUTTON))));
480         
481         zoom_in_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::temporal_zoom_step), false));
482         zoom_out_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::temporal_zoom_step), true));
483         zoom_out_full_button.signal_clicked().connect (mem_fun(*this, &Editor::temporal_zoom_session));
484         
485         zoom_indicator_box.pack_start (zoom_out_button, false, false);
486         zoom_indicator_box.pack_start (zoom_in_button, false, false);
487         zoom_indicator_box.pack_start (zoom_range_clock, false, false); 
488         zoom_indicator_box.pack_start (zoom_out_full_button, false, false);
489         
490         zoom_indicator_label.set_text (_("Zoom Span"));
491         zoom_indicator_label.set_name ("ToolBarLabel");
492
493         zoom_indicator_vbox.set_spacing (3);
494         zoom_indicator_vbox.set_border_width (3);
495         zoom_indicator_vbox.pack_start (zoom_indicator_label, false, false);
496         zoom_indicator_vbox.pack_start (zoom_indicator_box, false, false);
497
498         bottom_hbox.set_border_width (3);
499         bottom_hbox.set_spacing (3);
500
501         route_display_model = ListStore::create(route_display_columns);
502         route_list_display.set_model (route_display_model);
503         route_list_display.append_column (_("Visible"), route_display_columns.visible);
504         route_list_display.append_column (_("Name"), route_display_columns.text);
505         route_list_display.get_column (0)->set_data (X_("colnum"), GUINT_TO_POINTER(0));
506         route_list_display.get_column (1)->set_data (X_("colnum"), GUINT_TO_POINTER(1));
507         route_list_display.set_headers_visible (true);
508         route_list_display.set_name ("TrackListDisplay");
509         route_list_display.get_selection()->set_mode (SELECTION_NONE);
510         route_list_display.set_reorderable (true);
511         route_list_display.set_size_request (100,-1);
512
513         CellRendererToggle* route_list_visible_cell = dynamic_cast<CellRendererToggle*>(route_list_display.get_column_cell_renderer (0));
514         route_list_visible_cell->property_activatable() = true;
515         route_list_visible_cell->property_radio() = false;
516         
517         route_display_model->signal_row_deleted().connect (mem_fun (*this, &Editor::route_list_delete));
518         route_display_model->signal_row_changed().connect (mem_fun (*this, &Editor::route_list_change));
519
520         route_list_display.signal_button_press_event().connect (mem_fun (*this, &Editor::route_list_display_button_press), false);
521
522         route_list_scroller.add (route_list_display);
523         route_list_scroller.set_policy (POLICY_NEVER, POLICY_AUTOMATIC);
524
525         group_model = ListStore::create(group_columns);
526         edit_group_display.set_model (group_model);
527         edit_group_display.append_column (_("Name"), group_columns.text);
528         edit_group_display.append_column (_("Active"), group_columns.is_active);
529         edit_group_display.append_column (_("Visible"), group_columns.is_visible);
530         edit_group_display.get_column (0)->set_data (X_("colnum"), GUINT_TO_POINTER(0));
531         edit_group_display.get_column (1)->set_data (X_("colnum"), GUINT_TO_POINTER(1));
532         edit_group_display.get_column (2)->set_data (X_("colnum"), GUINT_TO_POINTER(2));
533         edit_group_display.get_column (0)->set_expand (true);
534         edit_group_display.get_column (1)->set_expand (false);
535         edit_group_display.get_column (2)->set_expand (false);
536         edit_group_display.set_headers_visible (true);
537
538         /* name is directly editable */
539
540         CellRendererText* name_cell = dynamic_cast<CellRendererText*>(edit_group_display.get_column_cell_renderer (0));
541         name_cell->property_editable() = true;
542         name_cell->signal_edited().connect (mem_fun (*this, &Editor::edit_group_name_edit));
543
544         /* use checkbox for the active + visible columns */
545
546         CellRendererToggle* active_cell = dynamic_cast<CellRendererToggle*>(edit_group_display.get_column_cell_renderer (1));
547         active_cell->property_activatable() = true;
548         active_cell->property_radio() = false;
549
550         active_cell = dynamic_cast<CellRendererToggle*>(edit_group_display.get_column_cell_renderer (1));
551         active_cell->property_activatable() = true;
552         active_cell->property_radio() = false;
553
554         edit_group_display.set_name ("EditGroupList");
555
556         group_model->signal_row_changed().connect (mem_fun (*this, &Editor::edit_group_row_change));
557
558         edit_group_display.set_name ("EditGroupList");
559         edit_group_display.get_selection()->set_mode (SELECTION_SINGLE);
560         edit_group_display.set_reorderable (false);
561         edit_group_display.set_rules_hint (true);
562         edit_group_display.set_size_request (75, -1);
563
564         edit_group_display_scroller.add (edit_group_display);
565         edit_group_display_scroller.set_policy (POLICY_AUTOMATIC, POLICY_AUTOMATIC);
566
567         edit_group_display.signal_button_press_event().connect (mem_fun(*this, &Editor::edit_group_list_button_press_event), false);
568
569         VBox* edit_group_display_packer = manage (new VBox());
570         HButtonBox* edit_group_display_button_box = manage (new HButtonBox());
571         edit_group_display_button_box->set_homogeneous (true);
572
573         Button* edit_group_add_button = manage (new Button ());
574         Button* edit_group_remove_button = manage (new Button ());
575
576         Widget* w;
577
578         w = manage (new Image (Stock::ADD, ICON_SIZE_BUTTON));
579         w->show();
580         edit_group_add_button->add (*w);
581
582         w = manage (new Image (Stock::REMOVE, ICON_SIZE_BUTTON));
583         w->show();
584         edit_group_remove_button->add (*w);
585
586         edit_group_add_button->signal_clicked().connect (mem_fun (*this, &Editor::new_edit_group));
587         edit_group_remove_button->signal_clicked().connect (mem_fun (*this, &Editor::remove_selected_edit_group));
588         
589         edit_group_display_button_box->pack_start (*edit_group_add_button);
590         edit_group_display_button_box->pack_start (*edit_group_remove_button);
591
592         edit_group_display_packer->pack_start (edit_group_display_scroller, true, true);
593         edit_group_display_packer->pack_start (*edit_group_display_button_box, false, false);
594
595         region_list_display.set_size_request (100, -1);
596         region_list_display.set_name ("RegionListDisplay");
597
598         region_list_model = TreeStore::create (region_list_columns);
599         region_list_model->set_sort_func (0, mem_fun (*this, &Editor::region_list_sorter));
600         region_list_model->set_sort_column (0, SORT_ASCENDING);
601
602         region_list_display.set_model (region_list_model);
603         region_list_display.append_column (_("Regions"), region_list_columns.name);
604         region_list_display.set_headers_visible (false);
605         region_list_display.set_hover_expand (true);
606
607         region_list_display.get_selection()->set_select_function (mem_fun (*this, &Editor::region_list_selection_filter));
608         
609         TreeViewColumn* tv_col = region_list_display.get_column(0);
610         CellRendererText* renderer = dynamic_cast<CellRendererText*>(region_list_display.get_column_cell_renderer (0));
611         tv_col->add_attribute(renderer->property_text(), region_list_columns.name);
612         tv_col->add_attribute(renderer->property_foreground_gdk(), region_list_columns.color_);
613         
614         region_list_display.get_selection()->set_mode (SELECTION_MULTIPLE);
615         region_list_display.add_object_drag (region_list_columns.region.index(), "regions");
616
617         /* setup DnD handling */
618         
619         list<TargetEntry> region_list_target_table;
620         
621         region_list_target_table.push_back (TargetEntry ("text/plain"));
622         region_list_target_table.push_back (TargetEntry ("text/uri-list"));
623         region_list_target_table.push_back (TargetEntry ("application/x-rootwin-drop"));
624         
625         region_list_display.add_drop_targets (region_list_target_table);
626         region_list_display.signal_drag_data_received().connect (mem_fun(*this, &Editor::region_list_display_drag_data_received));
627
628         region_list_scroller.add (region_list_display);
629         region_list_scroller.set_policy (POLICY_NEVER, POLICY_AUTOMATIC);
630
631         region_list_display.signal_key_press_event().connect (mem_fun(*this, &Editor::region_list_display_key_press));
632         region_list_display.signal_key_release_event().connect (mem_fun(*this, &Editor::region_list_display_key_release));
633         region_list_display.signal_button_press_event().connect (mem_fun(*this, &Editor::region_list_display_button_press), false);
634         region_list_display.signal_button_release_event().connect (mem_fun(*this, &Editor::region_list_display_button_release));
635         region_list_display.get_selection()->signal_changed().connect (mem_fun(*this, &Editor::region_list_selection_changed));
636         // region_list_display.signal_popup_menu().connect (bind (mem_fun (*this, &Editor::show_region_list_display_context_menu), 1, 0));
637         
638         named_selection_scroller.add (named_selection_display);
639         named_selection_scroller.set_policy (POLICY_NEVER, POLICY_AUTOMATIC);
640
641         named_selection_model = TreeStore::create (named_selection_columns);
642         named_selection_display.set_model (named_selection_model);
643         named_selection_display.append_column (_("Chunks"), named_selection_columns.text);
644         named_selection_display.set_headers_visible (false);
645         named_selection_display.set_size_request (100, -1);
646         named_selection_display.set_name ("RegionListDisplay");
647         
648         named_selection_display.get_selection()->set_mode (SELECTION_SINGLE);
649         named_selection_display.set_size_request (100, -1);
650         named_selection_display.signal_button_press_event().connect (mem_fun(*this, &Editor::named_selection_display_button_press), false);
651         named_selection_display.get_selection()->signal_changed().connect (mem_fun (*this, &Editor::named_selection_display_selection_changed));
652
653         /* SNAPSHOTS */
654
655         snapshot_display_model = ListStore::create (snapshot_display_columns);
656         snapshot_display.set_model (snapshot_display_model);
657         snapshot_display.append_column (X_("snapshot"), snapshot_display_columns.visible_name);
658         snapshot_display.set_name ("SnapshotDisplayList");
659         snapshot_display.set_size_request (75, -1);
660         snapshot_display.set_headers_visible (false);
661         snapshot_display.set_reorderable (false);
662         snapshot_display_scroller.add (snapshot_display);
663         snapshot_display_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
664
665         snapshot_display.get_selection()->signal_changed().connect (mem_fun(*this, &Editor::snapshot_display_selection_changed));
666         snapshot_display.signal_button_press_event().connect (mem_fun (*this, &Editor::snapshot_display_button_press), false);
667
668         Gtk::Label* nlabel;
669
670         nlabel = manage (new Label (_("Regions")));
671         nlabel->set_angle (-90);
672         the_notebook.append_page (region_list_scroller, *nlabel);
673         nlabel = manage (new Label (_("Tracks/Busses")));
674         nlabel->set_angle (-90);
675         the_notebook.append_page (route_list_scroller, *nlabel);
676         nlabel = manage (new Label (_("Snapshots")));
677         nlabel->set_angle (-90);
678         the_notebook.append_page (snapshot_display_scroller, *nlabel);
679         nlabel = manage (new Label (_("Edit Groups")));
680         nlabel->set_angle (-90);
681         the_notebook.append_page (*edit_group_display_packer, *nlabel);
682         nlabel = manage (new Label (_("Chunks")));
683         nlabel->set_angle (-90);
684         the_notebook.append_page (named_selection_scroller, *nlabel);
685
686         the_notebook.set_show_tabs (true);
687         the_notebook.set_scrollable (true);
688         the_notebook.popup_enable ();
689         the_notebook.set_tab_pos (Gtk::POS_RIGHT);
690
691         edit_pane.pack1 (edit_packer, true, true);
692         edit_pane.pack2 (the_notebook, false, true);
693         
694         edit_pane.signal_size_allocate().connect_notify (bind (mem_fun(*this, &Editor::pane_allocation_handler), static_cast<Paned*> (&edit_pane)));
695
696         top_hbox.pack_start (toolbar_frame, true, true);
697
698         HBox *hbox = manage (new HBox);
699         hbox->pack_start (edit_pane, true, true);
700
701         global_vpacker.pack_start (top_hbox, false, false);
702         global_vpacker.pack_start (*hbox, true, true);
703
704         global_hpacker.pack_start (global_vpacker, true, true);
705
706         set_name ("EditorWindow");
707         add_accel_group (ActionManager::ui_manager->get_accel_group());
708
709         vpacker.pack_end (global_hpacker, true, true);
710
711         /* register actions now so that set_state() can find them and set toggles/checks etc */
712         
713         register_actions ();
714         
715         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
716         set_state (*node);
717
718         _playlist_selector = new PlaylistSelector();
719         _playlist_selector->signal_delete_event().connect (bind (sigc::ptr_fun (just_hide_it), static_cast<Window *> (_playlist_selector)));
720
721         AudioRegionView::AudioRegionViewGoingAway.connect (mem_fun(*this, &Editor::catch_vanishing_audio_regionview));
722
723         /* nudge stuff */
724
725         nudge_forward_button.add (*(manage (new Image (get_xpm("right_arrow.xpm")))));
726         nudge_backward_button.add (*(manage (new Image (get_xpm("left_arrow.xpm")))));
727
728         ARDOUR_UI::instance()->tooltips().set_tip (nudge_forward_button, _("Nudge region/selection forwards"));
729         ARDOUR_UI::instance()->tooltips().set_tip (nudge_backward_button, _("Nudge region/selection backwards"));
730
731         nudge_forward_button.set_name ("TransportButton");
732         nudge_backward_button.set_name ("TransportButton");
733
734         fade_context_menu.set_name ("ArdourContextMenu");
735
736         set_title (_("ardour: editor"));
737         set_wmclass (_("ardour_editor"), "Ardour");
738
739         add (vpacker);
740         add_events (Gdk::KEY_PRESS_MASK|Gdk::KEY_RELEASE_MASK);
741
742         signal_configure_event().connect (mem_fun (*ARDOUR_UI::instance(), &ARDOUR_UI::configure_handler));
743         signal_delete_event().connect (mem_fun (*ARDOUR_UI::instance(), &ARDOUR_UI::exit_on_main_window_close));
744
745         /* allow external control surfaces/protocols to do various things */
746
747         ControlProtocol::ZoomToSession.connect (mem_fun (*this, &Editor::temporal_zoom_session));
748         ControlProtocol::ZoomIn.connect (bind (mem_fun (*this, &Editor::temporal_zoom_step), false));
749         ControlProtocol::ZoomOut.connect (bind (mem_fun (*this, &Editor::temporal_zoom_step), true));
750         ControlProtocol::ScrollTimeline.connect (mem_fun (*this, &Editor::control_scroll));
751         constructed = true;
752         instant_save ();
753 }
754
755 Editor::~Editor()
756 {
757         /* <CMT Additions> */
758         if(image_socket_listener)
759         {
760                 if(image_socket_listener->is_connected())
761                 {
762                         image_socket_listener->close_connection() ;
763                 }
764                 
765                 delete image_socket_listener ;
766                 image_socket_listener = 0 ;
767         }
768         /* </CMT Additions> */
769 }
770
771 void
772 Editor::add_toplevel_controls (Container& cont)
773 {
774         vpacker.pack_start (cont, false, false);
775         cont.show_all ();
776 }
777
778 void
779 Editor::catch_vanishing_audio_regionview (AudioRegionView *rv)
780 {
781         /* note: the selection will take care of the vanishing
782            audioregionview by itself.
783         */
784
785         if (clicked_regionview == rv) {
786                 clicked_regionview = 0;
787         }
788
789         if (entered_regionview == rv) {
790                 set_entered_regionview (0);
791         }
792 }
793
794 void
795 Editor::set_entered_regionview (AudioRegionView* rv)
796 {
797         if (rv == entered_regionview) {
798                 return;
799         }
800
801         if (entered_regionview) {
802                 entered_regionview->exited ();
803         }
804
805         if ((entered_regionview = rv) != 0) {
806                 entered_regionview->entered ();
807         }
808 }
809
810 void
811 Editor::set_entered_track (TimeAxisView* tav)
812 {
813         if (entered_track) {
814                 entered_track->exited ();
815         }
816
817         if ((entered_track = tav) != 0) {
818                 entered_track->entered ();
819         }
820 }
821
822 void
823 Editor::show_window ()
824 {
825         show_all ();
826         present ();
827
828         /* now reset all audio_time_axis heights, because widgets might need
829            to be re-hidden
830         */
831         
832         TimeAxisView *tv;
833         
834         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
835                 tv = (static_cast<TimeAxisView*>(*i));
836                 tv->reset_height ();
837         }
838 }
839
840 void
841 Editor::tie_vertical_scrolling ()
842 {
843         double y1 = vertical_adjustment.get_value();
844         controls_layout.get_vadjustment()->set_value (y1);
845         playhead_cursor->set_y_axis(y1);
846         edit_cursor->set_y_axis(y1);
847 }
848
849 void
850 Editor::set_frames_per_unit (double fpu)
851 {
852         jack_nframes_t frames;
853
854         if (fpu == frames_per_unit) {
855                 return;
856         }
857
858         if (fpu < 1.0) {
859                 fpu = 1.0;
860         }
861
862         // convert fpu to frame count
863
864         frames = (jack_nframes_t) floor (fpu * canvas_width);
865         
866         /* don't allow zooms that fit more than the maximum number
867            of frames into an 800 pixel wide space.
868         */
869
870         if (max_frames / fpu < 800.0) {
871                 return;
872         }
873
874         frames_per_unit = fpu;
875
876         if (frames != zoom_range_clock.current_duration()) {
877                 zoom_range_clock.set (frames);
878         }
879
880         /* only update these if we not about to call reposition_x_origin,
881            which will do the same updates.
882         */
883         
884         if (!no_zoom_repos_update) {
885                 horizontal_adjustment.set_value (leftmost_frame/frames_per_unit);
886                 update_fixed_rulers ();
887                 tempo_map_changed (Change (0));
888         }
889
890         if (mouse_mode == MouseRange && selection->time.start () != selection->time.end_frame ()) {
891                 if (!selection->tracks.empty()) {
892                         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
893                                 (*i)->reshow_selection (selection->time);
894                         }
895                 } else {
896                         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
897                                 (*i)->reshow_selection (selection->time);
898                         }
899                 }
900         }
901
902         ZoomChanged (); /* EMIT_SIGNAL */
903
904         reset_hscrollbar_stepping ();
905         reset_scrolling_region ();
906         
907         if (edit_cursor) edit_cursor->set_position (edit_cursor->current_frame);
908         if (playhead_cursor) playhead_cursor->set_position (playhead_cursor->current_frame);
909
910         instant_save ();
911
912 }
913
914 void
915 Editor::instant_save ()
916 {
917         if (!constructed || !ARDOUR_UI::instance()->session_loaded) {
918                 return;
919         }
920
921         if (session) {
922                 session->add_instant_xml(get_state(), session->path());
923         } else {
924                 Config->add_instant_xml(get_state(), get_user_ardour_path());
925         }
926 }
927
928 void
929 Editor::reposition_x_origin (jack_nframes_t frame)
930 {
931         if (frame != leftmost_frame) {
932                 leftmost_frame = frame;
933                 
934                 jack_nframes_t rightmost_frame = leftmost_frame + current_page_frames ();
935
936                 if (rightmost_frame > last_canvas_frame) {
937                         last_canvas_frame = rightmost_frame;
938                         reset_scrolling_region ();
939                 }
940
941                 horizontal_adjustment.set_value (frame/frames_per_unit);
942         }
943 }
944
945 void
946 Editor::edit_cursor_clock_changed()
947 {
948         if (edit_cursor->current_frame != edit_cursor_clock.current_time()) {
949                 edit_cursor->set_position (edit_cursor_clock.current_time());
950         }
951 }
952
953
954 void
955 Editor::zoom_adjustment_changed ()
956 {
957         if (session == 0 || no_zoom_repos_update) {
958                 return;
959         }
960
961         double fpu = zoom_range_clock.current_duration() / canvas_width;
962
963         if (fpu < 1.0) {
964                 fpu = 1.0;
965                 zoom_range_clock.set ((jack_nframes_t) floor (fpu * canvas_width));
966         } else if (fpu > session->current_end_frame() / canvas_width) {
967                 fpu = session->current_end_frame() / canvas_width;
968                 zoom_range_clock.set ((jack_nframes_t) floor (fpu * canvas_width));
969         }
970         
971         temporal_zoom (fpu);
972 }
973
974 void
975 Editor::control_scroll (float fraction)
976 {
977         ENSURE_GUI_THREAD(bind (mem_fun (*this, &Editor::control_scroll), fraction));
978
979         if (!session) {
980                 return;
981         }
982
983         double step = fraction * current_page_frames();
984         jack_nframes_t target;
985
986         if ((fraction < 0.0f) && (session->transport_frame() < (jack_nframes_t) fabs(step))) {
987                 target = 0;
988         } else if ((fraction > 0.0f) && (max_frames - session->transport_frame() < step)) {
989                 target = (max_frames - (current_page_frames()*2)); // allow room for slop in where the PH is on the screen
990         } else {
991                 target = (session->transport_frame() + (jack_nframes_t) floor ((fraction * current_page_frames())));
992         }
993
994         /* move visuals, we'll catch up with it later */
995
996         playhead_cursor->set_position (target);
997
998         if (target > (current_page_frames() / 2)) {
999                 /* try to center PH in window */
1000                 reposition_x_origin (target - (current_page_frames()/2));
1001         } else {
1002                 reposition_x_origin (0);
1003         }
1004
1005         /* cancel the existing */
1006
1007         control_scroll_connection.disconnect ();
1008
1009         /* add the next one */
1010
1011         control_scroll_connection = Glib::signal_timeout().connect (bind (mem_fun (*this, &Editor::deferred_control_scroll), target), 50);
1012 }
1013
1014 bool
1015 Editor::deferred_control_scroll (jack_nframes_t target)
1016 {
1017         session->request_locate (target);
1018         return false;
1019 }
1020
1021 void 
1022 Editor::canvas_horizontally_scrolled ()
1023 {
1024         leftmost_frame = (jack_nframes_t) floor (horizontal_adjustment.get_value() * frames_per_unit);
1025
1026         update_fixed_rulers ();
1027         
1028         if (!edit_hscroll_dragging) {
1029                 tempo_map_changed (Change (0));
1030         } else {
1031                 update_tempo_based_rulers();
1032         }
1033 }
1034
1035 void
1036 Editor::reposition_and_zoom (jack_nframes_t frame, double nfpu)
1037 {
1038         if (!repos_zoom_queued) {
1039                 Glib::signal_idle().connect (bind (mem_fun(*this, &Editor::deferred_reposition_and_zoom), frame, nfpu));
1040                 repos_zoom_queued = true;
1041         }
1042 }
1043
1044 gint
1045 Editor::deferred_reposition_and_zoom (jack_nframes_t frame, double nfpu)
1046 {
1047         /* if we need to force an update to the hscroller stuff,
1048            don't set no_zoom_repos_update.
1049         */
1050
1051         no_zoom_repos_update = (frame != leftmost_frame);
1052         
1053         set_frames_per_unit (nfpu);
1054         if (no_zoom_repos_update) {
1055                 reposition_x_origin  (frame);
1056         }
1057         no_zoom_repos_update = false;
1058         repos_zoom_queued = false;
1059         
1060         return FALSE;
1061 }
1062
1063 void
1064 Editor::on_realize ()
1065 {
1066         Window::on_realize ();
1067         Realized ();
1068 }
1069
1070 void
1071 Editor::queue_session_control_changed (Session::ControlType t)
1072 {
1073         Gtkmm2ext::UI::instance()->call_slot (bind (mem_fun(*this, &Editor::session_control_changed), t));
1074 }
1075
1076 void
1077 Editor::session_control_changed (Session::ControlType t)
1078 {
1079         // right now we're only tracking some state here 
1080
1081         switch (t) {
1082         case Session::AutoLoop:
1083                 update_loop_range_view (true);
1084                 break;
1085         case Session::PunchIn:
1086         case Session::PunchOut:
1087                 update_punch_range_view (true);
1088                 break;
1089
1090         case Session::LayeringModel:
1091                 update_layering_model ();
1092                 break;
1093
1094         default:
1095                 break;
1096         }
1097 }
1098
1099 void
1100 Editor::start_scrolling ()
1101 {
1102         scroll_connection = ARDOUR_UI::instance()->SuperRapidScreenUpdate.connect 
1103                 (mem_fun(*this, &Editor::update_current_screen));
1104 }
1105
1106 void
1107 Editor::stop_scrolling ()
1108 {
1109         scroll_connection.disconnect ();
1110         slower_update_connection.disconnect ();
1111 }
1112
1113 void
1114 Editor::map_position_change (jack_nframes_t frame)
1115 {
1116         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::map_position_change), frame));
1117
1118         if (session == 0 || !_follow_playhead) {
1119                 return;
1120         }
1121
1122         center_screen (frame);
1123         playhead_cursor->set_position (frame);
1124 }       
1125
1126 void
1127 Editor::center_screen (jack_nframes_t frame)
1128 {
1129         double page = canvas_width * frames_per_unit;
1130
1131         /* if we're off the page, then scroll.
1132          */
1133         
1134         if (frame < leftmost_frame || frame >= leftmost_frame + page) {
1135                 center_screen_internal (frame, page);
1136         }
1137 }
1138
1139 void
1140 Editor::center_screen_internal (jack_nframes_t frame, float page)
1141 {
1142         page /= 2;
1143                 
1144         if (frame > page) {
1145                 frame -= (jack_nframes_t) page;
1146         } else {
1147                 frame = 0;
1148         }
1149
1150     reposition_x_origin (frame);
1151 }
1152
1153 void
1154 Editor::handle_new_duration ()
1155 {
1156         ENSURE_GUI_THREAD (mem_fun (*this, &Editor::handle_new_duration));
1157
1158         jack_nframes_t new_end = session->get_maximum_extent() + (jack_nframes_t) floorf (current_page_frames() * 0.10f);
1159                                   
1160         if (new_end > last_canvas_frame) {
1161                 last_canvas_frame = new_end;
1162                 reset_scrolling_region ();
1163         }
1164
1165         horizontal_adjustment.set_value (leftmost_frame/frames_per_unit);
1166 }
1167
1168 void
1169 Editor::update_title_s (const string & snap_name)
1170 {
1171         ENSURE_GUI_THREAD(bind (mem_fun(*this, &Editor::update_title_s), snap_name));
1172         
1173         update_title ();
1174 }
1175
1176 void
1177 Editor::update_title ()
1178 {
1179         ENSURE_GUI_THREAD (mem_fun(*this, &Editor::update_title));
1180
1181         if (session) {
1182                 bool dirty = session->dirty();
1183
1184                 string wintitle = _("ardour: editor: ");
1185
1186                 if (dirty) {
1187                         wintitle += '[';
1188                 }
1189
1190                 wintitle += session->name();
1191
1192                 if (session->snap_name() != session->name()) {
1193                         wintitle += ':';
1194                         wintitle += session->snap_name();
1195                 }
1196
1197                 if (dirty) {
1198                         wintitle += ']';
1199                 }
1200
1201                 set_title (wintitle);
1202         }
1203 }
1204
1205 void
1206 Editor::connect_to_session (Session *t)
1207 {
1208         session = t;
1209
1210         if (first_action_message) {
1211                 first_action_message->hide();
1212         }
1213
1214         update_title ();
1215
1216         session->going_away.connect (mem_fun(*this, &Editor::session_going_away));
1217
1218         /* These signals can all be emitted by a non-GUI thread. Therefore the
1219            handlers for them must not attempt to directly interact with the GUI,
1220            but use Gtkmm2ext::UI::instance()->call_slot();
1221         */
1222
1223         session_connections.push_back (session->TransportStateChange.connect (mem_fun(*this, &Editor::map_transport_state)));
1224         session_connections.push_back (session->PositionChanged.connect (mem_fun(*this, &Editor::map_position_change)));
1225         session_connections.push_back (session->RouteAdded.connect (mem_fun(*this, &Editor::handle_new_route_p)));
1226         session_connections.push_back (session->AudioRegionAdded.connect (mem_fun(*this, &Editor::handle_new_audio_region)));
1227         session_connections.push_back (session->AudioRegionRemoved.connect (mem_fun(*this, &Editor::handle_audio_region_removed)));
1228         session_connections.push_back (session->DurationChanged.connect (mem_fun(*this, &Editor::handle_new_duration)));
1229         session_connections.push_back (session->edit_group_added.connect (mem_fun(*this, &Editor::add_edit_group)));
1230         session_connections.push_back (session->edit_group_removed.connect (mem_fun(*this, &Editor::edit_groups_changed)));
1231         session_connections.push_back (session->NamedSelectionAdded.connect (mem_fun(*this, &Editor::handle_new_named_selection)));
1232         session_connections.push_back (session->NamedSelectionRemoved.connect (mem_fun(*this, &Editor::handle_new_named_selection)));
1233         session_connections.push_back (session->DirtyChanged.connect (mem_fun(*this, &Editor::update_title)));
1234         session_connections.push_back (session->StateSaved.connect (mem_fun(*this, &Editor::update_title_s)));
1235         session_connections.push_back (session->AskAboutPlaylistDeletion.connect (mem_fun(*this, &Editor::playlist_deletion_dialog)));
1236         session_connections.push_back (session->RegionHiddenChange.connect (mem_fun(*this, &Editor::region_hidden)));
1237
1238         session_connections.push_back (session->SMPTEOffsetChanged.connect (mem_fun(*this, &Editor::update_just_smpte)));
1239         session_connections.push_back (session->SMPTETypeChanged.connect (mem_fun(*this, &Editor::update_just_smpte)));
1240
1241         session_connections.push_back (session->tempo_map().StateChanged.connect (mem_fun(*this, &Editor::tempo_map_changed)));
1242
1243         edit_groups_changed ();
1244
1245         edit_cursor_clock.set_session (session);
1246         selection_start_clock.set_session (session);
1247         selection_end_clock.set_session (session);
1248         zoom_range_clock.set_session (session);
1249         _playlist_selector->set_session (session);
1250         nudge_clock.set_session (session);
1251
1252 #ifdef FFT_ANALYSIS
1253         if (analysis_window != 0)
1254                 analysis_window->set_session (session);
1255 #endif
1256
1257         switch (session->get_edit_mode()) {
1258         case Splice:
1259                 edit_mode_selector.set_active_text (edit_mode_strings[splice_index]);
1260                 break;
1261
1262         case Slide:
1263                 edit_mode_selector.set_active_text (edit_mode_strings[slide_index]);
1264                 break;
1265         }
1266
1267         Location* loc = session->locations()->auto_loop_location();
1268         if (loc == 0) {
1269                 loc = new Location (0, session->current_end_frame(), _("Loop"),(Location::Flags) (Location::IsAutoLoop | Location::IsHidden));
1270                 if (loc->start() == loc->end()) {
1271                         loc->set_end (loc->start() + 1);
1272                 }
1273                 session->locations()->add (loc, false);
1274                 session->set_auto_loop_location (loc);
1275         }
1276         else {
1277                 // force name
1278                 loc->set_name (_("Loop"));
1279         }
1280         
1281         loc = session->locations()->auto_punch_location();
1282         if (loc == 0) {
1283                 loc = new Location (0, session->current_end_frame(), _("Punch"), (Location::Flags) (Location::IsAutoPunch | Location::IsHidden));
1284                 if (loc->start() == loc->end()) {
1285                         loc->set_end (loc->start() + 1);
1286                 }
1287                 session->locations()->add (loc, false);
1288                 session->set_auto_punch_location (loc);
1289         }
1290         else {
1291                 // force name
1292                 loc->set_name (_("Punch"));
1293         }
1294
1295         update_loop_range_view (true);
1296         update_punch_range_view (true);
1297         
1298         session->ControlChanged.connect (mem_fun(*this, &Editor::queue_session_control_changed));
1299         session->StateSaved.connect (mem_fun(*this, &Editor::session_state_saved));
1300         
1301         refresh_location_display ();
1302         session->locations()->added.connect (mem_fun(*this, &Editor::add_new_location));
1303         session->locations()->removed.connect (mem_fun(*this, &Editor::location_gone));
1304         session->locations()->changed.connect (mem_fun(*this, &Editor::refresh_location_display));
1305         session->locations()->StateChanged.connect (mem_fun(*this, &Editor::refresh_location_display_s));
1306         session->locations()->end_location()->changed.connect (mem_fun(*this, &Editor::end_location_changed));
1307
1308         bool yn;
1309         RefPtr<Action> act;
1310
1311         act = ActionManager::get_action (X_("Editor"), X_("toggle-xfades-active"));
1312         if (act) {
1313                 RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
1314                 /* do it twice to force the change */
1315                 yn = session->get_crossfades_active();
1316                 tact->set_active (!yn);
1317                 tact->set_active (yn);
1318         }
1319
1320         act = ActionManager::get_action (X_("Editor"), X_("toggle-auto-xfades"));
1321         if (act) {
1322                 RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
1323                 /* do it twice to force the change */
1324                 yn = Config->get_auto_xfade ();
1325                 tact->set_active (!yn);
1326                 tact->set_active (yn);
1327         }
1328
1329         /* xfade visibility state set from editor::set_state() */
1330         
1331         update_crossfade_model ();
1332         update_layering_model ();
1333
1334         handle_new_duration ();
1335
1336         redisplay_regions ();
1337         redisplay_named_selections ();
1338         redisplay_snapshots ();
1339
1340         initial_route_list_display ();
1341
1342         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
1343                 (static_cast<TimeAxisView*>(*i))->set_samples_per_unit (frames_per_unit);
1344         }
1345
1346         /* ::reposition_x_origin() doesn't work right here, since the old
1347            position may be zero already, and it does nothing in such
1348            circumstances.
1349         */
1350
1351         leftmost_frame = 0;
1352         
1353         horizontal_adjustment.set_value (0);
1354
1355         restore_ruler_visibility ();
1356         tempo_map_changed (Change (0));
1357
1358         edit_cursor->set_position (0);
1359         playhead_cursor->set_position (0);
1360
1361         start_scrolling ();
1362
1363         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
1364         set_state (*node);
1365
1366         /* don't show master bus in a new session */
1367
1368         if (ARDOUR_UI::instance()->session_is_new ()) {
1369
1370                 TreeModel::Children rows = route_display_model->children();
1371                 TreeModel::Children::iterator i;
1372         
1373                 no_route_list_redisplay = true;
1374                 
1375                 for (i = rows.begin(); i != rows.end(); ++i) {
1376                         TimeAxisView *tv =  (*i)[route_display_columns.tv];
1377                         AudioTimeAxisView *atv;
1378                         
1379                         if ((atv = dynamic_cast<AudioTimeAxisView*>(tv)) != 0) {
1380                                 if (atv->route().master()) {
1381                                         route_list_display.get_selection()->unselect (i);
1382                                 }
1383                         }
1384                 }
1385                 
1386                 no_route_list_redisplay = false;
1387                 redisplay_route_list ();
1388         }
1389 }
1390
1391 void
1392 Editor::build_cursors ()
1393 {
1394         using namespace Gdk;
1395         
1396         Gdk::Color mbg ("#000000" ); /* Black */
1397         Gdk::Color mfg ("#0000ff" ); /* Blue. */
1398
1399         {
1400                 RefPtr<Bitmap> source, mask;
1401                 source = Bitmap::create (mag_bits, mag_width, mag_height);
1402                 mask = Bitmap::create (magmask_bits, mag_width, mag_height);
1403                 zoom_cursor = new Gdk::Cursor (source, mask, mfg, mbg, mag_x_hot, mag_y_hot);
1404         }
1405
1406         Gdk::Color fbg ("#ffffff" );
1407         Gdk::Color ffg  ("#000000" );
1408         
1409         {
1410                 RefPtr<Bitmap> source, mask;
1411                 
1412                 source = Bitmap::create (fader_cursor_bits, fader_cursor_width, fader_cursor_height);
1413                 mask = Bitmap::create (fader_cursor_mask_bits, fader_cursor_width, fader_cursor_height);
1414                 fader_cursor = new Gdk::Cursor (source, mask, ffg, fbg, fader_cursor_x_hot, fader_cursor_y_hot);
1415         }
1416         
1417         { 
1418                 RefPtr<Bitmap> source, mask;
1419                 source = Bitmap::create (speaker_cursor_bits, speaker_cursor_width, speaker_cursor_height);
1420                 mask = Bitmap::create (speaker_cursor_mask_bits, speaker_cursor_width, speaker_cursor_height);
1421                 speaker_cursor = new Gdk::Cursor (source, mask, ffg, fbg, speaker_cursor_x_hot, speaker_cursor_y_hot);
1422         }
1423
1424         grabber_cursor = new Gdk::Cursor (HAND2);
1425         cross_hair_cursor = new Gdk::Cursor (CROSSHAIR);
1426         trimmer_cursor =  new Gdk::Cursor (SB_H_DOUBLE_ARROW);
1427         selector_cursor = new Gdk::Cursor (XTERM);
1428         time_fx_cursor = new Gdk::Cursor (SIZING);
1429         wait_cursor = new Gdk::Cursor  (WATCH);
1430         timebar_cursor = new Gdk::Cursor(LEFT_PTR);
1431 }
1432
1433 void
1434 Editor::popup_fade_context_menu (int button, int32_t time, ArdourCanvas::Item* item, ItemType item_type)
1435 {
1436         using namespace Menu_Helpers;
1437         AudioRegionView* arv = static_cast<AudioRegionView*> (item->get_data ("regionview"));
1438
1439         if (arv == 0) {
1440                 fatal << _("programming error: fade in canvas item has no regionview data pointer!") << endmsg;
1441                 /*NOTREACHED*/
1442         }
1443
1444         MenuList& items (fade_context_menu.items());
1445
1446         items.clear ();
1447
1448         switch (item_type) {
1449         case FadeInItem:
1450         case FadeInHandleItem:
1451                 if (arv->region.fade_in_active()) {
1452                         items.push_back (MenuElem (_("Deactivate"), bind (mem_fun (*arv, &AudioRegionView::set_fade_in_active), false)));
1453                 } else {
1454                         items.push_back (MenuElem (_("Activate"), bind (mem_fun (*arv, &AudioRegionView::set_fade_in_active), true)));
1455                 }
1456                 
1457                 items.push_back (SeparatorElem());
1458                 
1459                 items.push_back (MenuElem (_("Linear"), bind (mem_fun (arv->region, &AudioRegion::set_fade_in_shape), AudioRegion::Linear)));
1460                 items.push_back (MenuElem (_("Slowest"), bind (mem_fun (arv->region, &AudioRegion::set_fade_in_shape), AudioRegion::LogB)));
1461                 items.push_back (MenuElem (_("Slow"), bind (mem_fun (arv->region, &AudioRegion::set_fade_in_shape), AudioRegion::Fast)));
1462                 items.push_back (MenuElem (_("Fast"), bind (mem_fun (arv->region, &AudioRegion::set_fade_in_shape), AudioRegion::LogA)));
1463                 items.push_back (MenuElem (_("Fastest"), bind (mem_fun (arv->region, &AudioRegion::set_fade_in_shape), AudioRegion::Slow)));
1464                 break;
1465
1466         case FadeOutItem:
1467         case FadeOutHandleItem:
1468                 if (arv->region.fade_out_active()) {
1469                         items.push_back (MenuElem (_("Deactivate"), bind (mem_fun (*arv, &AudioRegionView::set_fade_out_active), false)));
1470                 } else {
1471                         items.push_back (MenuElem (_("Activate"), bind (mem_fun (*arv, &AudioRegionView::set_fade_out_active), true)));
1472                 }
1473                 
1474                 items.push_back (SeparatorElem());
1475                 
1476                 items.push_back (MenuElem (_("Linear"), bind (mem_fun (arv->region, &AudioRegion::set_fade_out_shape), AudioRegion::Linear)));
1477                 items.push_back (MenuElem (_("Slowest"), bind (mem_fun (arv->region, &AudioRegion::set_fade_out_shape), AudioRegion::Fast)));
1478                 items.push_back (MenuElem (_("Slow"), bind (mem_fun (arv->region, &AudioRegion::set_fade_out_shape), AudioRegion::LogB)));
1479                 items.push_back (MenuElem (_("Fast"), bind (mem_fun (arv->region, &AudioRegion::set_fade_out_shape), AudioRegion::LogA)));
1480                 items.push_back (MenuElem (_("Fastest"), bind (mem_fun (arv->region, &AudioRegion::set_fade_out_shape), AudioRegion::Slow)));
1481
1482                 break;
1483         default:
1484                 fatal << _("programming error: ")
1485                       << X_("non-fade canvas item passed to popup_fade_context_menu()")
1486                       << endmsg;
1487                 /*NOTREACHED*/
1488         }
1489
1490         fade_context_menu.popup (button, time);
1491 }
1492
1493 void
1494 Editor::popup_track_context_menu (int button, int32_t time, ItemType item_type, bool with_selection, jack_nframes_t frame)
1495 {
1496         using namespace Menu_Helpers;
1497         Menu* (Editor::*build_menu_function)(jack_nframes_t);
1498         Menu *menu;
1499
1500         switch (item_type) {
1501         case RegionItem:
1502         case AudioRegionViewName:
1503         case AudioRegionViewNameHighlight:
1504                 if (with_selection) {
1505                         build_menu_function = &Editor::build_track_selection_context_menu;
1506                 } else {
1507                         build_menu_function = &Editor::build_track_region_context_menu;
1508                 }
1509                 break;
1510
1511         case SelectionItem:
1512                 if (with_selection) {
1513                         build_menu_function = &Editor::build_track_selection_context_menu;
1514                 } else {
1515                         build_menu_function = &Editor::build_track_context_menu;
1516                 }
1517                 break;
1518
1519         case CrossfadeViewItem:
1520                 build_menu_function = &Editor::build_track_crossfade_context_menu;
1521                 break;
1522
1523         case StreamItem:
1524                 if (clicked_audio_trackview->get_diskstream()) {
1525                         build_menu_function = &Editor::build_track_context_menu;
1526                 } else {
1527                         build_menu_function = &Editor::build_track_bus_context_menu;
1528                 }
1529                 break;
1530
1531         default:
1532                 /* probably shouldn't happen but if it does, we don't care */
1533                 return;
1534         }
1535
1536         menu = (this->*build_menu_function)(frame);
1537         menu->set_name ("ArdourContextMenu");
1538         
1539         /* now handle specific situations */
1540
1541         switch (item_type) {
1542         case RegionItem:
1543         case AudioRegionViewName:
1544         case AudioRegionViewNameHighlight:
1545                 if (!with_selection) {
1546                         if (region_edit_menu_split_item) {
1547                                 if (clicked_regionview && clicked_regionview->region.covers (edit_cursor->current_frame)) {
1548                                         ActionManager::set_sensitive (ActionManager::edit_cursor_in_region_sensitive_actions, true);
1549                                 } else {
1550                                         ActionManager::set_sensitive (ActionManager::edit_cursor_in_region_sensitive_actions, false);
1551                                 }
1552                         }
1553                         if (region_edit_menu_split_multichannel_item) {
1554                                 if (clicked_regionview && clicked_regionview->region.n_channels() > 1) {
1555                                         // GTK2FIX find the action, change its sensitivity
1556                                         // region_edit_menu_split_multichannel_item->set_sensitive (true);
1557                                 } else {
1558                                         // GTK2FIX see above
1559                                         // region_edit_menu_split_multichannel_item->set_sensitive (false);
1560                                 }
1561                         }
1562                 }
1563                 break;
1564
1565         case SelectionItem:
1566                 break;
1567
1568         case CrossfadeViewItem:
1569                 break;
1570
1571         case StreamItem:
1572                 break;
1573
1574         default:
1575                 /* probably shouldn't happen but if it does, we don't care */
1576                 return;
1577         }
1578
1579         if (clicked_audio_trackview && clicked_audio_trackview->audio_track()) {
1580
1581                 /* Bounce to disk */
1582                 
1583                 using namespace Menu_Helpers;
1584                 MenuList& edit_items  = menu->items();
1585                 
1586                 edit_items.push_back (SeparatorElem());
1587
1588                 switch (clicked_audio_trackview->audio_track()->freeze_state()) {
1589                 case AudioTrack::NoFreeze:
1590                         edit_items.push_back (MenuElem (_("Freeze"), mem_fun(*this, &Editor::freeze_route)));
1591                         break;
1592
1593                 case AudioTrack::Frozen:
1594                         edit_items.push_back (MenuElem (_("Unfreeze"), mem_fun(*this, &Editor::unfreeze_route)));
1595                         break;
1596                         
1597                 case AudioTrack::UnFrozen:
1598                         edit_items.push_back (MenuElem (_("Freeze"), mem_fun(*this, &Editor::freeze_route)));
1599                         break;
1600                 }
1601
1602         }
1603
1604         menu->popup (button, time);
1605 }
1606
1607 Menu*
1608 Editor::build_track_context_menu (jack_nframes_t ignored)
1609 {
1610         using namespace Menu_Helpers;
1611
1612         MenuList& edit_items = track_context_menu.items();
1613         edit_items.clear();
1614
1615         add_dstream_context_items (edit_items);
1616         return &track_context_menu;
1617 }
1618
1619 Menu*
1620 Editor::build_track_bus_context_menu (jack_nframes_t ignored)
1621 {
1622         using namespace Menu_Helpers;
1623
1624         MenuList& edit_items = track_context_menu.items();
1625         edit_items.clear();
1626
1627         add_bus_context_items (edit_items);
1628         return &track_context_menu;
1629 }
1630
1631 Menu*
1632 Editor::build_track_region_context_menu (jack_nframes_t frame)
1633 {
1634         using namespace Menu_Helpers;
1635         MenuList& edit_items  = track_region_context_menu.items();
1636         edit_items.clear();
1637
1638         AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*> (clicked_trackview);
1639
1640         if (atv) {
1641                 AudioDiskstream* ds;
1642                 Playlist* pl;
1643                 
1644                 if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()))) {
1645                         Playlist::RegionList* regions = pl->regions_at ((jack_nframes_t) floor ( (double)frame * ds->speed()));
1646                         for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
1647                                 add_region_context_items (atv->view, (*i), edit_items);
1648                         }
1649                         delete regions;
1650                 }
1651         }
1652
1653         add_dstream_context_items (edit_items);
1654
1655         return &track_region_context_menu;
1656 }
1657
1658 Menu*
1659 Editor::build_track_crossfade_context_menu (jack_nframes_t frame)
1660 {
1661         using namespace Menu_Helpers;
1662         MenuList& edit_items  = track_crossfade_context_menu.items();
1663         edit_items.clear ();
1664
1665         AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*> (clicked_trackview);
1666
1667         if (atv) {
1668                 AudioDiskstream* ds;
1669                 Playlist* pl;
1670                 AudioPlaylist* apl;
1671
1672                 if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()) != 0) && ((apl = dynamic_cast<AudioPlaylist*> (pl)) != 0)) {
1673
1674                         Playlist::RegionList* regions = pl->regions_at (frame);
1675                         AudioPlaylist::Crossfades xfades;
1676
1677                         apl->crossfades_at (frame, xfades);
1678
1679                         bool many = xfades.size() > 1;
1680
1681                         for (AudioPlaylist::Crossfades::iterator i = xfades.begin(); i != xfades.end(); ++i) {
1682                                 add_crossfade_context_items (atv->view, (*i), edit_items, many);
1683                         }
1684
1685                         for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
1686                                 add_region_context_items (atv->view, (*i), edit_items);
1687                         }
1688
1689                         delete regions;
1690                 }
1691         }
1692
1693         add_dstream_context_items (edit_items);
1694
1695         return &track_crossfade_context_menu;
1696 }
1697
1698 #ifdef FFT_ANALYSIS
1699 void
1700 Editor::analyze_region_selection()
1701 {
1702         if (analysis_window == 0) {
1703                 analysis_window = new AnalysisWindow();
1704
1705                 if (session != 0)
1706                         analysis_window->set_session(session);
1707
1708                 analysis_window->show_all();
1709         }
1710
1711         analysis_window->set_regionmode();
1712         analysis_window->analyze();
1713         
1714         analysis_window->present();
1715 }
1716
1717 void
1718 Editor::analyze_range_selection()
1719 {
1720         if (analysis_window == 0) {
1721                 analysis_window = new AnalysisWindow();
1722
1723                 if (session != 0)
1724                         analysis_window->set_session(session);
1725
1726                 analysis_window->show_all();
1727         }
1728
1729         analysis_window->set_rangemode();
1730         analysis_window->analyze();
1731         
1732         analysis_window->present();
1733 }
1734 #endif /* FFT_ANALYSIS */
1735
1736
1737
1738 Menu*
1739 Editor::build_track_selection_context_menu (jack_nframes_t ignored)
1740 {
1741         using namespace Menu_Helpers;
1742         MenuList& edit_items  = track_selection_context_menu.items();
1743         edit_items.clear ();
1744
1745         add_selection_context_items (edit_items);
1746         add_dstream_context_items (edit_items);
1747
1748         return &track_selection_context_menu;
1749 }
1750
1751 void
1752 Editor::add_crossfade_context_items (StreamView* view, Crossfade* xfade, Menu_Helpers::MenuList& edit_items, bool many)
1753 {
1754         using namespace Menu_Helpers;
1755         Menu     *xfade_menu = manage (new Menu);
1756         MenuList& items       = xfade_menu->items();
1757         xfade_menu->set_name ("ArdourContextMenu");
1758         string str;
1759
1760         if (xfade->active()) {
1761                 str = _("Mute");
1762         } else { 
1763                 str = _("Unmute");
1764         }
1765
1766         items.push_back (MenuElem (str, bind (mem_fun(*this, &Editor::toggle_xfade_active), xfade)));
1767         items.push_back (MenuElem (_("Edit"), bind (mem_fun(*this, &Editor::edit_xfade), xfade)));
1768
1769         if (xfade->can_follow_overlap()) {
1770
1771                 if (xfade->following_overlap()) {
1772                         str = _("Convert to short");
1773                 } else {
1774                         str = _("Convert to full");
1775                 }
1776
1777                 items.push_back (MenuElem (str, bind (mem_fun(*this, &Editor::toggle_xfade_length), xfade)));
1778         }
1779
1780         if (many) {
1781                 str = xfade->out().name();
1782                 str += "->";
1783                 str += xfade->in().name();
1784         } else {
1785                 str = _("Crossfade");
1786         }
1787
1788         edit_items.push_back (MenuElem (str, *xfade_menu));
1789         edit_items.push_back (SeparatorElem());
1790 }
1791
1792 void
1793 Editor::xfade_edit_left_region ()
1794 {
1795         if (clicked_crossfadeview) {
1796                 clicked_crossfadeview->left_view.show_region_editor ();
1797         }
1798 }
1799
1800 void
1801 Editor::xfade_edit_right_region ()
1802 {
1803         if (clicked_crossfadeview) {
1804                 clicked_crossfadeview->right_view.show_region_editor ();
1805         }
1806 }
1807
1808 void
1809 Editor::add_region_context_items (StreamView* sv, Region* region, Menu_Helpers::MenuList& edit_items)
1810 {
1811         using namespace Menu_Helpers;
1812         Menu     *region_menu = manage (new Menu);
1813         MenuList& items       = region_menu->items();
1814         region_menu->set_name ("ArdourContextMenu");
1815         
1816         AudioRegion* ar = 0;
1817
1818         if (region) {
1819                 ar = dynamic_cast<AudioRegion*> (region);
1820         }
1821
1822         /* when this particular menu pops up, make the relevant region 
1823            become selected.
1824         */
1825
1826         region_menu->signal_map_event().connect (bind (mem_fun(*this, &Editor::set_selected_regionview_from_map_event), sv, region));
1827
1828         items.push_back (MenuElem (_("Popup region editor"), mem_fun(*this, &Editor::edit_region)));
1829         items.push_back (MenuElem (_("Raise to top layer"), mem_fun(*this, &Editor::raise_region_to_top)));
1830         items.push_back (MenuElem (_("Lower to bottom layer"), mem_fun  (*this, &Editor::lower_region_to_bottom)));
1831         items.push_back (SeparatorElem());
1832         items.push_back (MenuElem (_("Define sync point"), mem_fun(*this, &Editor::set_region_sync_from_edit_cursor)));
1833         items.push_back (MenuElem (_("Remove sync point"), mem_fun(*this, &Editor::remove_region_sync)));
1834         items.push_back (SeparatorElem());
1835
1836         items.push_back (MenuElem (_("Audition"), mem_fun(*this, &Editor::audition_selected_region)));
1837         items.push_back (MenuElem (_("Export"), mem_fun(*this, &Editor::export_region)));
1838         items.push_back (MenuElem (_("Bounce"), mem_fun(*this, &Editor::bounce_region_selection)));
1839
1840 #ifdef FFT_ANALYSIS
1841         items.push_back (MenuElem (_("Analyze region"), mem_fun(*this, &Editor::analyze_region_selection)));
1842 #endif
1843
1844         items.push_back (SeparatorElem());
1845
1846         /* XXX hopefully this nonsense will go away with SigC++ 2.X, where the compiler
1847            might be able to figure out which overloaded member function to use in
1848            a bind() call ...
1849         */
1850
1851         void (Editor::*type_A_pmf)(void (Region::*pmf)(bool), bool) = &Editor::region_selection_op;
1852
1853         items.push_back (MenuElem (_("Lock"), bind (mem_fun(*this, type_A_pmf), &Region::set_locked, true)));
1854         items.push_back (MenuElem (_("Unlock"), bind (mem_fun(*this, type_A_pmf), &Region::set_locked, false)));
1855         items.push_back (SeparatorElem());
1856
1857         if (region->muted()) {
1858                 items.push_back (MenuElem (_("Unmute"), bind (mem_fun(*this, type_A_pmf), &Region::set_muted, false)));
1859         } else {
1860                 items.push_back (MenuElem (_("Mute"), bind (mem_fun(*this, type_A_pmf), &Region::set_muted, true)));
1861         }
1862         items.push_back (SeparatorElem());
1863
1864         items.push_back (MenuElem (_("Original position"), mem_fun(*this, &Editor::naturalize)));
1865         items.push_back (SeparatorElem());
1866
1867
1868         if (ar) {
1869
1870                 items.push_back (MenuElem (_("Toggle envelope visibility"), mem_fun(*this, &Editor::toggle_gain_envelope_visibility)));
1871                 items.push_back (MenuElem (_("Toggle envelope active"), mem_fun(*this, &Editor::toggle_gain_envelope_active)));
1872                 items.push_back (SeparatorElem());
1873
1874                 if (ar->scale_amplitude() != 1.0f) {
1875                         items.push_back (MenuElem (_("DeNormalize"), mem_fun(*this, &Editor::denormalize_region)));
1876                 } else {
1877                         items.push_back (MenuElem (_("Normalize"), mem_fun(*this, &Editor::normalize_region)));
1878                 }
1879         }
1880         items.push_back (MenuElem (_("Reverse"), mem_fun(*this, &Editor::reverse_region)));
1881         items.push_back (SeparatorElem());
1882
1883
1884         /* range related stuff */
1885
1886         items.push_back (MenuElem (_("Add Range Markers"), mem_fun (*this, &Editor::add_location_from_audio_region)));
1887         items.push_back (MenuElem (_("Set Range"), mem_fun (*this, &Editor::set_selection_from_audio_region)));
1888         items.push_back (SeparatorElem());
1889                          
1890         /* Nudge region */
1891
1892         Menu *nudge_menu = manage (new Menu());
1893         MenuList& nudge_items = nudge_menu->items();
1894         nudge_menu->set_name ("ArdourContextMenu");
1895         
1896         nudge_items.push_back (MenuElem (_("Nudge fwd"), (bind (mem_fun(*this, &Editor::nudge_forward), false))));
1897         nudge_items.push_back (MenuElem (_("Nudge bwd"), (bind (mem_fun(*this, &Editor::nudge_backward), false))));
1898         nudge_items.push_back (MenuElem (_("Nudge fwd by capture offset"), (mem_fun(*this, &Editor::nudge_forward_capture_offset))));
1899         nudge_items.push_back (MenuElem (_("Nudge bwd by capture offset"), (mem_fun(*this, &Editor::nudge_backward_capture_offset))));
1900
1901         items.push_back (MenuElem (_("Nudge"), *nudge_menu));
1902         items.push_back (SeparatorElem());
1903
1904         Menu *trim_menu = manage (new Menu);
1905         MenuList& trim_items = trim_menu->items();
1906         trim_menu->set_name ("ArdourContextMenu");
1907         
1908         trim_items.push_back (MenuElem (_("Start to edit cursor"), mem_fun(*this, &Editor::trim_region_from_edit_cursor)));
1909         trim_items.push_back (MenuElem (_("Edit cursor to end"), mem_fun(*this, &Editor::trim_region_to_edit_cursor)));
1910                              
1911         items.push_back (MenuElem (_("Trim"), *trim_menu));
1912         items.push_back (SeparatorElem());
1913
1914         items.push_back (MenuElem (_("Split"), (mem_fun(*this, &Editor::split_region))));
1915         region_edit_menu_split_item = &items.back();
1916
1917         items.push_back (MenuElem (_("Make mono regions"), (mem_fun(*this, &Editor::split_multichannel_region))));
1918         region_edit_menu_split_multichannel_item = &items.back();
1919
1920         items.push_back (MenuElem (_("Duplicate"), (bind (mem_fun(*this, &Editor::duplicate_dialog), true))));
1921         items.push_back (MenuElem (_("Fill Track"), (mem_fun(*this, &Editor::region_fill_track))));
1922         items.push_back (SeparatorElem());
1923         items.push_back (MenuElem (_("Remove"), mem_fun(*this, &Editor::remove_clicked_region)));
1924         items.push_back (SeparatorElem());
1925         items.push_back (MenuElem (_("Destroy"), mem_fun(*this, &Editor::destroy_clicked_region)));
1926
1927         /* OK, stick the region submenu at the top of the list, and then add
1928            the standard items.
1929         */
1930
1931         /* we have to hack up the region name because "_" has a special
1932            meaning for menu titles.
1933         */
1934
1935         string::size_type pos = 0;
1936         string menu_item_name = region->name();
1937
1938         while ((pos = menu_item_name.find ("_", pos)) != string::npos) {
1939                 menu_item_name.replace (pos, 1, "__");
1940                 pos += 2;
1941         }
1942         
1943         edit_items.push_back (MenuElem (menu_item_name, *region_menu));
1944         edit_items.push_back (SeparatorElem());
1945 }
1946
1947 void
1948 Editor::add_selection_context_items (Menu_Helpers::MenuList& edit_items)
1949 {
1950         using namespace Menu_Helpers;
1951         Menu     *selection_menu = manage (new Menu);
1952         MenuList& items       = selection_menu->items();
1953         selection_menu->set_name ("ArdourContextMenu");
1954
1955         items.push_back (MenuElem (_("Play range"), mem_fun(*this, &Editor::play_selection)));
1956         items.push_back (MenuElem (_("Loop range"), mem_fun(*this, &Editor::set_route_loop_selection)));
1957
1958 #ifdef FFT_ANALYSIS
1959         items.push_back (SeparatorElem());
1960         items.push_back (MenuElem (_("Analyze range"), mem_fun(*this, &Editor::analyze_range_selection)));
1961 #endif
1962         
1963         items.push_back (SeparatorElem());
1964         items.push_back (MenuElem (_("Separate range to track"), mem_fun(*this, &Editor::separate_region_from_selection)));
1965         items.push_back (MenuElem (_("Separate range to region list"), mem_fun(*this, &Editor::new_region_from_selection)));
1966         
1967         items.push_back (SeparatorElem());
1968         items.push_back (MenuElem (_("Select all in range"), mem_fun(*this, &Editor::select_all_selectables_using_time_selection)));
1969         items.push_back (SeparatorElem());
1970         items.push_back (MenuElem (_("Set range to loop range"), mem_fun(*this, &Editor::set_selection_from_loop)));
1971         items.push_back (MenuElem (_("Set range to punch range"), mem_fun(*this, &Editor::set_selection_from_punch)));
1972         items.push_back (SeparatorElem());
1973         items.push_back (MenuElem (_("Crop region to range"), mem_fun(*this, &Editor::crop_region_to_selection)));
1974         items.push_back (MenuElem (_("Fill range with region"), mem_fun(*this, &Editor::region_fill_selection)));
1975         items.push_back (MenuElem (_("Duplicate range"), bind (mem_fun(*this, &Editor::duplicate_dialog), false)));
1976         items.push_back (MenuElem (_("Create chunk from range"), mem_fun(*this, &Editor::name_selection)));
1977         items.push_back (SeparatorElem());
1978         items.push_back (MenuElem (_("Bounce range"), mem_fun(*this, &Editor::bounce_range_selection)));
1979         items.push_back (MenuElem (_("Export range"), mem_fun(*this, &Editor::export_selection)));
1980
1981         edit_items.push_back (MenuElem (_("Range"), *selection_menu));
1982         edit_items.push_back (SeparatorElem());
1983 }
1984
1985 void
1986 Editor::add_dstream_context_items (Menu_Helpers::MenuList& edit_items)
1987 {
1988         using namespace Menu_Helpers;
1989
1990         /* Playback */
1991
1992         Menu *play_menu = manage (new Menu);
1993         MenuList& play_items = play_menu->items();
1994         play_menu->set_name ("ArdourContextMenu");
1995         
1996         play_items.push_back (MenuElem (_("Play from edit cursor")));
1997         play_items.push_back (MenuElem (_("Play from start"), mem_fun(*this, &Editor::play_from_start)));
1998         play_items.push_back (MenuElem (_("Play region"), mem_fun(*this, &Editor::play_selected_region)));
1999         play_items.push_back (SeparatorElem());
2000         play_items.push_back (MenuElem (_("Loop Region"), mem_fun(*this, &Editor::loop_selected_region)));
2001         
2002         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2003
2004         /* Selection */
2005
2006         Menu *select_menu = manage (new Menu);
2007         MenuList& select_items = select_menu->items();
2008         select_menu->set_name ("ArdourContextMenu");
2009         
2010         select_items.push_back (MenuElem (_("Select All in track"), bind (mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2011         select_items.push_back (MenuElem (_("Select All"), bind (mem_fun(*this, &Editor::select_all), Selection::Set)));
2012         select_items.push_back (MenuElem (_("Invert selection in track"), mem_fun(*this, &Editor::invert_selection_in_track)));
2013         select_items.push_back (MenuElem (_("Invert selection"), mem_fun(*this, &Editor::invert_selection)));
2014         select_items.push_back (SeparatorElem());
2015         select_items.push_back (MenuElem (_("Set range to loop range"), mem_fun(*this, &Editor::set_selection_from_loop)));
2016         select_items.push_back (MenuElem (_("Set range to punch range"), mem_fun(*this, &Editor::set_selection_from_punch)));
2017         select_items.push_back (SeparatorElem());
2018         select_items.push_back (MenuElem (_("Select all after edit cursor"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), edit_cursor, true)));
2019         select_items.push_back (MenuElem (_("Select all before edit cursor"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), edit_cursor, false)));
2020         select_items.push_back (MenuElem (_("Select all after playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2021         select_items.push_back (MenuElem (_("Select all before playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2022         select_items.push_back (MenuElem (_("Select all between cursors"), bind (mem_fun(*this, &Editor::select_all_selectables_between_cursors), playhead_cursor, edit_cursor)));
2023         select_items.push_back (SeparatorElem());
2024
2025         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2026
2027         /* Cut-n-Paste */
2028
2029         Menu *cutnpaste_menu = manage (new Menu);
2030         MenuList& cutnpaste_items = cutnpaste_menu->items();
2031         cutnpaste_menu->set_name ("ArdourContextMenu");
2032         
2033         cutnpaste_items.push_back (MenuElem (_("Cut"), mem_fun(*this, &Editor::cut)));
2034         cutnpaste_items.push_back (MenuElem (_("Copy"), mem_fun(*this, &Editor::copy)));
2035         cutnpaste_items.push_back (MenuElem (_("Paste at edit cursor"), bind (mem_fun(*this, &Editor::paste), 1.0f)));
2036         cutnpaste_items.push_back (MenuElem (_("Paste at mouse"), mem_fun(*this, &Editor::mouse_paste)));
2037
2038         cutnpaste_items.push_back (SeparatorElem());
2039
2040         cutnpaste_items.push_back (MenuElem (_("Align"), bind (mem_fun(*this, &Editor::align), ARDOUR::SyncPoint)));
2041         cutnpaste_items.push_back (MenuElem (_("Align Relative"), bind (mem_fun(*this, &Editor::align_relative), ARDOUR::SyncPoint)));
2042
2043         cutnpaste_items.push_back (SeparatorElem());
2044
2045         cutnpaste_items.push_back (MenuElem (_("Insert chunk"), bind (mem_fun(*this, &Editor::paste_named_selection), 1.0f)));
2046
2047         edit_items.push_back (MenuElem (_("Edit"), *cutnpaste_menu));
2048
2049         /* Adding new material */
2050         
2051         edit_items.push_back (SeparatorElem());
2052         edit_items.push_back (MenuElem (_("Insert Selected Region"), bind (mem_fun(*this, &Editor::insert_region_list_selection), 1.0f)));
2053         edit_items.push_back (MenuElem (_("Insert Existing Audio"), bind (mem_fun(*this, &Editor::add_external_audio_action), ImportToTrack)));
2054
2055         /* Nudge track */
2056
2057         Menu *nudge_menu = manage (new Menu());
2058         MenuList& nudge_items = nudge_menu->items();
2059         nudge_menu->set_name ("ArdourContextMenu");
2060         
2061         edit_items.push_back (SeparatorElem());
2062         nudge_items.push_back (MenuElem (_("Nudge entire track fwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, true))));
2063         nudge_items.push_back (MenuElem (_("Nudge track after edit cursor fwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, true))));
2064         nudge_items.push_back (MenuElem (_("Nudge entire track bwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, false))));
2065         nudge_items.push_back (MenuElem (_("Nudge track after edit cursor bwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, false))));
2066
2067         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2068 }
2069
2070 void
2071 Editor::add_bus_context_items (Menu_Helpers::MenuList& edit_items)
2072 {
2073         using namespace Menu_Helpers;
2074
2075         /* Playback */
2076
2077         Menu *play_menu = manage (new Menu);
2078         MenuList& play_items = play_menu->items();
2079         play_menu->set_name ("ArdourContextMenu");
2080         
2081         play_items.push_back (MenuElem (_("Play from edit cursor")));
2082         play_items.push_back (MenuElem (_("Play from start"), mem_fun(*this, &Editor::play_from_start)));
2083         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2084
2085         /* Selection */
2086
2087         Menu *select_menu = manage (new Menu);
2088         MenuList& select_items = select_menu->items();
2089         select_menu->set_name ("ArdourContextMenu");
2090         
2091         select_items.push_back (MenuElem (_("Select All in track"), bind (mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2092         select_items.push_back (MenuElem (_("Select All"), bind (mem_fun(*this, &Editor::select_all), Selection::Set)));
2093         select_items.push_back (MenuElem (_("Invert selection in track"), mem_fun(*this, &Editor::invert_selection_in_track)));
2094         select_items.push_back (MenuElem (_("Invert selection"), mem_fun(*this, &Editor::invert_selection)));
2095         select_items.push_back (SeparatorElem());
2096         select_items.push_back (MenuElem (_("Select all after edit cursor"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), edit_cursor, true)));
2097         select_items.push_back (MenuElem (_("Select all before edit cursor"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), edit_cursor, false)));
2098         select_items.push_back (MenuElem (_("Select all after playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2099         select_items.push_back (MenuElem (_("Select all before playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2100
2101         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2102
2103         /* Cut-n-Paste */
2104
2105         Menu *cutnpaste_menu = manage (new Menu);
2106         MenuList& cutnpaste_items = cutnpaste_menu->items();
2107         cutnpaste_menu->set_name ("ArdourContextMenu");
2108         
2109         cutnpaste_items.push_back (MenuElem (_("Cut"), mem_fun(*this, &Editor::cut)));
2110         cutnpaste_items.push_back (MenuElem (_("Copy"), mem_fun(*this, &Editor::copy)));
2111         cutnpaste_items.push_back (MenuElem (_("Paste"), bind (mem_fun(*this, &Editor::paste), 1.0f)));
2112
2113         Menu *nudge_menu = manage (new Menu());
2114         MenuList& nudge_items = nudge_menu->items();
2115         nudge_menu->set_name ("ArdourContextMenu");
2116         
2117         edit_items.push_back (SeparatorElem());
2118         nudge_items.push_back (MenuElem (_("Nudge entire track fwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, true))));
2119         nudge_items.push_back (MenuElem (_("Nudge track after edit cursor fwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, true))));
2120         nudge_items.push_back (MenuElem (_("Nudge entire track bwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, false))));
2121         nudge_items.push_back (MenuElem (_("Nudge track after edit cursor bwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, false))));
2122
2123         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2124 }
2125
2126 /* CURSOR SETTING AND MARKS AND STUFF */
2127
2128 void
2129 Editor::set_snap_to (SnapType st)
2130 {
2131         snap_type = st;
2132         vector<string> txt = internationalize (snap_type_strings);
2133         snap_type_selector.set_active_text (txt[(int)st]);
2134
2135         instant_save ();
2136
2137         switch (snap_type) {
2138         case SnapToAThirtysecondBeat:
2139         case SnapToASixteenthBeat:
2140         case SnapToAEighthBeat:
2141         case SnapToAQuarterBeat:
2142         case SnapToAThirdBeat:
2143                 update_tempo_based_rulers ();
2144         default:
2145                 /* relax */
2146                 break;
2147     }
2148 }
2149
2150 void
2151 Editor::set_snap_mode (SnapMode mode)
2152 {
2153         snap_mode = mode;
2154         vector<string> txt = internationalize (snap_mode_strings);
2155         snap_mode_selector.set_active_text (txt[(int)mode]);
2156
2157         instant_save ();
2158 }
2159
2160 int
2161 Editor::set_state (const XMLNode& node)
2162 {
2163         const XMLProperty* prop;
2164         XMLNode* geometry;
2165         int x, y, xoff, yoff;
2166         Gdk::Geometry g;
2167
2168
2169         if ((geometry = find_named_node (node, "geometry")) == 0) {
2170
2171                 g.base_width = default_width;
2172                 g.base_height = default_height;
2173                 x = 1;
2174                 y = 1;
2175                 xoff = 0;
2176                 yoff = 21;
2177
2178         } else {
2179
2180                 g.base_width = atoi(geometry->property("x_size")->value());
2181                 g.base_height = atoi(geometry->property("y_size")->value());
2182                 x = atoi(geometry->property("x_pos")->value());
2183                 y = atoi(geometry->property("y_pos")->value());
2184                 xoff = atoi(geometry->property("x_off")->value());
2185                 yoff = atoi(geometry->property("y_off")->value());
2186         }
2187
2188         set_geometry_hints (vpacker, g, Gdk::HINT_BASE_SIZE);
2189         set_default_size (g.base_width, g.base_height);
2190         move (x, y);
2191
2192         if ((prop = node.property ("zoom-focus"))) {
2193                 set_zoom_focus ((ZoomFocus) atoi (prop->value()));
2194         }
2195
2196         if ((prop = node.property ("zoom"))) {
2197                 set_frames_per_unit (PBD::atof (prop->value()));
2198         }
2199
2200         if ((prop = node.property ("snap-to"))) {
2201                 set_snap_to ((SnapType) atoi (prop->value()));
2202         }
2203
2204         if ((prop = node.property ("snap-mode"))) {
2205                 set_snap_mode ((SnapMode) atoi (prop->value()));
2206         }
2207
2208         if ((prop = node.property ("mouse-mode"))) {
2209                 MouseMode m = str2mousemode(prop->value());
2210                 mouse_mode = MouseMode ((int) m + 1); /* lie, force mode switch */
2211                 set_mouse_mode (m, true);
2212         } else {
2213                 mouse_mode = MouseGain; /* lie, to force the mode switch */
2214                 set_mouse_mode (MouseObject, true);
2215         }
2216
2217         if ((prop = node.property ("show-waveforms"))) {
2218                 bool yn = (prop->value() == "yes");
2219                 _show_waveforms = !yn;
2220                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleWaveformVisibility"));
2221                 if (act) {
2222                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2223                         /* do it twice to force the change */
2224                         tact->set_active (!yn);
2225                         tact->set_active (yn);
2226                 }
2227         }
2228
2229         if ((prop = node.property ("show-waveforms-recording"))) {
2230                 bool yn = (prop->value() == "yes");
2231                 _show_waveforms_recording = !yn;
2232                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleWaveformsWhileRecording"));
2233                 if (act) {
2234                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2235                         /* do it twice to force the change */
2236                         tact->set_active (!yn);
2237                         tact->set_active (yn);
2238                 }
2239         }
2240         
2241         if ((prop = node.property ("show-measures"))) {
2242                 bool yn = (prop->value() == "yes");
2243                 _show_measures = !yn;
2244                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleMeasureVisibility"));
2245                 if (act) {
2246                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2247                         /* do it twice to force the change */
2248                         tact->set_active (!yn);
2249                         tact->set_active (yn);
2250                 }
2251         }
2252
2253         if ((prop = node.property ("follow-playhead"))) {
2254                 bool yn = (prop->value() == "yes");
2255                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
2256                 if (act) {
2257                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2258                         /* do it twice to force the change */
2259                         tact->set_active (!yn);
2260                         tact->set_active (yn);
2261                 }
2262         }
2263
2264
2265         if ((prop = node.property ("region-list-sort-type"))) {
2266                 region_list_sort_type = (Editing::RegionListSortType) -1; // force change 
2267                 reset_region_list_sort_type(str2regionlistsorttype(prop->value()));
2268         }
2269
2270         if ((prop = node.property ("xfades-visible"))) {
2271                 bool yn = (prop->value() == "yes");
2272                 _xfade_visibility = !yn;
2273                 // set_xfade_visibility (yn);
2274         }
2275
2276         if ((prop = node.property ("show-editor-mixer"))) {
2277
2278                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2279                 if (act) {
2280                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2281                         bool yn = (prop->value() == X_("yes"));
2282
2283                         /* do it twice to force the change */
2284                         
2285                         tact->set_active (!yn);
2286                         tact->set_active (yn);
2287                 }
2288         }
2289
2290         return 0;
2291 }
2292
2293 XMLNode&
2294 Editor::get_state ()
2295 {
2296         XMLNode* node = new XMLNode ("Editor");
2297         char buf[32];
2298
2299         if (is_realized()) {
2300                 Glib::RefPtr<Gdk::Window> win = get_window();
2301                 
2302                 int x, y, xoff, yoff, width, height;
2303                 win->get_root_origin(x, y);
2304                 win->get_position(xoff, yoff);
2305                 win->get_size(width, height);
2306                 
2307                 XMLNode* geometry = new XMLNode ("geometry");
2308                 char buf[32];
2309                 snprintf(buf, sizeof(buf), "%d", width);
2310                 geometry->add_property("x_size", string(buf));
2311                 snprintf(buf, sizeof(buf), "%d", height);
2312                 geometry->add_property("y_size", string(buf));
2313                 snprintf(buf, sizeof(buf), "%d", x);
2314                 geometry->add_property("x_pos", string(buf));
2315                 snprintf(buf, sizeof(buf), "%d", y);
2316                 geometry->add_property("y_pos", string(buf));
2317                 snprintf(buf, sizeof(buf), "%d", xoff);
2318                 geometry->add_property("x_off", string(buf));
2319                 snprintf(buf, sizeof(buf), "%d", yoff);
2320                 geometry->add_property("y_off", string(buf));
2321                 snprintf(buf,sizeof(buf), "%d",gtk_paned_get_position (static_cast<Paned*>(&edit_pane)->gobj()));
2322                 geometry->add_property("edit_pane_pos", string(buf));
2323
2324                 node->add_child_nocopy (*geometry);
2325         }
2326
2327         snprintf (buf, sizeof(buf), "%d", (int) zoom_focus);
2328         node->add_property ("zoom-focus", buf);
2329         snprintf (buf, sizeof(buf), "%f", frames_per_unit);
2330         node->add_property ("zoom", buf);
2331         snprintf (buf, sizeof(buf), "%d", (int) snap_type);
2332         node->add_property ("snap-to", buf);
2333         snprintf (buf, sizeof(buf), "%d", (int) snap_mode);
2334         node->add_property ("snap-mode", buf);
2335
2336         node->add_property ("show-waveforms", _show_waveforms ? "yes" : "no");
2337         node->add_property ("show-waveforms-recording", _show_waveforms_recording ? "yes" : "no");
2338         node->add_property ("show-measures", _show_measures ? "yes" : "no");
2339         node->add_property ("follow-playhead", _follow_playhead ? "yes" : "no");
2340         node->add_property ("xfades-visible", _xfade_visibility ? "yes" : "no");
2341         node->add_property ("region-list-sort-type", enum2str(region_list_sort_type));
2342         node->add_property ("mouse-mode", enum2str(mouse_mode));
2343         
2344         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2345         if (act) {
2346                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2347                 node->add_property (X_("show-editor-mixer"), tact->get_active() ? "yes" : "no");
2348         }
2349
2350         return *node;
2351 }
2352
2353
2354
2355 TimeAxisView *
2356 Editor::trackview_by_y_position (double y)
2357 {
2358         TrackViewList::iterator iter;
2359         TimeAxisView *tv;
2360
2361         for (iter = track_views.begin(); iter != track_views.end(); ++iter) {
2362
2363                 tv = *iter;
2364
2365                 if (tv->hidden()) {
2366                         continue;
2367                 }
2368
2369                 if (tv->y_position <= y && y < ((tv->y_position + tv->height + track_spacing))) {
2370                         return tv;
2371                 }
2372         }
2373
2374         return 0;
2375 }
2376
2377 void
2378 Editor::snap_to (jack_nframes_t& start, int32_t direction, bool for_mark)
2379 {
2380         Location* before = 0;
2381         Location* after = 0;
2382
2383         if (!session) {
2384                 return;
2385         }
2386
2387         const jack_nframes_t one_second = session->frame_rate();
2388         const jack_nframes_t one_minute = session->frame_rate() * 60;
2389
2390         jack_nframes_t presnap = start;
2391
2392         switch (snap_type) {
2393         case SnapToFrame:
2394                 break;
2395
2396         case SnapToCDFrame:
2397                 if (direction) {
2398                         start = (jack_nframes_t) ceil ((double) start / (one_second / 75)) * (one_second / 75);
2399                 } else {
2400                         start = (jack_nframes_t) floor ((double) start / (one_second / 75)) * (one_second / 75);
2401                 }
2402                 break;
2403         case SnapToSMPTEFrame:
2404                 if (direction) {
2405                         start = (jack_nframes_t) (ceil ((double) start / session->frames_per_smpte_frame()) * session->frames_per_smpte_frame());
2406                 } else {
2407                         start = (jack_nframes_t) (floor ((double) start / session->frames_per_smpte_frame()) *  session->frames_per_smpte_frame());
2408                 }
2409                 break;
2410
2411         case SnapToSMPTESeconds:
2412                 if (session->smpte_offset_negative())
2413                 {
2414                         start += session->smpte_offset ();
2415                 } else {
2416                         start -= session->smpte_offset ();
2417                 }    
2418                 if (direction > 0) {
2419                         start = (jack_nframes_t) ceil ((double) start / one_second) * one_second;
2420                 } else {
2421                         start = (jack_nframes_t) floor ((double) start / one_second) * one_second;
2422                 }
2423                 
2424                 if (session->smpte_offset_negative())
2425                 {
2426                         start -= session->smpte_offset ();
2427                 } else {
2428                         start += session->smpte_offset ();
2429                 }
2430                 break;
2431                 
2432         case SnapToSMPTEMinutes:
2433                 if (session->smpte_offset_negative())
2434                 {
2435                         start += session->smpte_offset ();
2436                 } else {
2437                         start -= session->smpte_offset ();
2438                 }
2439                 if (direction) {
2440                         start = (jack_nframes_t) ceil ((double) start / one_minute) * one_minute;
2441                 } else {
2442                         start = (jack_nframes_t) floor ((double) start / one_minute) * one_minute;
2443                 }
2444                 if (session->smpte_offset_negative())
2445                 {
2446                         start -= session->smpte_offset ();
2447                 } else {
2448                         start += session->smpte_offset ();
2449                 }
2450                 break;
2451                 
2452         case SnapToSeconds:
2453                 if (direction) {
2454                         start = (jack_nframes_t) ceil ((double) start / one_second) * one_second;
2455                 } else {
2456                         start = (jack_nframes_t) floor ((double) start / one_second) * one_second;
2457                 }
2458                 break;
2459                 
2460         case SnapToMinutes:
2461                 if (direction) {
2462                         start = (jack_nframes_t) ceil ((double) start / one_minute) * one_minute;
2463                 } else {
2464                         start = (jack_nframes_t) floor ((double) start / one_minute) * one_minute;
2465                 }
2466                 break;
2467
2468         case SnapToBar:
2469                 start = session->tempo_map().round_to_bar (start, direction);
2470                 break;
2471
2472         case SnapToBeat:
2473                 start = session->tempo_map().round_to_beat (start, direction);
2474                 break;
2475
2476         case SnapToAThirtysecondBeat:
2477                 start = session->tempo_map().round_to_beat_subdivision (start, 32);
2478                 break;
2479
2480         case SnapToASixteenthBeat:
2481                 start = session->tempo_map().round_to_beat_subdivision (start, 16);
2482                 break;
2483
2484         case SnapToAEighthBeat:
2485                 start = session->tempo_map().round_to_beat_subdivision (start, 8);
2486                 break;
2487
2488         case SnapToAQuarterBeat:
2489                 start = session->tempo_map().round_to_beat_subdivision (start, 4);
2490                 break;
2491
2492         case SnapToAThirdBeat:
2493                 start = session->tempo_map().round_to_beat_subdivision (start, 3);
2494                 break;
2495
2496         case SnapToEditCursor:
2497                 start = edit_cursor->current_frame;
2498                 break;
2499
2500         case SnapToMark:
2501                 if (for_mark) {
2502                         return;
2503                 }
2504
2505                 before = session->locations()->first_location_before (start);
2506                 after = session->locations()->first_location_after (start);
2507
2508                 if (direction < 0) {
2509                         if (before) {
2510                                 start = before->start();
2511                         } else {
2512                                 start = 0;
2513                         }
2514                 } else if (direction > 0) {
2515                         if (after) {
2516                                 start = after->start();
2517                         } else {
2518                                 start = session->current_end_frame();
2519                         }
2520                 } else {
2521                         if (before) {
2522                                 if (after) {
2523                                         /* find nearest of the two */
2524                                         if ((start - before->start()) < (after->start() - start)) {
2525                                                 start = before->start();
2526                                         } else {
2527                                                 start = after->start();
2528                                         }
2529                                 } else {
2530                                         start = before->start();
2531                                 }
2532                         } else if (after) {
2533                                 start = after->start();
2534                         } else {
2535                                 /* relax */
2536                         }
2537                 }
2538                 break;
2539
2540         case SnapToRegionStart:
2541         case SnapToRegionEnd:
2542         case SnapToRegionSync:
2543         case SnapToRegionBoundary:
2544                 if (!region_boundary_cache.empty()) {
2545                         vector<jack_nframes_t>::iterator i;
2546
2547                         if (direction > 0) {
2548                                 i = std::upper_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2549                         } else {
2550                                 i = std::lower_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2551                         }
2552                         
2553                         if (i != region_boundary_cache.end()) {
2554                                 start = *i;
2555                         } else {
2556                                 start = region_boundary_cache.back();
2557                         }
2558                 }
2559                 break;
2560         }
2561
2562         switch (snap_mode) {
2563         case SnapNormal:
2564                 return;                 
2565                 
2566         case SnapMagnetic:
2567                 
2568                 if (presnap > start) {
2569                         if (presnap > (start + unit_to_frame(snap_threshold))) {
2570                                 start = presnap;
2571                         }
2572                         
2573                 } else if (presnap < start) {
2574                         if (presnap < (start - unit_to_frame(snap_threshold))) {
2575                                 start = presnap;
2576                         }
2577                 }
2578                 
2579         default:
2580                 return;
2581                 
2582         }
2583 }
2584
2585 void
2586 Editor::setup_toolbar ()
2587 {
2588         string pixmap_path;
2589         vector<ToggleButton *> mouse_mode_buttons;
2590
2591         mouse_mode_buttons.push_back (&mouse_move_button);
2592         mouse_mode_buttons.push_back (&mouse_select_button);
2593         mouse_mode_buttons.push_back (&mouse_gain_button);
2594         mouse_mode_buttons.push_back (&mouse_zoom_button);
2595         mouse_mode_buttons.push_back (&mouse_timefx_button);
2596         mouse_mode_buttons.push_back (&mouse_audition_button);
2597         mouse_mode_button_set = new GroupedButtons (mouse_mode_buttons);
2598
2599         mouse_mode_button_table.set_homogeneous (true);
2600         mouse_mode_button_table.set_col_spacings (2);
2601         mouse_mode_button_table.set_row_spacings (2);
2602         mouse_mode_button_table.set_border_width (5);
2603
2604         mouse_mode_button_table.attach (mouse_move_button, 0, 1, 0, 1);
2605         mouse_mode_button_table.attach (mouse_select_button, 1, 2, 0, 1);
2606         mouse_mode_button_table.attach (mouse_zoom_button, 2, 3, 0, 1);
2607  
2608         mouse_mode_button_table.attach (mouse_gain_button, 0, 1, 1, 2);
2609         mouse_mode_button_table.attach (mouse_timefx_button, 1, 2, 1, 2);
2610         mouse_mode_button_table.attach (mouse_audition_button, 2, 3, 1, 2);
2611
2612         mouse_mode_tearoff = manage (new TearOff (mouse_mode_button_table));
2613         mouse_mode_tearoff->set_name ("MouseModeBase");
2614
2615         mouse_mode_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2616                                                   &mouse_mode_tearoff->tearoff_window()));
2617         mouse_mode_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2618                                                   &mouse_mode_tearoff->tearoff_window(), 1));
2619         mouse_mode_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2620                                                   &mouse_mode_tearoff->tearoff_window()));
2621         mouse_mode_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2622                                                    &mouse_mode_tearoff->tearoff_window(), 1));
2623
2624         mouse_move_button.set_name ("MouseModeButton");
2625         mouse_select_button.set_name ("MouseModeButton");
2626         mouse_gain_button.set_name ("MouseModeButton");
2627         mouse_zoom_button.set_name ("MouseModeButton");
2628         mouse_timefx_button.set_name ("MouseModeButton");
2629         mouse_audition_button.set_name ("MouseModeButton");
2630
2631         ARDOUR_UI::instance()->tooltips().set_tip (mouse_move_button, _("select/move objects"));
2632         ARDOUR_UI::instance()->tooltips().set_tip (mouse_select_button, _("select/move ranges"));
2633         ARDOUR_UI::instance()->tooltips().set_tip (mouse_gain_button, _("draw gain automation"));
2634         ARDOUR_UI::instance()->tooltips().set_tip (mouse_zoom_button, _("select zoom range"));
2635         ARDOUR_UI::instance()->tooltips().set_tip (mouse_timefx_button, _("stretch/shrink regions"));
2636         ARDOUR_UI::instance()->tooltips().set_tip (mouse_audition_button, _("listen to specific regions"));
2637
2638         mouse_move_button.unset_flags (CAN_FOCUS);
2639         mouse_select_button.unset_flags (CAN_FOCUS);
2640         mouse_gain_button.unset_flags (CAN_FOCUS);
2641         mouse_zoom_button.unset_flags (CAN_FOCUS);
2642         mouse_timefx_button.unset_flags (CAN_FOCUS);
2643         mouse_audition_button.unset_flags (CAN_FOCUS);
2644
2645         mouse_select_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseRange));
2646         mouse_select_button.signal_button_release_event().connect (mem_fun(*this, &Editor::mouse_select_button_release));
2647
2648         mouse_move_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseObject));
2649         mouse_gain_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseGain));
2650         mouse_zoom_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseZoom));
2651         mouse_timefx_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseTimeFX));
2652         mouse_audition_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseAudition));
2653
2654         // mouse_move_button.set_active (true);
2655
2656         /* automation control */
2657
2658         global_automation_button.set_name ("MouseModeButton");
2659         automation_mode_button.set_name ("MouseModeButton");
2660
2661         automation_box.set_spacing (2);
2662         automation_box.set_border_width (2);
2663         automation_box.pack_start (global_automation_button, false, false);
2664         automation_box.pack_start (automation_mode_button, false, false);
2665
2666         /* Edit mode */
2667
2668         edit_mode_label.set_name ("ToolBarLabel");
2669
2670         edit_mode_selector.set_name ("EditModeSelector");
2671
2672         edit_mode_box.set_spacing (3);
2673         edit_mode_box.set_border_width (3);
2674
2675         /* XXX another disgusting hack because of the way combo boxes size themselves */
2676
2677         const guint32 FUDGE = 20; // Combo's are stupid - they steal space from the entry for the button
2678         Gtkmm2ext::set_size_request_to_display_given_text (edit_mode_selector, "EdgtMode", 2+FUDGE, 10);
2679         set_popdown_strings (edit_mode_selector, internationalize (edit_mode_strings));
2680         edit_mode_box.pack_start (edit_mode_label, false, false);
2681         edit_mode_box.pack_start (edit_mode_selector, false, false);
2682
2683         edit_mode_selector.signal_changed().connect (mem_fun(*this, &Editor::edit_mode_selection_done));
2684
2685         /* Snap Type */
2686
2687         snap_type_label.set_name ("ToolBarLabel");
2688
2689         snap_type_selector.set_name ("SnapTypeSelector");
2690
2691         snap_type_box.set_spacing (3);
2692         snap_type_box.set_border_width (3);
2693
2694         /* XXX another disgusting hack because of the way combo boxes size themselves */
2695
2696         Gtkmm2ext::set_size_request_to_display_given_text (snap_type_selector, "SMPTE Seconds", 2+FUDGE, 10);
2697         set_popdown_strings (snap_type_selector, internationalize (snap_type_strings));
2698
2699         snap_type_box.pack_start (snap_type_label, false, false);
2700         snap_type_box.pack_start (snap_type_selector, false, false);
2701
2702         snap_type_selector.signal_changed().connect (mem_fun(*this, &Editor::snap_type_selection_done));
2703
2704         /* Snap mode, not snap type */
2705
2706         snap_mode_label.set_name ("ToolBarLabel");
2707
2708         snap_mode_selector.set_name ("SnapModeSelector");
2709         
2710         snap_mode_box.set_spacing (3);
2711         snap_mode_box.set_border_width (3);
2712
2713         Gtkmm2ext::set_size_request_to_display_given_text (snap_mode_selector, "SngpMode", 2+FUDGE, 10);
2714         set_popdown_strings (snap_mode_selector, internationalize (snap_mode_strings));
2715
2716         snap_mode_box.pack_start (snap_mode_label, false, false);
2717         snap_mode_box.pack_start (snap_mode_selector, false, false);
2718
2719         snap_mode_selector.signal_changed().connect (mem_fun(*this, &Editor::snap_mode_selection_done));
2720
2721         /* Zoom focus mode */
2722
2723         zoom_focus_label.set_name ("ToolBarLabel");
2724
2725         zoom_focus_selector.set_name ("ZoomFocusSelector");
2726
2727         zoom_focus_box.set_spacing (3);
2728         zoom_focus_box.set_border_width (3);
2729
2730         /* XXX another disgusting hack because of the way combo boxes size themselves */
2731
2732         Gtkmm2ext::set_size_request_to_display_given_text (zoom_focus_selector, "Edgt Cursor", 2+FUDGE, 10);
2733         set_popdown_strings (zoom_focus_selector, internationalize (zoom_focus_strings));
2734
2735         zoom_focus_box.pack_start (zoom_focus_label, false, false);
2736         zoom_focus_box.pack_start (zoom_focus_selector, false, false);
2737
2738         zoom_focus_selector.signal_changed().connect (mem_fun(*this, &Editor::zoom_focus_selection_done));
2739
2740         /* selection/cursor clocks */
2741
2742         toolbar_selection_cursor_label.set_name ("ToolBarLabel");
2743         selection_start_clock_label.set_name ("ToolBarLabel");
2744         selection_end_clock_label.set_name ("ToolBarLabel");
2745         edit_cursor_clock_label.set_name ("ToolBarLabel");
2746
2747         selection_start_clock_label.set_text (_("Start:"));
2748         selection_end_clock_label.set_text (_("End:"));
2749         edit_cursor_clock_label.set_text (_("Edit"));
2750
2751         /* the zoom in/out buttons are generally taller than the clocks, so
2752            put all the toolbar clocks into a size group with one of the 
2753            buttons to make them all equal height.
2754
2755            this also applies to the various toolbar combos
2756         */
2757
2758         RefPtr<SizeGroup> toolbar_clock_size_group = SizeGroup::create (SIZE_GROUP_VERTICAL);
2759         toolbar_clock_size_group->add_widget (zoom_out_button);
2760         toolbar_clock_size_group->add_widget (edit_cursor_clock);
2761         toolbar_clock_size_group->add_widget (zoom_range_clock);
2762         toolbar_clock_size_group->add_widget (nudge_clock);
2763         toolbar_clock_size_group->add_widget (edit_mode_selector);
2764         toolbar_clock_size_group->add_widget (snap_type_selector);
2765         toolbar_clock_size_group->add_widget (snap_mode_selector);
2766         toolbar_clock_size_group->add_widget (zoom_focus_selector);
2767
2768         HBox* edit_clock_hbox = manage (new HBox());
2769         VBox* edit_clock_vbox = manage (new VBox());
2770
2771         edit_clock_hbox->pack_start (edit_cursor_clock, false, false);
2772
2773         edit_clock_vbox->set_spacing (3);
2774         edit_clock_vbox->set_border_width (3);
2775         edit_clock_vbox->pack_start (edit_cursor_clock_label, false, false);
2776         edit_clock_vbox->pack_start (*edit_clock_hbox, false, false);
2777
2778         HBox* hbox = new HBox;
2779
2780         hbox->pack_start (*edit_clock_vbox, false, false);
2781         hbox->pack_start (zoom_indicator_vbox, false, false); 
2782         hbox->pack_start (zoom_focus_box, false, false);
2783         hbox->pack_start (snap_type_box, false, false);
2784         hbox->pack_start (snap_mode_box, false, false);
2785         hbox->pack_start (edit_mode_box, false, false);
2786
2787         VBox *vbox = manage (new VBox);
2788
2789         vbox->set_spacing (3);
2790         vbox->set_border_width (3);
2791
2792         HBox *nbox = manage (new HBox);
2793         
2794         nudge_forward_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::nudge_forward), false));
2795         nudge_backward_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::nudge_backward), false));
2796
2797         nbox->pack_start (nudge_backward_button, false, false);
2798         nbox->pack_start (nudge_forward_button, false, false);
2799         nbox->pack_start (nudge_clock, false, false, 5);
2800
2801         nudge_label.set_name ("ToolBarLabel");
2802
2803         vbox->pack_start (nudge_label, false, false);
2804         vbox->pack_start (*nbox, false, false);
2805
2806         hbox->pack_start (*vbox, false, false);
2807
2808         hbox->show_all ();
2809
2810         tools_tearoff = new TearOff (*hbox);
2811         tools_tearoff->set_name ("MouseModeBase");
2812
2813         tools_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2814                                              &tools_tearoff->tearoff_window()));
2815         tools_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2816                                              &tools_tearoff->tearoff_window(), 0));
2817         tools_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2818                                              &tools_tearoff->tearoff_window()));
2819         tools_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2820                                               &tools_tearoff->tearoff_window(), 0));
2821
2822         toolbar_hbox.set_spacing (8);
2823         toolbar_hbox.set_border_width (2);
2824
2825         toolbar_hbox.pack_start (*tools_tearoff, false, false);
2826         toolbar_hbox.pack_start (*mouse_mode_tearoff, false, false);
2827         
2828         toolbar_base.set_name ("ToolBarBase");
2829         toolbar_base.add (toolbar_hbox);
2830
2831         toolbar_frame.set_shadow_type (SHADOW_OUT);
2832         toolbar_frame.set_name ("BaseFrame");
2833         toolbar_frame.add (toolbar_base);
2834 }
2835
2836 int
2837 Editor::convert_drop_to_paths (vector<ustring>& paths, 
2838                                const RefPtr<Gdk::DragContext>& context,
2839                                gint                x,
2840                                gint                y,
2841                                const SelectionData& data,
2842                                guint               info,
2843                                guint               time)                               
2844
2845 {       
2846         if (session == 0) {
2847                 return -1;
2848         }
2849
2850         vector<ustring> uris = data.get_uris();
2851
2852         if (uris.empty()) {
2853                 
2854                 /* This is seriously fucked up. Nautilus doesn't say that its URI lists
2855                    are actually URI lists. So do it by hand.
2856                 */
2857
2858                 if (data.get_target() != "text/plain") {
2859                         return -1;
2860                 }
2861   
2862                 /* Parse the "uri-list" format that Nautilus provides, 
2863                    where each pathname is delimited by \r\n
2864                 */
2865         
2866                 const char* p = data.get_text().c_str();
2867                 const char* q;
2868
2869                 while (p)
2870                 {
2871                         if (*p != '#')
2872                         {
2873                                 while (g_ascii_isspace (*p))
2874                                         p++;
2875                                 
2876                                 q = p;
2877                                 while (*q && (*q != '\n') && (*q != '\r'))
2878                                         q++;
2879                                 
2880                                 if (q > p)
2881                                 {
2882                                         q--;
2883                                         while (q > p && g_ascii_isspace (*q))
2884                                                 q--;
2885                                         
2886                                         if (q > p)
2887                                         {
2888                                                 uris.push_back (ustring (p, q - p + 1));
2889                                         }
2890                                 }
2891                         }
2892                         p = strchr (p, '\n');
2893                         if (p)
2894                                 p++;
2895                 }
2896
2897                 if (uris.empty()) {
2898                         return -1;
2899                 }
2900         }
2901         
2902         for (vector<ustring>::iterator i = uris.begin(); i != uris.end(); ++i) {
2903                 if ((*i).substr (0,7) == "file://") {
2904                         string p = *i;
2905                         PBD::url_decode (p);
2906                         paths.push_back (p.substr (7));
2907                 }
2908         }
2909
2910         return 0;
2911 }
2912
2913 void
2914 Editor::new_tempo_section ()
2915
2916 {
2917 }
2918
2919 void
2920 Editor::map_transport_state ()
2921 {
2922         ENSURE_GUI_THREAD (mem_fun(*this, &Editor::map_transport_state));
2923
2924         if (session->transport_stopped()) {
2925                 have_pending_keyboard_selection = false;
2926         }
2927 }
2928
2929 /* UNDO/REDO */
2930
2931 Editor::State::State ()
2932 {
2933         selection = new Selection;
2934 }
2935
2936 Editor::State::~State ()
2937 {
2938         delete selection;
2939 }
2940
2941 UndoAction
2942 Editor::get_memento () const
2943 {
2944         State *state = new State;
2945
2946         store_state (*state);
2947         return bind (mem_fun (*(const_cast<Editor*>(this)), &Editor::restore_state), state);
2948 }
2949
2950 void
2951 Editor::store_state (State& state) const
2952 {
2953         *state.selection = *selection;
2954 }
2955
2956 void
2957 Editor::restore_state (State *state)
2958 {
2959         if (*selection == *state->selection) {
2960                 return;
2961         }
2962
2963         *selection = *state->selection;
2964         time_selection_changed ();
2965         region_selection_changed ();   
2966
2967         /* XXX other selection change handlers? */
2968 }
2969
2970 void
2971 Editor::begin_reversible_command (string name)
2972 {
2973         if (session) {
2974                 before = &get_state();
2975                 session->begin_reversible_command (name);
2976         }
2977 }
2978
2979 void
2980 Editor::commit_reversible_command ()
2981 {
2982         if (session) {
2983                 session->commit_reversible_command (new MementoCommand<Editor>(*this, *before, get_state()));
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