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