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