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