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