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