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