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