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