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