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