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