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