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