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