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