(1) use select next/previous row functions for tab/shift-tab navigation in region...
[ardour.git] / gtk2_ardour / editor.cc
1 /*
2     Copyright (C) 2000-2009 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 #define __STDC_LIMIT_MACROS 1
23 #include <stdint.h>
24 #include <unistd.h>
25 #include <cstdlib>
26 #include <cmath>
27 #include <string>
28 #include <algorithm>
29 #include <map>
30
31 #include "ardour_ui.h"
32 /*
33  * ardour_ui.h include was moved to the top of the list
34  * due to a conflicting definition of 'Style' between
35  * Apple's MacTypes.h and BarController.
36  */
37
38 #include <boost/none.hpp>
39
40 #include <sigc++/bind.h>
41
42 #include "pbd/convert.h"
43 #include "pbd/error.h"
44 #include "pbd/enumwriter.h"
45 #include "pbd/memento_command.h"
46 #include "pbd/unknown_type.h"
47
48 #include <glibmm/miscutils.h>
49 #include <gtkmm/image.h>
50 #include <gdkmm/color.h>
51 #include <gdkmm/bitmap.h>
52
53 #include <gtkmm2ext/grouped_buttons.h>
54 #include <gtkmm2ext/gtk_ui.h>
55 #include <gtkmm2ext/tearoff.h>
56 #include <gtkmm2ext/utils.h>
57 #include <gtkmm2ext/window_title.h>
58 #include <gtkmm2ext/choice.h>
59 #include <gtkmm2ext/cell_renderer_pixbuf_toggle.h>
60
61 #include "ardour/audio_diskstream.h"
62 #include "ardour/audio_track.h"
63 #include "ardour/audioplaylist.h"
64 #include "ardour/audioregion.h"
65 #include "ardour/location.h"
66 #include "ardour/midi_region.h"
67 #include "ardour/plugin_manager.h"
68 #include "ardour/profile.h"
69 #include "ardour/route_group.h"
70 #include "ardour/session_directory.h"
71 #include "ardour/session_route.h"
72 #include "ardour/session_state_utils.h"
73 #include "ardour/tempo.h"
74 #include "ardour/utils.h"
75 #include "ardour/session_playlists.h"
76 #include "ardour/audioengine.h"
77
78 #include "control_protocol/control_protocol.h"
79
80 #include "editor.h"
81 #include "keyboard.h"
82 #include "marker.h"
83 #include "playlist_selector.h"
84 #include "audio_region_view.h"
85 #include "rgb_macros.h"
86 #include "selection.h"
87 #include "audio_streamview.h"
88 #include "time_axis_view.h"
89 #include "audio_time_axis.h"
90 #include "utils.h"
91 #include "crossfade_view.h"
92 #include "canvas-noevent-text.h"
93 #include "editing.h"
94 #include "public_editor.h"
95 #include "crossfade_edit.h"
96 #include "canvas_impl.h"
97 #include "actions.h"
98 #include "sfdb_ui.h"
99 #include "gui_thread.h"
100 #include "simpleline.h"
101 #include "rhythm_ferret.h"
102 #include "actions.h"
103 #include "tempo_lines.h"
104 #include "analysis_window.h"
105 #include "bundle_manager.h"
106 #include "global_port_matrix.h"
107 #include "editor_drag.h"
108 #include "editor_group_tabs.h"
109 #include "automation_time_axis.h"
110 #include "editor_routes.h"
111 #include "midi_time_axis.h"
112 #include "mixer_strip.h"
113 #include "editor_route_groups.h"
114 #include "editor_regions.h"
115 #include "editor_locations.h"
116 #include "editor_snapshots.h"
117 #include "editor_summary.h"
118 #include "region_layering_order_editor.h"
119
120 #include "i18n.h"
121
122 #ifdef WITH_CMT
123 #include "imageframe_socket_handler.h"
124 #endif
125
126 using namespace std;
127 using namespace ARDOUR;
128 using namespace PBD;
129 using namespace Gtk;
130 using namespace Glib;
131 using namespace Gtkmm2ext;
132 using namespace Editing;
133
134 using PBD::internationalize;
135 using PBD::atoi;
136 using Gtkmm2ext::Keyboard;
137
138 const double Editor::timebar_height = 15.0;
139
140 #include "editor_xpms"
141
142 static const gchar *_snap_type_strings[] = {
143         N_("CD Frames"),
144         N_("Timecode Frames"),
145         N_("Timecode Seconds"),
146         N_("Timecode Minutes"),
147         N_("Seconds"),
148         N_("Minutes"),
149         N_("Beats/32"),
150         N_("Beats/28"),
151         N_("Beats/24"),
152         N_("Beats/20"),
153         N_("Beats/16"),
154         N_("Beats/14"),
155         N_("Beats/12"),
156         N_("Beats/10"),
157         N_("Beats/8"),
158         N_("Beats/7"),
159         N_("Beats/6"),
160         N_("Beats/5"),
161         N_("Beats/4"),
162         N_("Beats/3"),
163         N_("Beats/2"),
164         N_("Beats"),
165         N_("Bars"),
166         N_("Marks"),
167         N_("Region starts"),
168         N_("Region ends"),
169         N_("Region syncs"),
170         N_("Region bounds"),
171         0
172 };
173
174 static const gchar *_snap_mode_strings[] = {
175         N_("No Grid"),
176         N_("Grid"),
177         N_("Magnetic"),
178         0
179 };
180
181 static const gchar *_edit_point_strings[] = {
182         N_("Playhead"),
183         N_("Marker"),
184         N_("Mouse"),
185         0
186 };
187
188 static const gchar *_zoom_focus_strings[] = {
189         N_("Left"),
190         N_("Right"),
191         N_("Center"),
192         N_("Playhead"),
193         N_("Mouse"),
194         N_("Edit point"),
195         0
196 };
197
198 #ifdef USE_RUBBERBAND
199 static const gchar *_rb_opt_strings[] = {
200         N_("Mushy"),
201         N_("Smooth"),
202         N_("Balanced multitimbral mixture"),
203         N_("Unpitched percussion with stable notes"),
204         N_("Crisp monophonic instrumental"),
205         N_("Unpitched solo percussion"),
206         N_("Resample without preserving pitch"),
207         0
208 };
209 #endif
210
211 /* Soundfile  drag-n-drop */
212
213 Gdk::Cursor* Editor::cross_hair_cursor = 0;
214 Gdk::Cursor* Editor::selector_cursor = 0;
215 Gdk::Cursor* Editor::trimmer_cursor = 0;
216 Gdk::Cursor* Editor::left_side_trim_cursor = 0;
217 Gdk::Cursor* Editor::right_side_trim_cursor = 0;
218 Gdk::Cursor* Editor::fade_in_cursor = 0;
219 Gdk::Cursor* Editor::fade_out_cursor = 0;
220 Gdk::Cursor* Editor::grabber_cursor = 0;
221 Gdk::Cursor* Editor::grabber_note_cursor = 0;
222 Gdk::Cursor* Editor::grabber_edit_point_cursor = 0;
223 Gdk::Cursor* Editor::zoom_in_cursor = 0;
224 Gdk::Cursor* Editor::zoom_out_cursor = 0;
225 Gdk::Cursor* Editor::time_fx_cursor = 0;
226 Gdk::Cursor* Editor::fader_cursor = 0;
227 Gdk::Cursor* Editor::speaker_cursor = 0;
228 Gdk::Cursor* Editor::midi_pencil_cursor = 0;
229 Gdk::Cursor* Editor::midi_select_cursor = 0;
230 Gdk::Cursor* Editor::midi_resize_cursor = 0;
231 Gdk::Cursor* Editor::midi_erase_cursor = 0;
232 Gdk::Cursor* Editor::wait_cursor = 0;
233 Gdk::Cursor* Editor::timebar_cursor = 0;
234 Gdk::Cursor* Editor::transparent_cursor = 0;
235 Gdk::Cursor* Editor::up_down_cursor = 0;
236
237 void
238 show_me_the_size (Requisition* r, const char* what)
239 {
240         cerr << "size of " << what << " = " << r->width << " x " << r->height << endl;
241 }
242
243 #ifdef GTKOSX
244 static void
245 pane_size_watcher (Paned* pane)
246 {
247        /* if the handle of a pane vanishes into (at least) the tabs of a notebook,
248           it is no longer accessible. so stop that. this doesn't happen on X11,
249           just the quartz backend.
250
251           ugh.
252        */
253
254        int max_width_of_lhs = GTK_WIDGET(pane->gobj())->allocation.width - 25;
255
256        gint pos = pane->get_position ();
257
258        if (pos > max_width_of_lhs) {
259                pane->set_position (max_width_of_lhs);
260        }
261 }
262 #endif
263
264 Editor::Editor ()
265         : _join_object_range_state (JOIN_OBJECT_RANGE_NONE)
266
267           /* time display buttons */
268         , minsec_label (_("Mins:Secs"))
269         , bbt_label (_("Bars:Beats"))
270         , timecode_label (_("Timecode"))
271         , frame_label (_("Samples"))
272         , tempo_label (_("Tempo"))
273         , meter_label (_("Meter"))
274         , mark_label (_("Location Markers"))
275         , range_mark_label (_("Range Markers"))
276         , transport_mark_label (_("Loop/Punch Ranges"))
277         , cd_mark_label (_("CD Markers"))
278         , edit_packer (4, 4, true)
279
280           /* the values here don't matter: layout widgets
281              reset them as needed.
282           */
283
284         , vertical_adjustment (0.0, 0.0, 10.0, 400.0)
285
286           /* tool bar related */
287
288         , zoom_range_clock (X_("zoomrange"), false, X_("ZoomRangeClock"), true, false, true)
289
290         , toolbar_selection_clock_table (2,3)
291
292         , automation_mode_button (_("mode"))
293         , global_automation_button (_("automation"))
294
295         , midi_panic_button (_("Panic"))
296
297 #ifdef WITH_CMT
298         , image_socket_listener(0)
299 #endif
300
301           /* nudge */
302
303         , nudge_clock (X_("nudge"), false, X_("NudgeClock"), true, false, true)
304         , meters_running(false)
305         , _pending_locate_request (false)
306         , _pending_initial_locate (false)
307         , _last_cut_copy_source_track (0)
308
309         , _region_selection_change_updates_region_list (true)
310 {
311         constructed = false;
312
313         /* we are a singleton */
314
315         PublicEditor::_instance = this;
316
317         _have_idled = false;
318
319         selection = new Selection (this);
320         cut_buffer = new Selection (this);
321
322         clicked_regionview = 0;
323         clicked_axisview = 0;
324         clicked_routeview = 0;
325         clicked_crossfadeview = 0;
326         clicked_control_point = 0;
327         last_update_frame = 0;
328         pre_press_cursor = 0;
329         _drags = new DragManager (this);
330         current_mixer_strip = 0;
331         current_bbt_points = 0;
332         tempo_lines = 0;
333
334         snap_type_strings =  I18N (_snap_type_strings);
335         snap_mode_strings =  I18N (_snap_mode_strings);
336         zoom_focus_strings = I18N (_zoom_focus_strings);
337         edit_point_strings = I18N (_edit_point_strings);
338 #ifdef USE_RUBBERBAND
339         rb_opt_strings = I18N (_rb_opt_strings);
340         rb_current_opt = 4;
341 #endif
342
343         snap_threshold = 5.0;
344         bbt_beat_subdivision = 4;
345         _canvas_width = 0;
346         _canvas_height = 0;
347         last_autoscroll_x = 0;
348         last_autoscroll_y = 0;
349         autoscroll_active = false;
350         autoscroll_timeout_tag = -1;
351         logo_item = 0;
352
353         analysis_window = 0;
354
355         current_interthread_info = 0;
356         _show_measures = true;
357         show_gain_after_trim = false;
358         verbose_cursor_on = true;
359         last_item_entered = 0;
360
361         have_pending_keyboard_selection = false;
362         _follow_playhead = true;
363         _stationary_playhead = false;
364         _xfade_visibility = true;
365         editor_ruler_menu = 0;
366         no_ruler_shown_update = false;
367         marker_menu = 0;
368         session_range_marker_menu = 0;
369         range_marker_menu = 0;
370         marker_menu_item = 0;
371         tempo_or_meter_marker_menu = 0;
372         transport_marker_menu = 0;
373         new_transport_marker_menu = 0;
374         editor_mixer_strip_width = Wide;
375         show_editor_mixer_when_tracks_arrive = false;
376         region_edit_menu_split_multichannel_item = 0;
377         region_edit_menu_split_item = 0;
378         temp_location = 0;
379         leftmost_frame = 0;
380         current_stepping_trackview = 0;
381         entered_track = 0;
382         entered_regionview = 0;
383         entered_marker = 0;
384         clear_entered_track = false;
385         current_timefx = 0;
386         playhead_cursor = 0;
387         button_release_can_deselect = true;
388         _dragging_playhead = false;
389         _dragging_edit_point = false;
390         select_new_marker = false;
391         rhythm_ferret = 0;
392         layering_order_editor = 0;
393         _bundle_manager = 0;
394         no_save_visual = false;
395         resize_idle_id = -1;
396
397         scrubbing_direction = 0;
398
399         sfbrowser = 0;
400
401         location_marker_color = ARDOUR_UI::config()->canvasvar_LocationMarker.get();
402         location_range_color = ARDOUR_UI::config()->canvasvar_LocationRange.get();
403         location_cd_marker_color = ARDOUR_UI::config()->canvasvar_LocationCDMarker.get();
404         location_loop_color = ARDOUR_UI::config()->canvasvar_LocationLoop.get();
405         location_punch_color = ARDOUR_UI::config()->canvasvar_LocationPunch.get();
406
407         _edit_point = EditAtMouse;
408         _internal_editing = false;
409         current_canvas_cursor = 0;
410
411         frames_per_unit = 2048; /* too early to use reset_zoom () */
412
413         _scroll_callbacks = 0;
414
415         zoom_focus = ZoomFocusLeft;
416         set_zoom_focus (ZoomFocusLeft);
417         zoom_range_clock.ValueChanged.connect (sigc::mem_fun(*this, &Editor::zoom_adjustment_changed));
418
419         bbt_label.set_name ("EditorTimeButton");
420         bbt_label.set_size_request (-1, (int)timebar_height);
421         bbt_label.set_alignment (1.0, 0.5);
422         bbt_label.set_padding (5,0);
423         bbt_label.hide ();
424         bbt_label.set_no_show_all();
425         minsec_label.set_name ("EditorTimeButton");
426         minsec_label.set_size_request (-1, (int)timebar_height);
427         minsec_label.set_alignment (1.0, 0.5);
428         minsec_label.set_padding (5,0);
429         minsec_label.hide ();
430         minsec_label.set_no_show_all();
431         timecode_label.set_name ("EditorTimeButton");
432         timecode_label.set_size_request (-1, (int)timebar_height);
433         timecode_label.set_alignment (1.0, 0.5);
434         timecode_label.set_padding (5,0);
435         timecode_label.hide ();
436         timecode_label.set_no_show_all();
437         frame_label.set_name ("EditorTimeButton");
438         frame_label.set_size_request (-1, (int)timebar_height);
439         frame_label.set_alignment (1.0, 0.5);
440         frame_label.set_padding (5,0);
441         frame_label.hide ();
442         frame_label.set_no_show_all();
443
444         tempo_label.set_name ("EditorTimeButton");
445         tempo_label.set_size_request (-1, (int)timebar_height);
446         tempo_label.set_alignment (1.0, 0.5);
447         tempo_label.set_padding (5,0);
448         tempo_label.hide();
449         tempo_label.set_no_show_all();
450         meter_label.set_name ("EditorTimeButton");
451         meter_label.set_size_request (-1, (int)timebar_height);
452         meter_label.set_alignment (1.0, 0.5);
453         meter_label.set_padding (5,0);
454         meter_label.hide();
455         meter_label.set_no_show_all();
456         mark_label.set_name ("EditorTimeButton");
457         mark_label.set_size_request (-1, (int)timebar_height);
458         mark_label.set_alignment (1.0, 0.5);
459         mark_label.set_padding (5,0);
460         mark_label.hide();
461         mark_label.set_no_show_all();
462         cd_mark_label.set_name ("EditorTimeButton");
463         cd_mark_label.set_size_request (-1, (int)timebar_height);
464         cd_mark_label.set_alignment (1.0, 0.5);
465         cd_mark_label.set_padding (5,0);
466         cd_mark_label.hide();
467         cd_mark_label.set_no_show_all();
468         range_mark_label.set_name ("EditorTimeButton");
469         range_mark_label.set_size_request (-1, (int)timebar_height);
470         range_mark_label.set_alignment (1.0, 0.5);
471         range_mark_label.set_padding (5,0);
472         range_mark_label.hide();
473         range_mark_label.set_no_show_all();
474         transport_mark_label.set_name ("EditorTimeButton");
475         transport_mark_label.set_size_request (-1, (int)timebar_height);
476         transport_mark_label.set_alignment (1.0, 0.5);
477         transport_mark_label.set_padding (5,0);
478         transport_mark_label.hide();
479         transport_mark_label.set_no_show_all();
480
481         initialize_rulers ();
482         initialize_canvas ();
483         _summary = new EditorSummary (this);
484
485         selection->TimeChanged.connect (sigc::mem_fun(*this, &Editor::time_selection_changed));
486         selection->TracksChanged.connect (sigc::mem_fun(*this, &Editor::track_selection_changed));
487         editor_regions_selection_changed_connection = selection->RegionsChanged.connect (sigc::mem_fun(*this, &Editor::region_selection_changed));
488         selection->PointsChanged.connect (sigc::mem_fun(*this, &Editor::point_selection_changed));
489         selection->MarkersChanged.connect (sigc::mem_fun(*this, &Editor::marker_selection_changed));
490
491         edit_controls_vbox.set_spacing (0);
492         vertical_adjustment.signal_value_changed().connect (sigc::mem_fun(*this, &Editor::tie_vertical_scrolling), true);
493         track_canvas->signal_map_event().connect (sigc::mem_fun (*this, &Editor::track_canvas_map_handler));
494
495         HBox* h = manage (new HBox);
496         _group_tabs = new EditorGroupTabs (this);
497         h->pack_start (*_group_tabs, PACK_SHRINK);
498         h->pack_start (edit_controls_vbox);
499         controls_layout.add (*h);
500
501         controls_layout.set_name ("EditControlsBase");
502         controls_layout.add_events (Gdk::SCROLL_MASK);
503         controls_layout.signal_scroll_event().connect (sigc::mem_fun(*this, &Editor::control_layout_scroll), false);
504
505         controls_layout.add_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK|Gdk::ENTER_NOTIFY_MASK|Gdk::LEAVE_NOTIFY_MASK);
506         controls_layout.signal_button_release_event().connect (sigc::mem_fun(*this, &Editor::edit_controls_button_release));
507         controls_layout_size_request_connection = controls_layout.signal_size_request().connect (sigc::mem_fun (*this, &Editor::controls_layout_size_request));
508
509         build_cursors ();
510
511         ArdourCanvas::Canvas* time_pad = manage(new ArdourCanvas::Canvas());
512         ArdourCanvas::SimpleLine* pad_line_1 = manage(new ArdourCanvas::SimpleLine(*time_pad->root(),
513                         0.0, 1.0, 100.0, 1.0));
514         pad_line_1->property_color_rgba() = 0xFF0000FF;
515         pad_line_1->show();
516         time_pad->show();
517
518         time_canvas_vbox.set_size_request (-1, (int)(timebar_height * visible_timebars) + 2);
519         time_canvas_vbox.set_size_request (-1, -1);
520
521         ruler_label_event_box.add (ruler_label_vbox);
522         ruler_label_event_box.set_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK);
523         ruler_label_event_box.signal_button_release_event().connect (sigc::mem_fun(*this, &Editor::ruler_label_button_release));
524
525         time_button_event_box.add (time_button_vbox);
526         time_button_event_box.set_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK);
527         time_button_event_box.signal_button_release_event().connect (sigc::mem_fun(*this, &Editor::ruler_label_button_release));
528
529         /* these enable us to have a dedicated window (for cursor setting, etc.)
530            for the canvas areas.
531         */
532
533         track_canvas_event_box.add (*track_canvas);
534
535         time_canvas_event_box.add (time_canvas_vbox);
536         time_canvas_event_box.set_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK|Gdk::POINTER_MOTION_MASK);
537
538         edit_packer.set_col_spacings (0);
539         edit_packer.set_row_spacings (0);
540         edit_packer.set_homogeneous (false);
541         edit_packer.set_border_width (0);
542         edit_packer.set_name ("EditorWindow");
543
544         /* labels for the rulers */
545         edit_packer.attach (ruler_label_event_box,   1, 2, 0, 1,    FILL,        SHRINK, 0, 0);
546         /* labels for the marker "tracks" */
547         edit_packer.attach (time_button_event_box,   1, 2, 1, 2,    FILL,        SHRINK, 0, 0);
548         /* the rulers */
549         edit_packer.attach (time_canvas_event_box,   2, 3, 0, 1,    FILL|EXPAND, FILL, 0, 0);
550         /* track controls */
551         edit_packer.attach (controls_layout,         0, 2, 2, 3,    FILL,        FILL|EXPAND, 0, 0);
552         /* main canvas */
553         edit_packer.attach (track_canvas_event_box,  2, 3, 1, 3,    FILL|EXPAND, FILL|EXPAND, 0, 0);
554
555         bottom_hbox.set_border_width (2);
556         bottom_hbox.set_spacing (3);
557
558         _route_groups = new EditorRouteGroups (this);
559         _routes = new EditorRoutes (this);
560         _regions = new EditorRegions (this);
561         _snapshots = new EditorSnapshots (this);
562         _locations = new EditorLocations (this);
563
564         Gtk::Label* nlabel;
565
566         nlabel = manage (new Label (_("Regions")));
567         nlabel->set_angle (-90);
568         the_notebook.append_page (_regions->widget (), *nlabel);
569         nlabel = manage (new Label (_("Tracks & Busses")));
570         nlabel->set_angle (-90);
571         the_notebook.append_page (_routes->widget (), *nlabel);
572         nlabel = manage (new Label (_("Snapshots")));
573         nlabel->set_angle (-90);
574         the_notebook.append_page (_snapshots->widget (), *nlabel);
575         nlabel = manage (new Label (_("Route Groups")));
576         nlabel->set_angle (-90);
577         the_notebook.append_page (_route_groups->widget (), *nlabel);
578         nlabel = manage (new Label (_("Ranges & Marks")));
579         nlabel->set_angle (-90);
580         the_notebook.append_page (_locations->widget (), *nlabel);
581
582         the_notebook.set_show_tabs (true);
583         the_notebook.set_scrollable (true);
584         the_notebook.popup_disable ();
585         the_notebook.set_tab_pos (Gtk::POS_RIGHT);
586         the_notebook.show_all ();
587         
588         post_maximal_editor_width = 0;
589         post_maximal_horizontal_pane_position = 0;
590         post_maximal_editor_height = 0;
591         post_maximal_vertical_pane_position = 0;
592
593         editor_summary_pane.pack1(edit_packer);
594
595         Button* summary_arrows_left_left = manage (new Button);
596         summary_arrows_left_left->add (*manage (new Arrow (ARROW_LEFT, SHADOW_NONE)));
597         summary_arrows_left_left->signal_pressed().connect (sigc::hide_return (sigc::mem_fun (*this, &Editor::horizontal_scroll_left_press)));
598         summary_arrows_left_left->signal_released().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_left_release));
599         Button* summary_arrows_left_right = manage (new Button);
600         summary_arrows_left_right->add (*manage (new Arrow (ARROW_RIGHT, SHADOW_NONE)));
601         summary_arrows_left_right->signal_pressed().connect (sigc::hide_return (sigc::mem_fun (*this, &Editor::horizontal_scroll_right_press)));
602         summary_arrows_left_right->signal_released().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_right_release));
603         VBox* summary_arrows_left = manage (new VBox);
604         summary_arrows_left->pack_start (*summary_arrows_left_left);
605         summary_arrows_left->pack_start (*summary_arrows_left_right);
606
607         Button* summary_arrows_right_left = manage (new Button);
608         summary_arrows_right_left->add (*manage (new Arrow (ARROW_LEFT, SHADOW_NONE)));
609         summary_arrows_right_left->signal_pressed().connect (sigc::hide_return (sigc::mem_fun (*this, &Editor::horizontal_scroll_left_press)));
610         summary_arrows_right_left->signal_released().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_left_release));
611         Button* summary_arrows_right_right = manage (new Button);
612         summary_arrows_right_right->add (*manage (new Arrow (ARROW_RIGHT, SHADOW_NONE)));
613         summary_arrows_right_right->signal_pressed().connect (sigc::hide_return (sigc::mem_fun (*this, &Editor::horizontal_scroll_right_press)));
614         summary_arrows_right_right->signal_released().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_right_release));
615         VBox* summary_arrows_right = manage (new VBox);
616         summary_arrows_right->pack_start (*summary_arrows_right_left);
617         summary_arrows_right->pack_start (*summary_arrows_right_right);
618
619         Frame* summary_frame = manage (new Frame);
620         summary_frame->set_shadow_type (Gtk::SHADOW_ETCHED_IN);
621         summary_frame->add (*_summary);
622         summary_frame->show ();
623
624         _summary_hbox.pack_start (*summary_arrows_left, false, false);
625         _summary_hbox.pack_start (*summary_frame, true, true);
626         _summary_hbox.pack_start (*summary_arrows_right, false, false);
627         
628         editor_summary_pane.pack2 (_summary_hbox);
629
630         edit_pane.pack1 (editor_summary_pane, true, true);
631         edit_pane.pack2 (the_notebook, false, true);
632
633         editor_summary_pane.signal_size_allocate().connect (sigc::bind (sigc::mem_fun (*this, &Editor::pane_allocation_handler), static_cast<Paned*> (&editor_summary_pane)));
634
635         /* XXX: editor_summary_pane might need similar special OS X treatment to the edit_pane */
636
637         edit_pane.signal_size_allocate().connect (sigc::bind (sigc::mem_fun(*this, &Editor::pane_allocation_handler), static_cast<Paned*> (&edit_pane)));
638 #ifdef GTKOSX
639         Glib::PropertyProxy<int> proxy = edit_pane.property_position();
640         proxy.signal_changed().connect (bind (sigc::ptr_fun (pane_size_watcher), static_cast<Paned*> (&edit_pane)));
641 #endif
642         top_hbox.pack_start (toolbar_frame, false, true);
643
644         HBox *hbox = manage (new HBox);
645         hbox->pack_start (edit_pane, true, true);
646
647         global_vpacker.pack_start (top_hbox, false, false);
648         global_vpacker.pack_start (*hbox, true, true);
649
650         global_hpacker.pack_start (global_vpacker, true, true);
651
652         set_name ("EditorWindow");
653         add_accel_group (ActionManager::ui_manager->get_accel_group());
654
655         status_bar_hpacker.show ();
656
657         vpacker.pack_end (status_bar_hpacker, false, false);
658         vpacker.pack_end (global_hpacker, true, true);
659
660         /* register actions now so that set_state() can find them and set toggles/checks etc */
661
662         register_actions ();
663
664         setup_toolbar ();
665         setup_midi_toolbar ();
666
667         _snap_type = SnapToBeat;
668         set_snap_to (_snap_type);
669         _snap_mode = SnapOff;
670         set_snap_mode (_snap_mode);
671         set_mouse_mode (MouseObject, true);
672         set_edit_point_preference (EditAtMouse, true);
673
674         _playlist_selector = new PlaylistSelector();
675         _playlist_selector->signal_delete_event().connect (sigc::bind (sigc::ptr_fun (just_hide_it), static_cast<Window *> (_playlist_selector)));
676
677         RegionView::RegionViewGoingAway.connect (*this, invalidator (*this),  ui_bind (&Editor::catch_vanishing_regionview, this, _1), gui_context());
678
679         /* nudge stuff */
680
681         nudge_forward_button.add (*(manage (new Image (::get_icon("nudge_right")))));
682         nudge_backward_button.add (*(manage (new Image (::get_icon("nudge_left")))));
683
684         nudge_forward_button.set_name ("TransportButton");
685         nudge_backward_button.set_name ("TransportButton");
686
687         fade_context_menu.set_name ("ArdourContextMenu");
688
689         /* icons, titles, WM stuff */
690
691         list<Glib::RefPtr<Gdk::Pixbuf> > window_icons;
692         Glib::RefPtr<Gdk::Pixbuf> icon;
693
694         if ((icon = ::get_icon ("ardour_icon_16px")) != 0) {
695                 window_icons.push_back (icon);
696         }
697         if ((icon = ::get_icon ("ardour_icon_22px")) != 0) {
698                 window_icons.push_back (icon);
699         }
700         if ((icon = ::get_icon ("ardour_icon_32px")) != 0) {
701                 window_icons.push_back (icon);
702         }
703         if ((icon = ::get_icon ("ardour_icon_48px")) != 0) {
704                 window_icons.push_back (icon);
705         }
706         if (!window_icons.empty()) {
707                 set_icon_list (window_icons);
708                 set_default_icon_list (window_icons);
709         }
710
711         WindowTitle title(Glib::get_application_name());
712         title += _("Editor");
713         set_title (title.get_string());
714         set_wmclass (X_("ardour_editor"), PROGRAM_NAME);
715
716         add (vpacker);
717         add_events (Gdk::KEY_PRESS_MASK|Gdk::KEY_RELEASE_MASK);
718
719         signal_configure_event().connect (sigc::mem_fun (*ARDOUR_UI::instance(), &ARDOUR_UI::configure_handler));
720         signal_delete_event().connect (sigc::mem_fun (*ARDOUR_UI::instance(), &ARDOUR_UI::exit_on_main_window_close));
721
722         /* allow external control surfaces/protocols to do various things */
723
724         ControlProtocol::ZoomToSession.connect (*this, invalidator (*this), boost::bind (&Editor::temporal_zoom_session, this), gui_context());
725         ControlProtocol::ZoomIn.connect (*this, invalidator (*this), boost::bind (&Editor::temporal_zoom_step, this, false), gui_context());
726         ControlProtocol::ZoomOut.connect (*this, invalidator (*this), boost::bind (&Editor::temporal_zoom_step, this, true), gui_context());
727         ControlProtocol::ScrollTimeline.connect (*this, invalidator (*this), ui_bind (&Editor::control_scroll, this, _1), gui_context());
728         BasicUI::AccessAction.connect (*this, invalidator (*this), ui_bind (&Editor::access_action, this, _1, _2), gui_context());
729         
730         /* problematic: has to return a value and thus cannot be x-thread */
731
732         Session::AskAboutPlaylistDeletion.connect_same_thread (*this, boost::bind (&Editor::playlist_deletion_dialog, this, _1));
733
734         Config->ParameterChanged.connect (*this, invalidator (*this), ui_bind (&Editor::parameter_changed, this, _1), gui_context());
735
736         TimeAxisView::CatchDeletion.connect (*this, invalidator (*this), ui_bind (&Editor::timeaxisview_deleted, this, _1), gui_context());
737
738         _last_normalization_value = 0;
739
740         constructed = true;
741         instant_save ();
742
743         setup_fade_images ();
744 }
745
746 Editor::~Editor()
747 {
748 #ifdef WITH_CMT
749         if(image_socket_listener) {
750                 if(image_socket_listener->is_connected())
751                 {
752                         image_socket_listener->close_connection() ;
753                 }
754
755                 delete image_socket_listener ;
756                 image_socket_listener = 0 ;
757         }
758 #endif
759         
760         delete _routes;
761         delete _route_groups;
762         delete track_canvas;
763         delete _drags;
764 }
765
766 void
767 Editor::add_toplevel_controls (Container& cont)
768 {
769         vpacker.pack_start (cont, false, false);
770         cont.show_all ();
771 }
772
773 void
774 Editor::catch_vanishing_regionview (RegionView *rv)
775 {
776         /* note: the selection will take care of the vanishing
777            audioregionview by itself.
778         */
779
780         if (_drags->active() && _drags->have_item (rv->get_canvas_group()) && !_drags->ending()) {
781                 _drags->abort ();
782         }
783
784         if (clicked_regionview == rv) {
785                 clicked_regionview = 0;
786         }
787
788         if (entered_regionview == rv) {
789                 set_entered_regionview (0);
790         }
791 }
792
793 void
794 Editor::set_entered_regionview (RegionView* rv)
795 {
796         if (rv == entered_regionview) {
797                 return;
798         }
799
800         if (entered_regionview) {
801                 entered_regionview->exited ();
802         }
803
804         if ((entered_regionview = rv) != 0) {
805                 entered_regionview->entered (internal_editing ());
806         }
807 }
808
809 void
810 Editor::set_entered_track (TimeAxisView* tav)
811 {
812         if (entered_track) {
813                 entered_track->exited ();
814         }
815
816         if ((entered_track = tav) != 0) {
817                 entered_track->entered ();
818         }
819 }
820
821 void
822 Editor::show_window ()
823 {
824         if (! is_visible ()) {
825                 show_all ();
826
827                 /* re-hide editor list if necessary */
828                 editor_list_button_toggled ();
829
830                 /* re-hide summary widget if necessary */
831                 parameter_changed ("show-summary");
832
833                 parameter_changed ("show-edit-group-tabs");
834
835                 /* now reset all audio_time_axis heights, because widgets might need
836                    to be re-hidden
837                 */
838
839                 TimeAxisView *tv;
840
841                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
842                         tv = (static_cast<TimeAxisView*>(*i));
843                         tv->reset_height ();
844                 }
845         }
846
847         present ();
848 }
849
850 void
851 Editor::instant_save ()
852 {
853         if (!constructed || !ARDOUR_UI::instance()->session_loaded) {
854                 return;
855         }
856
857         if (_session) {
858                 _session->add_instant_xml(get_state());
859         } else {
860                 Config->add_instant_xml(get_state());
861         }
862 }
863
864 void
865 Editor::zoom_adjustment_changed ()
866 {
867         if (_session == 0) {
868                 return;
869         }
870
871         double fpu = zoom_range_clock.current_duration() / _canvas_width;
872
873         if (fpu < 1.0) {
874                 fpu = 1.0;
875                 zoom_range_clock.set ((framepos_t) floor (fpu * _canvas_width));
876         } else if (fpu > _session->current_end_frame() / _canvas_width) {
877                 fpu = _session->current_end_frame() / _canvas_width;
878                 zoom_range_clock.set ((framepos_t) floor (fpu * _canvas_width));
879         }
880
881         temporal_zoom (fpu);
882 }
883
884 void
885 Editor::control_scroll (float fraction)
886 {
887         ENSURE_GUI_THREAD (*this, &Editor::control_scroll, fraction)
888
889         if (!_session) {
890                 return;
891         }
892
893         double step = fraction * current_page_frames();
894
895         /*
896                 _control_scroll_target is an optional<T>
897
898                 it acts like a pointer to an framepos_t, with
899                 a operator conversion to boolean to check
900                 that it has a value could possibly use
901                 playhead_cursor->current_frame to store the
902                 value and a boolean in the class to know
903                 when it's out of date
904         */
905
906         if (!_control_scroll_target) {
907                 _control_scroll_target = _session->transport_frame();
908                 _dragging_playhead = true;
909         }
910
911         if ((fraction < 0.0f) && (*_control_scroll_target < (framepos_t) fabs(step))) {
912                 *_control_scroll_target = 0;
913         } else if ((fraction > 0.0f) && (max_framepos - *_control_scroll_target < step)) {
914                 *_control_scroll_target = max_framepos - (current_page_frames()*2); // allow room for slop in where the PH is on the screen
915         } else {
916                 *_control_scroll_target += (framepos_t) floor (step);
917         }
918
919         /* move visuals, we'll catch up with it later */
920
921         playhead_cursor->set_position (*_control_scroll_target);
922         UpdateAllTransportClocks (*_control_scroll_target);
923
924         if (*_control_scroll_target > (current_page_frames() / 2)) {
925                 /* try to center PH in window */
926                 reset_x_origin (*_control_scroll_target - (current_page_frames()/2));
927         } else {
928                 reset_x_origin (0);
929         }
930
931         /*
932                 Now we do a timeout to actually bring the session to the right place
933                 according to the playhead. This is to avoid reading disk buffers on every
934                 call to control_scroll, which is driven by ScrollTimeline and therefore
935                 probably by a control surface wheel which can generate lots of events.
936         */
937         /* cancel the existing timeout */
938
939         control_scroll_connection.disconnect ();
940
941         /* add the next timeout */
942
943         control_scroll_connection = Glib::signal_timeout().connect (sigc::bind (sigc::mem_fun (*this, &Editor::deferred_control_scroll), *_control_scroll_target), 250);
944 }
945
946 bool
947 Editor::deferred_control_scroll (framepos_t /*target*/)
948 {
949         _session->request_locate (*_control_scroll_target, _session->transport_rolling());
950         // reset for next stream
951         _control_scroll_target = boost::none;
952         _dragging_playhead = false;
953         return false;
954 }
955
956 void
957 Editor::access_action (std::string action_group, std::string action_item)
958 {
959         if (!_session) {
960                 return;
961         }
962
963         ENSURE_GUI_THREAD (*this, &Editor::access_action, action_group, action_item)
964
965         RefPtr<Action> act;
966         act = ActionManager::get_action( action_group.c_str(), action_item.c_str() );
967
968         if (act) {
969                 act->activate();
970         }
971 }
972
973 void
974 Editor::on_realize ()
975 {
976         Window::on_realize ();
977         Realized ();
978 }
979
980 void
981 Editor::map_position_change (framepos_t frame)
982 {
983         ENSURE_GUI_THREAD (*this, &Editor::map_position_change, frame)
984
985         if (_session == 0) {
986                 return;
987         }
988
989         if (_follow_playhead) {
990                 center_screen (frame);
991         }
992
993         playhead_cursor->set_position (frame);
994 }
995
996 void
997 Editor::center_screen (framepos_t frame)
998 {
999         double page = _canvas_width * frames_per_unit;
1000
1001         /* if we're off the page, then scroll.
1002          */
1003
1004         if (frame < leftmost_frame || frame >= leftmost_frame + page) {
1005                 center_screen_internal (frame, page);
1006         }
1007 }
1008
1009 void
1010 Editor::center_screen_internal (framepos_t frame, float page)
1011 {
1012         page /= 2;
1013
1014         if (frame > page) {
1015                 frame -= (framepos_t) page;
1016         } else {
1017                 frame = 0;
1018         }
1019
1020         reset_x_origin (frame);
1021 }
1022
1023
1024 void
1025 Editor::update_title ()
1026 {
1027         ENSURE_GUI_THREAD (*this, &Editor::update_title)
1028
1029         if (_session) {
1030                 bool dirty = _session->dirty();
1031
1032                 string session_name;
1033
1034                 if (_session->snap_name() != _session->name()) {
1035                         session_name = _session->snap_name();
1036                 } else {
1037                         session_name = _session->name();
1038                 }
1039
1040                 if (dirty) {
1041                         session_name = "*" + session_name;
1042                 }
1043
1044                 WindowTitle title(session_name);
1045                 title += Glib::get_application_name();
1046                 set_title (title.get_string());
1047         }
1048 }
1049
1050 void
1051 Editor::set_session (Session *t)
1052 {
1053         SessionHandlePtr::set_session (t);
1054
1055         if (!_session) {
1056                 return;
1057         }
1058
1059         zoom_range_clock.set_session (_session);
1060         _playlist_selector->set_session (_session);
1061         nudge_clock.set_session (_session);
1062         _summary->set_session (_session);
1063         _group_tabs->set_session (_session);
1064         _route_groups->set_session (_session);
1065         _regions->set_session (_session);
1066         _snapshots->set_session (_session);
1067         _routes->set_session (_session);
1068         _locations->set_session (_session);
1069
1070         if (rhythm_ferret) {
1071                 rhythm_ferret->set_session (_session);
1072         }
1073
1074         if (analysis_window) {
1075                 analysis_window->set_session (_session);
1076         }
1077
1078         if (sfbrowser) {
1079                 sfbrowser->set_session (_session);
1080         }
1081
1082         compute_fixed_ruler_scale ();
1083
1084         /* there are never any selected regions at startup */
1085         sensitize_the_right_region_actions (false);
1086
1087         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
1088         set_state (*node, Stateful::loading_state_version);
1089
1090         /* catch up with the playhead */
1091
1092         _session->request_locate (playhead_cursor->current_frame);
1093         _pending_initial_locate = true;
1094
1095         update_title ();
1096
1097         /* These signals can all be emitted by a non-GUI thread. Therefore the
1098            handlers for them must not attempt to directly interact with the GUI,
1099            but use Gtkmm2ext::UI::instance()->call_slot();
1100         */
1101
1102         _session->StepEditStatusChange.connect (_session_connections, invalidator (*this), ui_bind(&Editor::step_edit_status_change, this, _1), gui_context());
1103         _session->TransportStateChange.connect (_session_connections, invalidator (*this), boost::bind (&Editor::map_transport_state, this), gui_context());
1104         _session->PositionChanged.connect (_session_connections, invalidator (*this), ui_bind (&Editor::map_position_change, this, _1), gui_context());
1105         _session->RouteAdded.connect (_session_connections, invalidator (*this), ui_bind (&Editor::handle_new_route, this, _1), gui_context());
1106         _session->DirtyChanged.connect (_session_connections, invalidator (*this), boost::bind (&Editor::update_title, this), gui_context());
1107         _session->TimecodeOffsetChanged.connect (_session_connections, invalidator (*this), boost::bind (&Editor::update_just_timecode, this), gui_context());
1108         _session->tempo_map().PropertyChanged.connect (_session_connections, invalidator (*this), ui_bind (&Editor::tempo_map_changed, this, _1), gui_context());
1109         _session->Located.connect (_session_connections, invalidator (*this), boost::bind (&Editor::located, this), gui_context());
1110         _session->config.ParameterChanged.connect (_session_connections, invalidator (*this), ui_bind (&Editor::parameter_changed, this, _1), gui_context());
1111         _session->StateSaved.connect (_session_connections, invalidator (*this), ui_bind (&Editor::session_state_saved, this, _1), gui_context());
1112         _session->locations()->added.connect (_session_connections, invalidator (*this), ui_bind (&Editor::add_new_location, this, _1), gui_context());
1113         _session->locations()->removed.connect (_session_connections, invalidator (*this), ui_bind (&Editor::location_gone, this, _1), gui_context());
1114         _session->locations()->changed.connect (_session_connections, invalidator (*this), boost::bind (&Editor::refresh_location_display, this), gui_context());
1115         _session->locations()->StateChanged.connect (_session_connections, invalidator (*this), ui_bind (&Editor::refresh_location_display_s, this, _1), gui_context());
1116         _session->history().Changed.connect (_session_connections, invalidator (*this), boost::bind (&Editor::history_changed, this), gui_context());
1117
1118         if (Profile->get_sae()) {
1119                 BBT_Time bbt;
1120                 bbt.bars = 0;
1121                 bbt.beats = 0;
1122                 bbt.ticks = 120;
1123                 nframes_t pos = _session->tempo_map().bbt_duration_at (0, bbt, 1);
1124                 nudge_clock.set_mode(AudioClock::BBT);
1125                 nudge_clock.set (pos, true, 0, AudioClock::BBT);
1126
1127         } else {
1128                 nudge_clock.set (_session->frame_rate() * 5, true, 0, AudioClock::Timecode); // default of 5 seconds
1129         }
1130
1131         playhead_cursor->canvas_item.show ();
1132
1133         Location* loc = _session->locations()->auto_loop_location();
1134         if (loc == 0) {
1135                 loc = new Location (*_session, 0, _session->current_end_frame(), _("Loop"),(Location::Flags) (Location::IsAutoLoop | Location::IsHidden));
1136                 if (loc->start() == loc->end()) {
1137                         loc->set_end (loc->start() + 1);
1138                 }
1139                 _session->locations()->add (loc, false);
1140                 _session->set_auto_loop_location (loc);
1141         } else {
1142                 // force name
1143                 loc->set_name (_("Loop"));
1144         }
1145
1146         loc = _session->locations()->auto_punch_location();
1147         if (loc == 0) {
1148                 loc = new Location (*_session, 0, _session->current_end_frame(), _("Punch"), (Location::Flags) (Location::IsAutoPunch | Location::IsHidden));
1149                 if (loc->start() == loc->end()) {
1150                         loc->set_end (loc->start() + 1);
1151                 }
1152                 _session->locations()->add (loc, false);
1153                 _session->set_auto_punch_location (loc);
1154         } else {
1155                 // force name
1156                 loc->set_name (_("Punch"));
1157         }
1158
1159         boost::function<void (string)> pc (boost::bind (&Editor::parameter_changed, this, _1));
1160         Config->map_parameters (pc);
1161         _session->config.map_parameters (pc);
1162
1163         refresh_location_display ();
1164
1165         restore_ruler_visibility ();
1166         //tempo_map_changed (PropertyChange (0));
1167         _session->tempo_map().apply_with_metrics (*this, &Editor::draw_metric_marks);
1168
1169         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
1170                 (static_cast<TimeAxisView*>(*i))->set_samples_per_unit (frames_per_unit);
1171         }
1172
1173         super_rapid_screen_update_connection = ARDOUR_UI::instance()->SuperRapidScreenUpdate.connect (
1174                 sigc::mem_fun (*this, &Editor::super_rapid_screen_update)
1175                 );
1176         
1177         switch (_snap_type) {
1178         case SnapToRegionStart:
1179         case SnapToRegionEnd:
1180         case SnapToRegionSync:
1181         case SnapToRegionBoundary:
1182                 build_region_boundary_cache ();
1183                 break;
1184
1185         default:
1186                 break;
1187         }
1188
1189         /* register for undo history */
1190         _session->register_with_memento_command_factory(_id, this);
1191
1192         start_updating_meters ();
1193 }
1194
1195 void
1196 Editor::build_cursors ()
1197 {
1198         using namespace Gdk;
1199
1200         {
1201                 Glib::RefPtr<Gdk::Pixbuf> zoom_in_cursor_pixbuf (::get_icon ("zoom_in_cursor"));
1202                 zoom_in_cursor = new Gdk::Cursor (Gdk::Display::get_default(), zoom_in_cursor_pixbuf, 5, 5);
1203         }
1204
1205         {
1206                 Glib::RefPtr<Gdk::Pixbuf> zoom_out_cursor_pixbuf (::get_icon ("zoom_out_cursor"));
1207                 zoom_out_cursor = new Gdk::Cursor (Gdk::Display::get_default(), zoom_out_cursor_pixbuf, 5, 5);
1208         }
1209         
1210         Gdk::Color fbg ("#ffffff" );
1211         Gdk::Color ffg  ("#000000" );
1212
1213         {
1214                 RefPtr<Bitmap> source, mask;
1215
1216                 source = Bitmap::create (fader_cursor_bits, fader_cursor_width, fader_cursor_height);
1217                 mask = Bitmap::create (fader_cursor_mask_bits, fader_cursor_width, fader_cursor_height);
1218                 fader_cursor = new Gdk::Cursor (source, mask, ffg, fbg, fader_cursor_x_hot, fader_cursor_y_hot);
1219         }
1220
1221         {
1222                 RefPtr<Bitmap> source, mask;
1223                 source = Bitmap::create (speaker_cursor_bits, speaker_cursor_width, speaker_cursor_height);
1224                 mask = Bitmap::create (speaker_cursor_mask_bits, speaker_cursor_width, speaker_cursor_height);
1225                 speaker_cursor = new Gdk::Cursor (source, mask, ffg, fbg, speaker_cursor_x_hot, speaker_cursor_y_hot);
1226         }
1227
1228         {
1229                 RefPtr<Bitmap> bits;
1230                 char pix[4] = { 0, 0, 0, 0 };
1231                 bits = Bitmap::create (pix, 2, 2);
1232                 Gdk::Color c;
1233                 transparent_cursor = new Gdk::Cursor (bits, bits, c, c, 0, 0);
1234         }
1235
1236         {
1237                 RefPtr<Bitmap> bits;
1238                 char pix[4] = { 0, 0, 0, 0 };
1239                 bits = Bitmap::create (pix, 2, 2);
1240                 Gdk::Color c;
1241                 transparent_cursor = new Gdk::Cursor (bits, bits, c, c, 0, 0);
1242         }
1243
1244         {
1245                 Glib::RefPtr<Gdk::Pixbuf> grabber_pixbuf (::get_icon ("grabber"));
1246                 grabber_cursor = new Gdk::Cursor (Gdk::Display::get_default(), grabber_pixbuf, 5, 0);
1247         }
1248
1249         {
1250                 Glib::RefPtr<Gdk::Pixbuf> grabber_note_pixbuf (::get_icon ("grabber_note"));
1251                 grabber_note_cursor = new Gdk::Cursor (Gdk::Display::get_default(), grabber_note_pixbuf, 5, 10);
1252         }
1253
1254         {
1255                 Glib::RefPtr<Gdk::Pixbuf> grabber_edit_point_pixbuf (::get_icon ("grabber_edit_point"));
1256                 grabber_edit_point_cursor = new Gdk::Cursor (Gdk::Display::get_default(), grabber_edit_point_pixbuf, 5, 17);
1257         }
1258
1259         cross_hair_cursor = new Gdk::Cursor (CROSSHAIR);
1260         trimmer_cursor =  new Gdk::Cursor (SB_H_DOUBLE_ARROW);
1261
1262         {
1263                 Glib::RefPtr<Gdk::Pixbuf> apixbuf (::get_icon ("trim_left_cursor"));
1264                 left_side_trim_cursor = new Gdk::Cursor (Gdk::Display::get_default(), apixbuf, 5, 11);
1265         }
1266
1267         {
1268                 Glib::RefPtr<Gdk::Pixbuf> apixbuf (::get_icon ("trim_right_cursor"));
1269                 right_side_trim_cursor = new Gdk::Cursor (Gdk::Display::get_default(), apixbuf, 23, 11);
1270         }
1271
1272         {
1273                 Glib::RefPtr<Gdk::Pixbuf> apixbuf (::get_icon ("fade_in_cursor"));
1274                 fade_in_cursor = new Gdk::Cursor (Gdk::Display::get_default(), apixbuf, 0, 40);
1275         }
1276
1277         {
1278                 Glib::RefPtr<Gdk::Pixbuf> apixbuf (::get_icon ("fade_out_cursor"));
1279                 fade_out_cursor = new Gdk::Cursor (Gdk::Display::get_default(), apixbuf, 27, 40);
1280         }
1281
1282         selector_cursor = new Gdk::Cursor (XTERM);
1283         time_fx_cursor = new Gdk::Cursor (SIZING);
1284         wait_cursor = new Gdk::Cursor  (WATCH);
1285         timebar_cursor = new Gdk::Cursor(LEFT_PTR);
1286         midi_pencil_cursor = new Gdk::Cursor (PENCIL);
1287         midi_select_cursor = new Gdk::Cursor (CENTER_PTR);
1288         midi_resize_cursor = new Gdk::Cursor (SIZING);
1289         midi_erase_cursor = new Gdk::Cursor (DRAPED_BOX);
1290         up_down_cursor = new Gdk::Cursor (Gdk::SB_V_DOUBLE_ARROW);
1291 }
1292
1293 /** Pop up a context menu for when the user clicks on a fade in or fade out */
1294 void
1295 Editor::popup_fade_context_menu (int button, int32_t time, ArdourCanvas::Item* item, ItemType item_type)
1296 {
1297         using namespace Menu_Helpers;
1298         AudioRegionView* arv = static_cast<AudioRegionView*> (item->get_data ("regionview"));
1299
1300         if (arv == 0) {
1301                 fatal << _("programming error: fade in canvas item has no regionview data pointer!") << endmsg;
1302                 /*NOTREACHED*/
1303         }
1304
1305         MenuList& items (fade_context_menu.items());
1306
1307         items.clear ();
1308
1309         switch (item_type) {
1310         case FadeInItem:
1311         case FadeInHandleItem:
1312                 if (arv->audio_region()->fade_in_active()) {
1313                         items.push_back (MenuElem (_("Deactivate"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_active), false)));
1314                 } else {
1315                         items.push_back (MenuElem (_("Activate"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_active), true)));
1316                 }
1317
1318                 items.push_back (SeparatorElem());
1319
1320                 if (Profile->get_sae()) {
1321                         
1322                         items.push_back (MenuElem (_("Linear"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), FadeLinear)));
1323                         items.push_back (MenuElem (_("Slowest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), FadeFast)));
1324                         
1325                 } else {
1326
1327                         items.push_back (
1328                                 ImageMenuElem (
1329                                         _("Linear"),
1330                                         *_fade_in_images[FadeLinear],
1331                                         sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), FadeLinear)
1332                                         )
1333                                 );
1334
1335                         dynamic_cast<ImageMenuItem*>(&items.back())->set_always_show_image ();
1336
1337                         items.push_back (
1338                                 ImageMenuElem (
1339                                         _("Slowest"),
1340                                         *_fade_in_images[FadeFast],
1341                                         sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), FadeFast)
1342                                         ));
1343                         
1344                         dynamic_cast<ImageMenuItem*>(&items.back())->set_always_show_image ();
1345                         
1346                         items.push_back (
1347                                 ImageMenuElem (
1348                                         _("Slow"),
1349                                         *_fade_in_images[FadeLogB],
1350                                         sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), FadeLogB)
1351                                         ));
1352                         
1353                         dynamic_cast<ImageMenuItem*>(&items.back())->set_always_show_image ();
1354                         
1355                         items.push_back (
1356                                 ImageMenuElem (
1357                                         _("Fast"),
1358                                         *_fade_in_images[FadeLogA],
1359                                         sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), FadeLogA)
1360                                         ));
1361                         
1362                         dynamic_cast<ImageMenuItem*>(&items.back())->set_always_show_image ();
1363                         
1364                         items.push_back (
1365                                 ImageMenuElem (
1366                                         _("Fastest"),
1367                                         *_fade_in_images[FadeSlow],
1368                                         sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), FadeSlow)
1369                                         ));
1370                         
1371                         dynamic_cast<ImageMenuItem*>(&items.back())->set_always_show_image ();
1372                 }
1373
1374                 break;
1375
1376         case FadeOutItem:
1377         case FadeOutHandleItem:
1378                 if (arv->audio_region()->fade_out_active()) {
1379                         items.push_back (MenuElem (_("Deactivate"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_active), false)));
1380                 } else {
1381                         items.push_back (MenuElem (_("Activate"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_active), true)));
1382                 }
1383
1384                 items.push_back (SeparatorElem());
1385
1386                 if (Profile->get_sae()) {
1387                         items.push_back (MenuElem (_("Linear"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), FadeLinear)));
1388                         items.push_back (MenuElem (_("Slowest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), FadeSlow)));
1389                 } else {
1390
1391                         items.push_back (
1392                                 ImageMenuElem (
1393                                         _("Linear"),
1394                                         *_fade_out_images[FadeLinear],
1395                                         sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), FadeLinear)
1396                                         )
1397                                 );
1398
1399                         dynamic_cast<ImageMenuItem*>(&items.back())->set_always_show_image ();
1400
1401                         items.push_back (
1402                                 ImageMenuElem (
1403                                         _("Slowest"),
1404                                         *_fade_out_images[FadeFast],
1405                                         sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), FadeSlow)
1406                                         ));
1407                         
1408                         dynamic_cast<ImageMenuItem*>(&items.back())->set_always_show_image ();
1409                         
1410                         items.push_back (
1411                                 ImageMenuElem (
1412                                         _("Slow"),
1413                                         *_fade_out_images[FadeLogB],
1414                                         sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), FadeLogA)
1415                                         ));
1416                         
1417                         dynamic_cast<ImageMenuItem*>(&items.back())->set_always_show_image ();
1418                         
1419                         items.push_back (
1420                                 ImageMenuElem (
1421                                         _("Fast"),
1422                                         *_fade_out_images[FadeLogA],
1423                                         sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), FadeLogB)
1424                                         ));
1425                         
1426                         dynamic_cast<ImageMenuItem*>(&items.back())->set_always_show_image ();
1427                         
1428                         items.push_back (
1429                                 ImageMenuElem (
1430                                         _("Fastest"),
1431                                         *_fade_out_images[FadeSlow],
1432                                         sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), FadeFast)
1433                                         ));
1434                         
1435                         dynamic_cast<ImageMenuItem*>(&items.back())->set_always_show_image ();
1436                 }
1437
1438                 break;
1439
1440         default:
1441                 fatal << _("programming error: ")
1442                       << X_("non-fade canvas item passed to popup_fade_context_menu()")
1443                       << endmsg;
1444                 /*NOTREACHED*/
1445         }
1446
1447         fade_context_menu.popup (button, time);
1448 }
1449
1450 void
1451 Editor::popup_track_context_menu (int button, int32_t time, ItemType item_type, bool with_selection, framepos_t frame)
1452 {
1453         using namespace Menu_Helpers;
1454         Menu* (Editor::*build_menu_function)(framepos_t);
1455         Menu *menu;
1456
1457         switch (item_type) {
1458         case RegionItem:
1459         case RegionViewName:
1460         case RegionViewNameHighlight:
1461         case LeftFrameHandle:
1462         case RightFrameHandle:
1463                 if (with_selection) {
1464                         build_menu_function = &Editor::build_track_selection_context_menu;
1465                 } else {
1466                         build_menu_function = &Editor::build_track_region_context_menu;
1467                 }
1468                 break;
1469
1470         case SelectionItem:
1471                 if (with_selection) {
1472                         build_menu_function = &Editor::build_track_selection_context_menu;
1473                 } else {
1474                         build_menu_function = &Editor::build_track_context_menu;
1475                 }
1476                 break;
1477
1478         case CrossfadeViewItem:
1479                 build_menu_function = &Editor::build_track_crossfade_context_menu;
1480                 break;
1481
1482         case StreamItem:
1483                 if (clicked_routeview->track()) {
1484                         build_menu_function = &Editor::build_track_context_menu;
1485                 } else {
1486                         build_menu_function = &Editor::build_track_bus_context_menu;
1487                 }
1488                 break;
1489
1490         default:
1491                 /* probably shouldn't happen but if it does, we don't care */
1492                 return;
1493         }
1494
1495         menu = (this->*build_menu_function)(frame);
1496         menu->set_name ("ArdourContextMenu");
1497
1498         /* now handle specific situations */
1499
1500         switch (item_type) {
1501         case RegionItem:
1502         case RegionViewName:
1503         case RegionViewNameHighlight:
1504         case LeftFrameHandle:
1505         case RightFrameHandle:
1506                 if (!with_selection) {
1507                         if (region_edit_menu_split_item) {
1508                                 if (clicked_regionview && clicked_regionview->region()->covers (get_preferred_edit_position())) {
1509                                         ActionManager::set_sensitive (ActionManager::edit_point_in_region_sensitive_actions, true);
1510                                 } else {
1511                                         ActionManager::set_sensitive (ActionManager::edit_point_in_region_sensitive_actions, false);
1512                                 }
1513                         }
1514                         if (region_edit_menu_split_multichannel_item) {
1515                                 if (clicked_regionview && clicked_regionview->region()->n_channels() > 1) {
1516                                         region_edit_menu_split_multichannel_item->set_sensitive (true);
1517                                 } else {
1518                                         region_edit_menu_split_multichannel_item->set_sensitive (false);
1519                                 }
1520                         }
1521                 }
1522                 break;
1523
1524         case SelectionItem:
1525                 break;
1526
1527         case CrossfadeViewItem:
1528                 break;
1529
1530         case StreamItem:
1531                 break;
1532
1533         default:
1534                 /* probably shouldn't happen but if it does, we don't care */
1535                 return;
1536         }
1537
1538         if (item_type != SelectionItem && clicked_routeview && clicked_routeview->audio_track()) {
1539
1540                 /* Bounce to disk */
1541
1542                 using namespace Menu_Helpers;
1543                 MenuList& edit_items  = menu->items();
1544
1545                 edit_items.push_back (SeparatorElem());
1546
1547                 switch (clicked_routeview->audio_track()->freeze_state()) {
1548                 case AudioTrack::NoFreeze:
1549                         edit_items.push_back (MenuElem (_("Freeze"), sigc::mem_fun(*this, &Editor::freeze_route)));
1550                         break;
1551
1552                 case AudioTrack::Frozen:
1553                         edit_items.push_back (MenuElem (_("Unfreeze"), sigc::mem_fun(*this, &Editor::unfreeze_route)));
1554                         break;
1555
1556                 case AudioTrack::UnFrozen:
1557                         edit_items.push_back (MenuElem (_("Freeze"), sigc::mem_fun(*this, &Editor::freeze_route)));
1558                         break;
1559                 }
1560
1561         }
1562
1563         if (item_type == StreamItem && clicked_routeview) {
1564                 clicked_routeview->build_underlay_menu(menu);
1565         }
1566
1567         menu->popup (button, time);
1568 }
1569
1570 Menu*
1571 Editor::build_track_context_menu (framepos_t)
1572 {
1573         using namespace Menu_Helpers;
1574
1575         MenuList& edit_items = track_context_menu.items();
1576         edit_items.clear();
1577
1578         add_dstream_context_items (edit_items);
1579         return &track_context_menu;
1580 }
1581
1582 Menu*
1583 Editor::build_track_bus_context_menu (framepos_t)
1584 {
1585         using namespace Menu_Helpers;
1586
1587         MenuList& edit_items = track_context_menu.items();
1588         edit_items.clear();
1589
1590         add_bus_context_items (edit_items);
1591         return &track_context_menu;
1592 }
1593
1594 Menu*
1595 Editor::build_track_region_context_menu (framepos_t frame)
1596 {
1597         using namespace Menu_Helpers;
1598         MenuList& edit_items  = track_region_context_menu.items();
1599         edit_items.clear();
1600
1601         /* we've just cleared the track region context menu, so the menu that these
1602            two items were on will have disappeared; stop them dangling.
1603         */
1604         region_edit_menu_split_item = 0;
1605         region_edit_menu_split_multichannel_item = 0;
1606
1607         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (clicked_axisview);
1608
1609         if (rtv) {
1610                 boost::shared_ptr<Track> tr;
1611                 boost::shared_ptr<Playlist> pl;
1612
1613                 /* Don't offer a region submenu if we are in internal edit mode, as we don't select regions in this
1614                    mode and so offering region context is somewhat confusing.
1615                 */
1616                 if ((tr = rtv->track()) && ((pl = tr->playlist())) && !internal_editing()) {
1617                         framepos_t framepos = (framepos_t) floor ((double)frame * tr->speed());
1618                         uint32_t regions_at = pl->count_regions_at (framepos);
1619                         list<boost::shared_ptr<Region> > regions_for_menu;
1620
1621                         if (selection->regions.size() > 1) {
1622                                 // there's already a multiple selection: just add a
1623                                 // single region context menu that will act on all
1624                                 // selected regions
1625
1626                                 for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
1627                                         regions_for_menu.push_back ((*i)->region ());
1628                                 }
1629                         } else {
1630                                 boost::shared_ptr<Region> top_region = pl->top_region_at (framepos);
1631                                 if (top_region) {
1632                                         regions_for_menu.push_back (top_region);
1633                                 }
1634                         }
1635
1636                         add_region_context_items (rtv->view(), regions_for_menu, edit_items, framepos, regions_at > 1);
1637                 }
1638         }
1639
1640         add_dstream_context_items (edit_items);
1641
1642         return &track_region_context_menu;
1643 }
1644
1645 Menu*
1646 Editor::build_track_crossfade_context_menu (framepos_t frame)
1647 {
1648         using namespace Menu_Helpers;
1649         MenuList& edit_items  = track_crossfade_context_menu.items();
1650         edit_items.clear ();
1651
1652         AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*> (clicked_axisview);
1653
1654         if (atv) {
1655                 boost::shared_ptr<Track> tr;
1656                 boost::shared_ptr<Playlist> pl;
1657                 boost::shared_ptr<AudioPlaylist> apl;
1658
1659                 if ((tr = atv->track()) && ((pl = tr->playlist()) != 0) && ((apl = boost::dynamic_pointer_cast<AudioPlaylist> (pl)) != 0)) {
1660
1661                         AudioPlaylist::Crossfades xfades;
1662
1663                         apl->crossfades_at (frame, xfades);
1664
1665                         bool many = xfades.size() > 1;
1666
1667                         for (AudioPlaylist::Crossfades::iterator i = xfades.begin(); i != xfades.end(); ++i) {
1668                                 add_crossfade_context_items (atv->audio_view(), (*i), edit_items, many);
1669                         }
1670
1671                         framepos_t framepos = (framepos_t) floor ((double)frame * tr->speed());
1672                         uint32_t regions_at = pl->count_regions_at (framepos);
1673                         list<boost::shared_ptr<Region> > regions_for_menu;
1674
1675                         if (selection->regions.size() > 1) {
1676                                 // there's already a multiple selection: just add a
1677                                 // single region context menu that will act on all
1678                                 // selected regions
1679
1680                                 for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
1681                                         regions_for_menu.push_back ((*i)->region ());
1682                                 }
1683                         } else {
1684                                 boost::shared_ptr<Region> top_region = pl->top_region_at (framepos);
1685                                 if (top_region) {
1686                                         regions_for_menu.push_back (top_region);
1687                                 }
1688                         }
1689                         
1690                         add_region_context_items (atv->audio_view(), regions_for_menu, edit_items, framepos, regions_at > 1);
1691                 }
1692         }
1693
1694         add_dstream_context_items (edit_items);
1695
1696         return &track_crossfade_context_menu;
1697 }
1698
1699 void
1700 Editor::analyze_region_selection()
1701 {
1702         if (analysis_window == 0) {
1703                 analysis_window = new AnalysisWindow();
1704
1705                 if (_session != 0)
1706                         analysis_window->set_session(_session);
1707
1708                 analysis_window->show_all();
1709         }
1710
1711         analysis_window->set_regionmode();
1712         analysis_window->analyze();
1713
1714         analysis_window->present();
1715 }
1716
1717 void
1718 Editor::analyze_range_selection()
1719 {
1720         if (analysis_window == 0) {
1721                 analysis_window = new AnalysisWindow();
1722
1723                 if (_session != 0)
1724                         analysis_window->set_session(_session);
1725
1726                 analysis_window->show_all();
1727         }
1728
1729         analysis_window->set_rangemode();
1730         analysis_window->analyze();
1731
1732         analysis_window->present();
1733 }
1734
1735 Menu*
1736 Editor::build_track_selection_context_menu (framepos_t)
1737 {
1738         using namespace Menu_Helpers;
1739         MenuList& edit_items  = track_selection_context_menu.items();
1740         edit_items.clear ();
1741
1742         add_selection_context_items (edit_items);
1743         // edit_items.push_back (SeparatorElem());
1744         // add_dstream_context_items (edit_items);
1745
1746         return &track_selection_context_menu;
1747 }
1748
1749 /** Add context menu items relevant to crossfades.
1750  * @param edit_items List to add the items to.
1751  */
1752 void
1753 Editor::add_crossfade_context_items (AudioStreamView* /*view*/, boost::shared_ptr<Crossfade> xfade, Menu_Helpers::MenuList& edit_items, bool many)
1754 {
1755         using namespace Menu_Helpers;
1756         Menu     *xfade_menu = manage (new Menu);
1757         MenuList& items       = xfade_menu->items();
1758         xfade_menu->set_name ("ArdourContextMenu");
1759         string str;
1760
1761         if (xfade->active()) {
1762                 str = _("Mute");
1763         } else {
1764                 str = _("Unmute");
1765         }
1766
1767         items.push_back (MenuElem (str, sigc::bind (sigc::mem_fun(*this, &Editor::toggle_xfade_active), boost::weak_ptr<Crossfade> (xfade))));
1768         items.push_back (MenuElem (_("Edit..."), sigc::bind (sigc::mem_fun(*this, &Editor::edit_xfade), boost::weak_ptr<Crossfade> (xfade))));
1769
1770         if (xfade->can_follow_overlap()) {
1771
1772                 if (xfade->following_overlap()) {
1773                         str = _("Convert to Short");
1774                 } else {
1775                         str = _("Convert to Full");
1776                 }
1777
1778                 items.push_back (MenuElem (str, sigc::bind (sigc::mem_fun(*this, &Editor::toggle_xfade_length), xfade)));
1779         }
1780
1781         if (many) {
1782                 str = xfade->out()->name();
1783                 str += "->";
1784                 str += xfade->in()->name();
1785         } else {
1786                 str = _("Crossfade");
1787         }
1788
1789         edit_items.push_back (MenuElem (str, *xfade_menu));
1790         edit_items.push_back (SeparatorElem());
1791 }
1792
1793 void
1794 Editor::xfade_edit_left_region ()
1795 {
1796         if (clicked_crossfadeview) {
1797                 clicked_crossfadeview->left_view.show_region_editor ();
1798         }
1799 }
1800
1801 void
1802 Editor::xfade_edit_right_region ()
1803 {
1804         if (clicked_crossfadeview) {
1805                 clicked_crossfadeview->right_view.show_region_editor ();
1806         }
1807 }
1808
1809 void
1810 Editor::add_region_context_items (StreamView* sv, list<boost::shared_ptr<Region> > regions, Menu_Helpers::MenuList& edit_items,
1811                                   framepos_t position, bool multiple_regions_at_position)
1812 {
1813         using namespace Menu_Helpers;
1814         Gtk::MenuItem* foo_item;
1815         Menu     *region_menu = manage (new Menu);
1816         MenuList& items       = region_menu->items();
1817         region_menu->set_name ("ArdourContextMenu");
1818
1819         /* Look through the regions that we are handling and make notes about what we have got */
1820         
1821         bool have_audio = false;
1822         bool have_midi = false;
1823         bool have_locked = false;
1824         bool have_unlocked = false;
1825         bool have_position_lock_style_audio = false;
1826         bool have_position_lock_style_music = false;
1827         bool have_muted = false;
1828         bool have_unmuted = false;
1829         bool have_opaque = false;
1830         bool have_non_opaque = false;
1831         bool have_not_at_natural_position = false;
1832         bool have_envelope_visible = false;
1833         bool have_envelope_invisible = false;
1834         bool have_envelope_active = false;
1835         bool have_envelope_inactive = false;
1836         bool have_non_unity_scale_amplitude = false;
1837
1838         for (list<boost::shared_ptr<Region> >::const_iterator i = regions.begin(); i != regions.end(); ++i) {
1839                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (*i);
1840                 if (ar) {
1841                         have_audio = true;
1842                 }
1843                 if (boost::dynamic_pointer_cast<MidiRegion> (*i)) {
1844                         have_midi = true;
1845                 }
1846
1847                 if ((*i)->locked()) {
1848                         have_locked = true;
1849                 } else {
1850                         have_unlocked = true;
1851                 }
1852
1853                 if ((*i)->position_lock_style() == MusicTime) {
1854                         have_position_lock_style_music = true;
1855                 } else {
1856                         have_position_lock_style_audio = true;
1857                 }
1858
1859                 if ((*i)->muted()) {
1860                         have_muted = true;
1861                 } else {
1862                         have_unmuted = true;
1863                 }
1864
1865                 if ((*i)->opaque()) {
1866                         have_opaque = true;
1867                 } else {
1868                         have_non_opaque = true;
1869                 }
1870
1871                 if (!(*i)->at_natural_position()) {
1872                         have_not_at_natural_position = true;
1873                 }
1874
1875                 if (ar) {
1876                         /* its a bit unfortunate that "envelope visible" is a view-only
1877                            property. we have to find the regionview to able to check
1878                            its current setting.
1879                         */
1880
1881                         RegionView* rv = sv->find_view (ar);
1882                         have_envelope_invisible = true;
1883
1884                         if (rv) {
1885                                 AudioRegionView* arv = dynamic_cast<AudioRegionView*> (rv);
1886                                 if (arv && arv->envelope_visible()) {
1887                                         have_envelope_visible = true;
1888                                 }
1889                         }
1890
1891                         if (ar->envelope_active()) {
1892                                 have_envelope_active = true;
1893                         } else {
1894                                 have_envelope_inactive = true;
1895                         }
1896
1897                         if (ar->scale_amplitude() != 1) {
1898                                 have_non_unity_scale_amplitude = true;
1899                         }
1900                 }
1901         }
1902
1903         if (regions.size() == 1) {
1904
1905                 /* when this particular menu pops up, make the relevant region
1906                    become selected.
1907                 */
1908
1909                 region_menu->signal_map_event().connect (
1910                         sigc::bind (sigc::mem_fun(*this, &Editor::set_selected_regionview_from_map_event), sv, boost::weak_ptr<Region> (regions.front()))
1911                         );
1912
1913                 items.push_back (MenuElem (_("Rename..."), sigc::mem_fun(*this, &Editor::rename_region)));
1914                 
1915                 if (have_midi) {
1916                         items.push_back (MenuElem (_("List Editor..."), sigc::mem_fun(*this, &Editor::show_midi_list_editor)));
1917                 }
1918                 
1919                 items.push_back (MenuElem (_("Region Properties..."), sigc::mem_fun(*this, &Editor::edit_region)));
1920         }
1921
1922         items.push_back (MenuElem (_("Raise to Top Layer"), sigc::mem_fun(*this, &Editor::raise_region_to_top)));
1923         items.push_back (MenuElem (_("Lower to Bottom Layer"), sigc::mem_fun  (*this, &Editor::lower_region_to_bottom)));
1924         items.push_back (SeparatorElem());
1925         items.push_back (MenuElem (_("Define Sync Point"), sigc::mem_fun(*this, &Editor::set_region_sync_from_edit_point)));
1926         if (_edit_point == EditAtMouse) {
1927                 items.back ().set_sensitive (false);
1928         }
1929         items.push_back (MenuElem (_("Remove Sync Point"), sigc::mem_fun(*this, &Editor::remove_region_sync)));
1930         items.push_back (SeparatorElem());
1931
1932         items.push_back (MenuElem (_("Audition"), sigc::mem_fun(*this, &Editor::play_selected_region)));
1933         items.push_back (MenuElem (_("Export..."), sigc::mem_fun(*this, &Editor::export_region)));
1934         items.push_back (MenuElem (_("Bounce"), sigc::mem_fun(*this, &Editor::bounce_region_selection)));
1935
1936         if (have_audio) {
1937                 items.push_back (MenuElem (_("Spectral Analysis..."), sigc::mem_fun(*this, &Editor::analyze_region_selection)));
1938         }
1939
1940         items.push_back (SeparatorElem());
1941
1942         items.push_back (CheckMenuElem (_("Lock")));
1943         CheckMenuItem* region_lock_item = static_cast<CheckMenuItem*>(&items.back());
1944         if (have_locked && !have_unlocked) {
1945                 region_lock_item->set_active();
1946         } else if (have_locked && have_unlocked) {
1947                 region_lock_item->set_inconsistent ();
1948         }
1949         region_lock_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_region_lock));
1950
1951         items.push_back (CheckMenuElem (_("Glue to Bars and Beats")));
1952         CheckMenuItem* bbt_glue_item = static_cast<CheckMenuItem*>(&items.back());
1953
1954         if (have_position_lock_style_music && !have_position_lock_style_audio) {
1955                 bbt_glue_item->set_active ();
1956         } else if (have_position_lock_style_music && have_position_lock_style_audio) {
1957                 bbt_glue_item->set_inconsistent ();
1958         }
1959
1960         bbt_glue_item->signal_activate().connect (sigc::mem_fun (*this, &Editor::toggle_region_lock_style));
1961
1962         items.push_back (CheckMenuElem (_("Mute")));
1963         CheckMenuItem* region_mute_item = static_cast<CheckMenuItem*>(&items.back());
1964
1965         if (have_muted && !have_unmuted) {
1966                 region_mute_item->set_active();
1967         } else if (have_muted && have_unmuted) {
1968                 region_mute_item->set_inconsistent ();
1969         }
1970         
1971         region_mute_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_region_mute));
1972         
1973         items.push_back (MenuElem (_("Transpose..."), mem_fun(*this, &Editor::pitch_shift_regions)));
1974
1975         if (!Profile->get_sae()) {
1976                 items.push_back (CheckMenuElem (_("Opaque")));
1977                 CheckMenuItem* region_opaque_item = static_cast<CheckMenuItem*>(&items.back());
1978                 if (have_opaque && !have_non_opaque) {
1979                         region_opaque_item->set_active();
1980                 } else if (have_opaque && have_non_opaque) {
1981                         region_opaque_item->set_inconsistent ();
1982                 }
1983                 region_opaque_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_region_opaque));
1984         }
1985
1986         items.push_back (CheckMenuElem (_("Original Position"), sigc::mem_fun(*this, &Editor::naturalize)));
1987         if (!have_not_at_natural_position) {
1988                 items.back().set_sensitive (false);
1989         }
1990
1991         items.push_back (SeparatorElem());
1992
1993         if (have_audio) {
1994
1995                 if (!Profile->get_sae()) {
1996                         items.push_back (MenuElem (_("Reset Envelope"), sigc::mem_fun(*this, &Editor::reset_region_gain_envelopes)));
1997
1998                         items.push_back (CheckMenuElem (_("Envelope Visible")));
1999                         CheckMenuItem* region_envelope_visible_item = static_cast<CheckMenuItem*> (&items.back());
2000                         if (have_envelope_visible && !have_envelope_invisible) {
2001                                 region_envelope_visible_item->set_active ();
2002                         } else if (have_envelope_visible && have_envelope_invisible) {
2003                                 region_envelope_visible_item->set_inconsistent ();
2004                         }
2005                         region_envelope_visible_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_gain_envelope_visibility));
2006
2007                         items.push_back (CheckMenuElem (_("Envelope Active")));
2008                         CheckMenuItem* region_envelope_active_item = static_cast<CheckMenuItem*> (&items.back());
2009
2010                         if (have_envelope_active && !have_envelope_inactive) {
2011                                 region_envelope_active_item->set_active ();
2012                         } else if (have_envelope_active && have_envelope_inactive) {
2013                                 region_envelope_active_item->set_inconsistent ();
2014                         }
2015
2016                         region_envelope_active_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_gain_envelope_active));
2017                         items.push_back (SeparatorElem());
2018                 }
2019
2020                 items.push_back (MenuElem (_("Normalize..."), sigc::mem_fun(*this, &Editor::normalize_region)));
2021                 if (have_non_unity_scale_amplitude) {
2022                         items.push_back (MenuElem (_("Reset Gain"), sigc::mem_fun(*this, &Editor::reset_region_scale_amplitude)));
2023                 }
2024
2025         } else if (have_midi) {
2026                 items.push_back (MenuElem (_("Quantize"), sigc::mem_fun(*this, &Editor::quantize_region)));
2027                 items.push_back (MenuElem (_("Fork"), sigc::mem_fun(*this, &Editor::fork_region)));
2028                 items.push_back (SeparatorElem());
2029         }
2030
2031         items.push_back (MenuElem (_("Strip Silence..."), sigc::mem_fun (*this, &Editor::strip_region_silence)));
2032         items.push_back (MenuElem (_("Reverse"), sigc::mem_fun(*this, &Editor::reverse_region)));
2033         items.push_back (SeparatorElem());
2034
2035         /* range related stuff */
2036
2037         items.push_back (MenuElem (_("Add Single Range"), sigc::mem_fun (*this, &Editor::add_location_from_audio_region)));
2038         items.push_back (MenuElem (_("Add Range Markers"), sigc::mem_fun (*this, &Editor::add_locations_from_audio_region)));
2039         if (selection->regions.size() < 2) {
2040                 items.back().set_sensitive (false);
2041         }
2042
2043         items.push_back (MenuElem (_("Set Range Selection"), sigc::mem_fun (*this, &Editor::set_selection_from_region)));
2044         items.push_back (SeparatorElem());
2045
2046         /* Nudge region */
2047
2048         Menu *nudge_menu = manage (new Menu());
2049         MenuList& nudge_items = nudge_menu->items();
2050         nudge_menu->set_name ("ArdourContextMenu");
2051
2052         nudge_items.push_back (MenuElem (_("Nudge Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_forward), false, false))));
2053         nudge_items.push_back (MenuElem (_("Nudge Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_backward), false, false))));
2054         nudge_items.push_back (MenuElem (_("Nudge Forward by Capture Offset"), (sigc::mem_fun(*this, &Editor::nudge_forward_capture_offset))));
2055         nudge_items.push_back (MenuElem (_("Nudge Backward by Capture Offset"), (sigc::mem_fun(*this, &Editor::nudge_backward_capture_offset))));
2056
2057         items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2058         items.push_back (SeparatorElem());
2059
2060         Menu *trim_menu = manage (new Menu);
2061         MenuList& trim_items = trim_menu->items();
2062         trim_menu->set_name ("ArdourContextMenu");
2063
2064         trim_items.push_back (MenuElem (_("Start to Edit Point"), sigc::mem_fun(*this, &Editor::trim_region_from_edit_point)));
2065         foo_item = &trim_items.back();
2066         if (_edit_point == EditAtMouse) {
2067                 foo_item->set_sensitive (false);
2068         }
2069         trim_items.push_back (MenuElem (_("Edit Point to End"), sigc::mem_fun(*this, &Editor::trim_region_to_edit_point)));
2070         foo_item = &trim_items.back();
2071         if (_edit_point == EditAtMouse) {
2072                 foo_item->set_sensitive (false);
2073         }
2074         trim_items.push_back (MenuElem (_("Trim to Loop"), sigc::mem_fun(*this, &Editor::trim_region_to_loop)));
2075         trim_items.push_back (MenuElem (_("Trim to Punch"), sigc::mem_fun(*this, &Editor::trim_region_to_punch)));
2076
2077         items.push_back (MenuElem (_("Trim"), *trim_menu));
2078         items.push_back (SeparatorElem());
2079
2080         items.push_back (MenuElem (_("Split"), (sigc::mem_fun(*this, &Editor::split))));
2081         region_edit_menu_split_item = &items.back();
2082
2083         if (_edit_point == EditAtMouse) {
2084                 region_edit_menu_split_item->set_sensitive (false);
2085         }
2086
2087         if (have_audio) {
2088                 items.push_back (MenuElem (_("Make Mono Regions"), (sigc::mem_fun(*this, &Editor::split_multichannel_region))));
2089                 region_edit_menu_split_multichannel_item = &items.back();
2090         }
2091
2092         items.push_back (MenuElem (_("Duplicate"), (sigc::bind (sigc::mem_fun(*this, &Editor::duplicate_dialog), false))));
2093         items.push_back (MenuElem (_("Multi-Duplicate..."), (sigc::bind (sigc::mem_fun(*this, &Editor::duplicate_dialog), true))));
2094         items.push_back (MenuElem (_("Fill Track"), (sigc::mem_fun(*this, &Editor::region_fill_track))));
2095         items.push_back (SeparatorElem());
2096         items.push_back (MenuElem (_("Remove"), sigc::mem_fun(*this, &Editor::remove_selected_regions)));
2097
2098         /* OK, stick the region submenu at the top of the list, and then add
2099            the standard items.
2100         */
2101
2102         /* we have to hack up the region name because "_" has a special
2103            meaning for menu titles.
2104         */
2105
2106         string::size_type pos = 0;
2107         string menu_item_name = (regions.size() == 1) ? regions.front()->name() : _("Selected Regions");
2108
2109         while ((pos = menu_item_name.find ("_", pos)) != string::npos) {
2110                 menu_item_name.replace (pos, 1, "__");
2111                 pos += 2;
2112         }
2113
2114         edit_items.push_back (MenuElem (menu_item_name, *region_menu));
2115         if (multiple_regions_at_position && (layering_order_editor == 0 || !layering_order_editor->is_visible ())) {
2116                 edit_items.push_back (MenuElem (_("Choose Top Region..."), (bind (mem_fun(*this, &Editor::change_region_layering_order), position))));
2117         }
2118         edit_items.push_back (SeparatorElem());
2119 }
2120
2121 /** Add context menu items relevant to selection ranges.
2122  * @param edit_items List to add the items to.
2123  */
2124 void
2125 Editor::add_selection_context_items (Menu_Helpers::MenuList& edit_items)
2126 {
2127         using namespace Menu_Helpers;
2128
2129         edit_items.push_back (MenuElem (_("Play Range"), sigc::mem_fun(*this, &Editor::play_selection)));
2130         edit_items.push_back (MenuElem (_("Loop Range"), sigc::bind (sigc::mem_fun(*this, &Editor::set_loop_from_selection), true)));
2131
2132         edit_items.push_back (SeparatorElem());
2133         edit_items.push_back (MenuElem (_("Spectral Analysis"), sigc::mem_fun(*this, &Editor::analyze_range_selection)));
2134
2135         if (!selection->regions.empty()) {
2136                 edit_items.push_back (SeparatorElem());
2137                 edit_items.push_back (MenuElem (_("Extend Range to End of Region"), sigc::bind (sigc::mem_fun(*this, &Editor::extend_selection_to_end_of_region), false)));
2138                 edit_items.push_back (MenuElem (_("Extend Range to Start of Region"), sigc::bind (sigc::mem_fun(*this, &Editor::extend_selection_to_start_of_region), false)));
2139         }
2140
2141         edit_items.push_back (SeparatorElem());
2142         edit_items.push_back (MenuElem (_("Convert to region in-place"), mem_fun(*this, &Editor::separate_region_from_selection)));
2143         edit_items.push_back (MenuElem (_("Convert to Region in Region List"), sigc::mem_fun(*this, &Editor::new_region_from_selection)));
2144
2145         edit_items.push_back (SeparatorElem());
2146         edit_items.push_back (MenuElem (_("Select All in Range"), sigc::mem_fun(*this, &Editor::select_all_selectables_using_time_selection)));
2147
2148         edit_items.push_back (SeparatorElem());
2149         edit_items.push_back (MenuElem (_("Set Loop from Range"), sigc::bind (sigc::mem_fun(*this, &Editor::set_loop_from_selection), false)));
2150         edit_items.push_back (MenuElem (_("Set Punch from Range"), sigc::mem_fun(*this, &Editor::set_punch_from_selection)));
2151
2152         edit_items.push_back (SeparatorElem());
2153         edit_items.push_back (MenuElem (_("Add Range Markers"), sigc::mem_fun (*this, &Editor::add_location_from_selection)));
2154
2155         edit_items.push_back (SeparatorElem());
2156         edit_items.push_back (MenuElem (_("Crop Region to Range"), sigc::mem_fun(*this, &Editor::crop_region_to_selection)));
2157         edit_items.push_back (MenuElem (_("Fill Range with Region"), sigc::mem_fun(*this, &Editor::region_fill_selection)));
2158         edit_items.push_back (MenuElem (_("Duplicate Range"), sigc::bind (sigc::mem_fun(*this, &Editor::duplicate_dialog), false)));
2159
2160         edit_items.push_back (SeparatorElem());
2161         edit_items.push_back (MenuElem (_("Consolidate Range"), sigc::bind (sigc::mem_fun(*this, &Editor::bounce_range_selection), true, false)));
2162         edit_items.push_back (MenuElem (_("Consolidate Range With Processing"), sigc::bind (sigc::mem_fun(*this, &Editor::bounce_range_selection), true, true)));
2163         edit_items.push_back (MenuElem (_("Bounce Range to Region List"), sigc::bind (sigc::mem_fun(*this, &Editor::bounce_range_selection), false, false)));
2164         edit_items.push_back (MenuElem (_("Bounce Range to Region List With Processing"), sigc::bind (sigc::mem_fun(*this, &Editor::bounce_range_selection), false, true)));
2165         edit_items.push_back (MenuElem (_("Export Range"), sigc::mem_fun(*this, &Editor::export_selection)));
2166 }
2167
2168
2169 void
2170 Editor::add_dstream_context_items (Menu_Helpers::MenuList& edit_items)
2171 {
2172         using namespace Menu_Helpers;
2173
2174         /* Playback */
2175
2176         Menu *play_menu = manage (new Menu);
2177         MenuList& play_items = play_menu->items();
2178         play_menu->set_name ("ArdourContextMenu");
2179
2180         play_items.push_back (MenuElem (_("Play From Edit Point"), sigc::mem_fun(*this, &Editor::play_from_edit_point)));
2181         play_items.push_back (MenuElem (_("Play From Start"), sigc::mem_fun(*this, &Editor::play_from_start)));
2182         play_items.push_back (MenuElem (_("Play Region"), sigc::mem_fun(*this, &Editor::play_selected_region)));
2183         play_items.push_back (SeparatorElem());
2184         play_items.push_back (MenuElem (_("Loop Region"), sigc::mem_fun(*this, &Editor::loop_selected_region)));
2185
2186         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2187
2188         /* Selection */
2189
2190         Menu *select_menu = manage (new Menu);
2191         MenuList& select_items = select_menu->items();
2192         select_menu->set_name ("ArdourContextMenu");
2193
2194         select_items.push_back (MenuElem (_("Select All in Track"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2195         select_items.push_back (MenuElem (_("Select All"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all), Selection::Set)));
2196         select_items.push_back (MenuElem (_("Invert Selection in Track"), sigc::mem_fun(*this, &Editor::invert_selection_in_track)));
2197         select_items.push_back (MenuElem (_("Invert Selection"), sigc::mem_fun(*this, &Editor::invert_selection)));
2198         select_items.push_back (SeparatorElem());
2199         select_items.push_back (MenuElem (_("Set Range to Loop Range"), sigc::mem_fun(*this, &Editor::set_selection_from_loop)));
2200         select_items.push_back (MenuElem (_("Set Range to Punch Range"), sigc::mem_fun(*this, &Editor::set_selection_from_punch)));
2201         select_items.push_back (SeparatorElem());
2202         select_items.push_back (MenuElem (_("Select All After Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_edit), true)));
2203         select_items.push_back (MenuElem (_("Select All Before Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_edit), false)));
2204         select_items.push_back (MenuElem (_("Select All After Playhead"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2205         select_items.push_back (MenuElem (_("Select All Before Playhead"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2206         select_items.push_back (MenuElem (_("Select All Between Playhead and Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_between), false)));
2207         select_items.push_back (MenuElem (_("Select All Within Playhead and Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_between), true)));
2208         select_items.push_back (MenuElem (_("Select Range Between Playhead and Edit Point"), sigc::mem_fun(*this, &Editor::select_range_between)));
2209
2210         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2211
2212         /* Cut-n-Paste */
2213
2214         Menu *cutnpaste_menu = manage (new Menu);
2215         MenuList& cutnpaste_items = cutnpaste_menu->items();
2216         cutnpaste_menu->set_name ("ArdourContextMenu");
2217
2218         cutnpaste_items.push_back (MenuElem (_("Cut"), sigc::mem_fun(*this, &Editor::cut)));
2219         cutnpaste_items.push_back (MenuElem (_("Copy"), sigc::mem_fun(*this, &Editor::copy)));
2220         cutnpaste_items.push_back (MenuElem (_("Paste"), sigc::bind (sigc::mem_fun(*this, &Editor::paste), 1.0f)));
2221
2222         cutnpaste_items.push_back (SeparatorElem());
2223
2224         cutnpaste_items.push_back (MenuElem (_("Align"), sigc::bind (sigc::mem_fun(*this, &Editor::align), ARDOUR::SyncPoint)));
2225         cutnpaste_items.push_back (MenuElem (_("Align Relative"), sigc::bind (sigc::mem_fun(*this, &Editor::align_relative), ARDOUR::SyncPoint)));
2226
2227         edit_items.push_back (MenuElem (_("Edit"), *cutnpaste_menu));
2228
2229         /* Adding new material */
2230
2231         edit_items.push_back (SeparatorElem());
2232         edit_items.push_back (MenuElem (_("Insert Selected Region"), sigc::bind (sigc::mem_fun(*this, &Editor::insert_region_list_selection), 1.0f)));
2233         edit_items.push_back (MenuElem (_("Insert Existing Media"), sigc::bind (sigc::mem_fun(*this, &Editor::add_external_audio_action), ImportToTrack)));
2234
2235         /* Nudge track */
2236
2237         Menu *nudge_menu = manage (new Menu());
2238         MenuList& nudge_items = nudge_menu->items();
2239         nudge_menu->set_name ("ArdourContextMenu");
2240
2241         edit_items.push_back (SeparatorElem());
2242         nudge_items.push_back (MenuElem (_("Nudge Entire Track Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), false, true))));
2243         nudge_items.push_back (MenuElem (_("Nudge Track After Edit Point Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), true, true))));
2244         nudge_items.push_back (MenuElem (_("Nudge Entire Track Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), false, false))));
2245         nudge_items.push_back (MenuElem (_("Nudge Track After Edit Point Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), true, false))));
2246
2247         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2248 }
2249
2250 void
2251 Editor::add_bus_context_items (Menu_Helpers::MenuList& edit_items)
2252 {
2253         using namespace Menu_Helpers;
2254
2255         /* Playback */
2256
2257         Menu *play_menu = manage (new Menu);
2258         MenuList& play_items = play_menu->items();
2259         play_menu->set_name ("ArdourContextMenu");
2260
2261         play_items.push_back (MenuElem (_("Play From Edit Point"), sigc::mem_fun(*this, &Editor::play_from_edit_point)));
2262         play_items.push_back (MenuElem (_("Play From Start"), sigc::mem_fun(*this, &Editor::play_from_start)));
2263         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2264
2265         /* Selection */
2266
2267         Menu *select_menu = manage (new Menu);
2268         MenuList& select_items = select_menu->items();
2269         select_menu->set_name ("ArdourContextMenu");
2270
2271         select_items.push_back (MenuElem (_("Select All in Track"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2272         select_items.push_back (MenuElem (_("Select All"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all), Selection::Set)));
2273         select_items.push_back (MenuElem (_("Invert Selection in Track"), sigc::mem_fun(*this, &Editor::invert_selection_in_track)));
2274         select_items.push_back (MenuElem (_("Invert Selection"), sigc::mem_fun(*this, &Editor::invert_selection)));
2275         select_items.push_back (SeparatorElem());
2276         select_items.push_back (MenuElem (_("Select All After Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_edit), true)));
2277         select_items.push_back (MenuElem (_("Select All Before Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_edit), false)));
2278         select_items.push_back (MenuElem (_("Select All After Playhead"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2279         select_items.push_back (MenuElem (_("Select All Before Playhead"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2280
2281         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2282
2283         /* Cut-n-Paste */
2284
2285         Menu *cutnpaste_menu = manage (new Menu);
2286         MenuList& cutnpaste_items = cutnpaste_menu->items();
2287         cutnpaste_menu->set_name ("ArdourContextMenu");
2288
2289         cutnpaste_items.push_back (MenuElem (_("Cut"), sigc::mem_fun(*this, &Editor::cut)));
2290         cutnpaste_items.push_back (MenuElem (_("Copy"), sigc::mem_fun(*this, &Editor::copy)));
2291         cutnpaste_items.push_back (MenuElem (_("Paste"), sigc::bind (sigc::mem_fun(*this, &Editor::paste), 1.0f)));
2292
2293         Menu *nudge_menu = manage (new Menu());
2294         MenuList& nudge_items = nudge_menu->items();
2295         nudge_menu->set_name ("ArdourContextMenu");
2296
2297         edit_items.push_back (SeparatorElem());
2298         nudge_items.push_back (MenuElem (_("Nudge Entire Track Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), false, true))));
2299         nudge_items.push_back (MenuElem (_("Nudge Track After Edit Point Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), true, true))));
2300         nudge_items.push_back (MenuElem (_("Nudge Entire Track Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), false, false))));
2301         nudge_items.push_back (MenuElem (_("Nudge Track After Edit Point Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), true, false))));
2302
2303         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2304 }
2305
2306 SnapType
2307 Editor::snap_type() const
2308 {
2309         return _snap_type;
2310 }
2311
2312 SnapMode
2313 Editor::snap_mode() const
2314 {
2315         return _snap_mode;
2316 }
2317
2318 void
2319 Editor::set_snap_to (SnapType st)
2320 {
2321         unsigned int snap_ind = (unsigned int)st;
2322
2323         _snap_type = st;
2324
2325         if (snap_ind > snap_type_strings.size() - 1) {
2326                 snap_ind = 0;
2327                 _snap_type = (SnapType)snap_ind;
2328         }
2329
2330         string str = snap_type_strings[snap_ind];
2331
2332         if (str != snap_type_selector.get_active_text()) {
2333                 snap_type_selector.set_active_text (str);
2334         }
2335
2336         instant_save ();
2337
2338         switch (_snap_type) {
2339         case SnapToBeatDiv32:
2340         case SnapToBeatDiv28:
2341         case SnapToBeatDiv24:
2342         case SnapToBeatDiv20:
2343         case SnapToBeatDiv16:
2344         case SnapToBeatDiv14:
2345         case SnapToBeatDiv12:
2346         case SnapToBeatDiv10:
2347         case SnapToBeatDiv8:
2348         case SnapToBeatDiv7:
2349         case SnapToBeatDiv6:
2350         case SnapToBeatDiv5:
2351         case SnapToBeatDiv4:
2352         case SnapToBeatDiv3:
2353         case SnapToBeatDiv2:
2354                 compute_bbt_ruler_scale (leftmost_frame, leftmost_frame + current_page_frames());
2355                 update_tempo_based_rulers ();
2356                 break;
2357
2358         case SnapToRegionStart:
2359         case SnapToRegionEnd:
2360         case SnapToRegionSync:
2361         case SnapToRegionBoundary:
2362                 build_region_boundary_cache ();
2363                 break;
2364
2365         default:
2366                 /* relax */
2367                 break;
2368         }
2369
2370         SnapChanged (); /* EMIT SIGNAL */
2371 }
2372
2373 void
2374 Editor::set_snap_mode (SnapMode mode)
2375 {
2376         _snap_mode = mode;
2377         string str = snap_mode_strings[(int)mode];
2378
2379         if (str != snap_mode_selector.get_active_text ()) {
2380                 snap_mode_selector.set_active_text (str);
2381         }
2382
2383         instant_save ();
2384 }
2385 void
2386 Editor::set_edit_point_preference (EditPoint ep, bool force)
2387 {
2388         bool changed = (_edit_point != ep);
2389
2390         _edit_point = ep;
2391         string str = edit_point_strings[(int)ep];
2392
2393         if (str != edit_point_selector.get_active_text ()) {
2394                 edit_point_selector.set_active_text (str);
2395         }
2396
2397         set_canvas_cursor ();
2398
2399         if (!force && !changed) {
2400                 return;
2401         }
2402
2403         const char* action=NULL;
2404
2405         switch (_edit_point) {
2406         case EditAtPlayhead:
2407                 action = "edit-at-playhead";
2408                 break;
2409         case EditAtSelectedMarker:
2410                 action = "edit-at-marker";
2411                 break;
2412         case EditAtMouse:
2413                 action = "edit-at-mouse";
2414                 break;
2415         }
2416
2417         Glib::RefPtr<Action> act = ActionManager::get_action ("Editor", action);
2418         if (act) {
2419                 Glib::RefPtr<RadioAction>::cast_dynamic(act)->set_active (true);
2420         }
2421
2422         framepos_t foo;
2423         bool in_track_canvas;
2424
2425         if (!mouse_frame (foo, in_track_canvas)) {
2426                 in_track_canvas = false;
2427         }
2428
2429         reset_canvas_action_sensitivity (in_track_canvas);
2430
2431         instant_save ();
2432 }
2433
2434 int
2435 Editor::set_state (const XMLNode& node, int /*version*/)
2436 {
2437         const XMLProperty* prop;
2438         XMLNode* geometry;
2439         int x, y, xoff, yoff;
2440         Gdk::Geometry g;
2441
2442         if ((prop = node.property ("id")) != 0) {
2443                 _id = prop->value ();
2444         }
2445
2446         g.base_width = default_width;
2447         g.base_height = default_height;
2448         x = 1;
2449         y = 1;
2450         xoff = 0;
2451         yoff = 21;
2452
2453         if ((geometry = find_named_node (node, "geometry")) != 0) {
2454
2455                 XMLProperty* prop;
2456
2457                 if ((prop = geometry->property("x_size")) == 0) {
2458                         prop = geometry->property ("x-size");
2459                 }
2460                 if (prop) {
2461                         g.base_width = atoi(prop->value());
2462                 }
2463                 if ((prop = geometry->property("y_size")) == 0) {
2464                         prop = geometry->property ("y-size");
2465                 }
2466                 if (prop) {
2467                         g.base_height = atoi(prop->value());
2468                 }
2469
2470                 if ((prop = geometry->property ("x_pos")) == 0) {
2471                         prop = geometry->property ("x-pos");
2472                 }
2473                 if (prop) {
2474                         x = atoi (prop->value());
2475
2476                 }
2477                 if ((prop = geometry->property ("y_pos")) == 0) {
2478                         prop = geometry->property ("y-pos");
2479                 }
2480                 if (prop) {
2481                         y = atoi (prop->value());
2482                 }
2483
2484                 if ((prop = geometry->property ("x_off")) == 0) {
2485                         prop = geometry->property ("x-off");
2486                 }
2487                 if (prop) {
2488                         xoff = atoi (prop->value());
2489                 }
2490                 if ((prop = geometry->property ("y_off")) == 0) {
2491                         prop = geometry->property ("y-off");
2492                 }
2493                 if (prop) {
2494                         yoff = atoi (prop->value());
2495                 }
2496         }
2497
2498         set_default_size (g.base_width, g.base_height);
2499         move (x, y);
2500
2501         if (_session && (prop = node.property ("playhead"))) {
2502                 framepos_t pos;
2503                 sscanf (prop->value().c_str(), "%" PRIi64, &pos);
2504                 playhead_cursor->set_position (pos);
2505         } else {
2506                 playhead_cursor->set_position (0);
2507         }
2508         
2509         if ((prop = node.property ("mixer-width"))) {
2510                 editor_mixer_strip_width = Width (string_2_enum (prop->value(), editor_mixer_strip_width));
2511         }
2512
2513         if ((prop = node.property ("zoom-focus"))) {
2514                 set_zoom_focus ((ZoomFocus) atoi (prop->value()));
2515         }
2516
2517         if ((prop = node.property ("zoom"))) {
2518                 reset_zoom (PBD::atof (prop->value()));
2519         } else {
2520                 reset_zoom (frames_per_unit);
2521         }
2522
2523         if ((prop = node.property ("snap-to"))) {
2524                 set_snap_to ((SnapType) atoi (prop->value()));
2525         }
2526
2527         if ((prop = node.property ("snap-mode"))) {
2528                 set_snap_mode ((SnapMode) atoi (prop->value()));
2529         }
2530
2531         if ((prop = node.property ("mouse-mode"))) {
2532                 MouseMode m = str2mousemode(prop->value());
2533                 set_mouse_mode (m, true);
2534         } else {
2535                 set_mouse_mode (MouseObject, true);
2536         }
2537
2538         if ((prop = node.property ("left-frame")) != 0){
2539                 framepos_t pos;
2540                 if (sscanf (prop->value().c_str(), "%" PRId64, &pos) == 1) {
2541                         reset_x_origin (pos);
2542                 }
2543         }
2544
2545         if ((prop = node.property ("y-origin")) != 0) {
2546                 reset_y_origin (atof (prop->value ()));
2547         }
2548
2549         if ((prop = node.property ("internal-edit"))) {
2550                 bool yn = string_is_affirmative (prop->value());
2551                 RefPtr<Action> act = ActionManager::get_action (X_("MouseMode"), X_("toggle-internal-edit"));
2552                 if (act) {
2553                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2554                         tact->set_active (!yn);
2555                         tact->set_active (yn);
2556                 }
2557         }
2558
2559         if ((prop = node.property ("join-object-range"))) {
2560                 join_object_range_button.set_active (string_is_affirmative (prop->value ()));
2561         }
2562
2563         if ((prop = node.property ("edit-point"))) {
2564                 set_edit_point_preference ((EditPoint) string_2_enum (prop->value(), _edit_point), true);
2565         }
2566
2567         if ((prop = node.property ("show-measures"))) {
2568                 bool yn = string_is_affirmative (prop->value());
2569                 _show_measures = yn;
2570                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleMeasureVisibility"));
2571                 if (act) {
2572                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2573                         /* do it twice to force the change */
2574                         tact->set_active (!yn);
2575                         tact->set_active (yn);
2576                 }
2577         }
2578
2579         if ((prop = node.property ("follow-playhead"))) {
2580                 bool yn = string_is_affirmative (prop->value());
2581                 set_follow_playhead (yn);
2582                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
2583                 if (act) {
2584                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2585                         if (tact->get_active() != yn) {
2586                                 tact->set_active (yn);
2587                         }
2588                 }
2589         }
2590
2591         if ((prop = node.property ("stationary-playhead"))) {
2592                 bool yn = (prop->value() == "yes");
2593                 set_stationary_playhead (yn);
2594                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-stationary-playhead"));
2595                 if (act) {
2596                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2597                         if (tact->get_active() != yn) {
2598                                 tact->set_active (yn);
2599                         }
2600                 }
2601         }
2602         
2603         if ((prop = node.property ("region-list-sort-type"))) {
2604                 RegionListSortType st;
2605                 _regions->reset_sort_type ((RegionListSortType) string_2_enum (prop->value(), st), true);
2606         }
2607
2608         if ((prop = node.property ("xfades-visible"))) {
2609                 bool yn = string_is_affirmative (prop->value());
2610                 _xfade_visibility = !yn;
2611                 // set_xfade_visibility (yn);
2612         }
2613
2614         if ((prop = node.property ("show-editor-mixer"))) {
2615
2616                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2617                 if (act) {
2618
2619                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2620                         bool yn = string_is_affirmative (prop->value());
2621
2622                         /* do it twice to force the change */
2623
2624                         tact->set_active (!yn);
2625                         tact->set_active (yn);
2626                 }
2627         }
2628
2629         if ((prop = node.property ("show-editor-list"))) {
2630
2631                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-list"));
2632                 assert(act);
2633                 if (act) {
2634
2635                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2636                         bool yn = string_is_affirmative (prop->value());
2637
2638                         /* do it twice to force the change */
2639
2640                         tact->set_active (!yn);
2641                         tact->set_active (yn);
2642                 }
2643         }
2644
2645         if ((prop = node.property (X_("editor-list-page")))) {
2646                 the_notebook.set_current_page (atoi (prop->value ()));
2647         }
2648
2649         XMLNodeList children = node.children ();
2650         for (XMLNodeList::const_iterator i = children.begin(); i != children.end(); ++i) {
2651                 selection->set_state (**i, Stateful::current_state_version);
2652                 _regions->set_state (**i);
2653         }
2654
2655         return 0;
2656 }
2657
2658 XMLNode&
2659 Editor::get_state ()
2660 {
2661         XMLNode* node = new XMLNode ("Editor");
2662         char buf[32];
2663
2664         _id.print (buf, sizeof (buf));
2665         node->add_property ("id", buf);
2666
2667         if (is_realized()) {
2668                 Glib::RefPtr<Gdk::Window> win = get_window();
2669
2670                 int x, y, xoff, yoff, width, height;
2671                 win->get_root_origin(x, y);
2672                 win->get_position(xoff, yoff);
2673                 win->get_size(width, height);
2674
2675                 XMLNode* geometry = new XMLNode ("geometry");
2676
2677                 snprintf(buf, sizeof(buf), "%d", width);
2678                 geometry->add_property("x-size", string(buf));
2679                 snprintf(buf, sizeof(buf), "%d", height);
2680                 geometry->add_property("y-size", string(buf));
2681                 snprintf(buf, sizeof(buf), "%d", x);
2682                 geometry->add_property("x-pos", string(buf));
2683                 snprintf(buf, sizeof(buf), "%d", y);
2684                 geometry->add_property("y-pos", string(buf));
2685                 snprintf(buf, sizeof(buf), "%d", xoff);
2686                 geometry->add_property("x-off", string(buf));
2687                 snprintf(buf, sizeof(buf), "%d", yoff);
2688                 geometry->add_property("y-off", string(buf));
2689                 snprintf(buf,sizeof(buf), "%d",gtk_paned_get_position (static_cast<Paned*>(&edit_pane)->gobj()));
2690                 geometry->add_property("edit-horizontal-pane-pos", string(buf));
2691                 snprintf(buf,sizeof(buf), "%d",gtk_paned_get_position (static_cast<Paned*>(&editor_summary_pane)->gobj()));
2692                 geometry->add_property("edit-vertical-pane-pos", string(buf));
2693
2694                 node->add_child_nocopy (*geometry);
2695         }
2696
2697         maybe_add_mixer_strip_width (*node);
2698
2699         snprintf (buf, sizeof(buf), "%d", (int) zoom_focus);
2700         node->add_property ("zoom-focus", buf);
2701         snprintf (buf, sizeof(buf), "%f", frames_per_unit);
2702         node->add_property ("zoom", buf);
2703         snprintf (buf, sizeof(buf), "%d", (int) _snap_type);
2704         node->add_property ("snap-to", buf);
2705         snprintf (buf, sizeof(buf), "%d", (int) _snap_mode);
2706         node->add_property ("snap-mode", buf);
2707
2708         node->add_property ("edit-point", enum_2_string (_edit_point));
2709
2710         snprintf (buf, sizeof (buf), "%" PRIi64, playhead_cursor->current_frame);
2711         node->add_property ("playhead", buf);
2712         snprintf (buf, sizeof (buf), "%" PRIi64, leftmost_frame);
2713         node->add_property ("left-frame", buf);
2714         snprintf (buf, sizeof (buf), "%f", vertical_adjustment.get_value ());
2715         node->add_property ("y-origin", buf);
2716
2717         node->add_property ("show-measures", _show_measures ? "yes" : "no");
2718         node->add_property ("follow-playhead", _follow_playhead ? "yes" : "no");
2719         node->add_property ("stationary-playhead", _stationary_playhead ? "yes" : "no");
2720         node->add_property ("xfades-visible", _xfade_visibility ? "yes" : "no");
2721         node->add_property ("region-list-sort-type", enum_2_string (_regions->sort_type ()));
2722         node->add_property ("mouse-mode", enum2str(mouse_mode));
2723         node->add_property ("internal-edit", _internal_editing ? "yes" : "no");
2724         node->add_property ("join-object-range", join_object_range_button.get_active () ? "yes" : "no");
2725
2726         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2727         if (act) {
2728                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2729                 node->add_property (X_("show-editor-mixer"), tact->get_active() ? "yes" : "no");
2730         }
2731
2732         act = ActionManager::get_action (X_("Editor"), X_("show-editor-list"));
2733         if (act) {
2734                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2735                 node->add_property (X_("show-editor-list"), tact->get_active() ? "yes" : "no");
2736         }
2737
2738         snprintf (buf, sizeof (buf), "%d", the_notebook.get_current_page ());
2739         node->add_property (X_("editor-list-page"), buf);
2740
2741         node->add_child_nocopy (selection->get_state ());
2742         node->add_child_nocopy (_regions->get_state ());
2743         
2744         return *node;
2745 }
2746
2747
2748
2749 /** @param y y offset from the top of all trackviews.
2750  *  @return pair: TimeAxisView that y is over, layer index.
2751  *  TimeAxisView may be 0.  Layer index is the layer number if the TimeAxisView is valid and is
2752  *  in stacked region display mode, otherwise 0.
2753  */
2754 std::pair<TimeAxisView *, layer_t>
2755 Editor::trackview_by_y_position (double y)
2756 {
2757         for (TrackViewList::iterator iter = track_views.begin(); iter != track_views.end(); ++iter) {
2758
2759                 std::pair<TimeAxisView*, int> const r = (*iter)->covers_y_position (y);
2760                 if (r.first) {
2761                         return r;
2762                 }
2763         }
2764
2765         return std::make_pair ( (TimeAxisView *) 0, 0);
2766 }
2767
2768 /** Snap a position to the grid, if appropriate, taking into account current
2769  *  grid settings and also the state of any snap modifier keys that may be pressed.
2770  *  @param start Position to snap.
2771  *  @param event Event to get current key modifier information from, or 0.
2772  */
2773 void
2774 Editor::snap_to_with_modifier (framepos_t& start, GdkEvent const * event, int32_t direction, bool for_mark)
2775 {
2776         if (!_session || !event) {
2777                 return;
2778         }
2779
2780         if (Keyboard::modifier_state_contains (event->button.state, Keyboard::snap_modifier())) {
2781                 if (_snap_mode == SnapOff) {
2782                         snap_to_internal (start, direction, for_mark);
2783                 }
2784         } else {
2785                 if (_snap_mode != SnapOff) {
2786                         snap_to_internal (start, direction, for_mark);
2787                 }
2788         }
2789 }
2790
2791 void
2792 Editor::snap_to (framepos_t& start, int32_t direction, bool for_mark)
2793 {
2794         if (!_session || _snap_mode == SnapOff) {
2795                 return;
2796         }
2797
2798         snap_to_internal (start, direction, for_mark);
2799 }
2800
2801 void
2802 Editor::timecode_snap_to_internal (framepos_t& start, int32_t direction, bool /*for_mark*/)
2803 {
2804         const framepos_t one_timecode_second = (framepos_t)(rint(_session->timecode_frames_per_second()) * _session->frames_per_timecode_frame());
2805         framepos_t one_timecode_minute = (framepos_t)(rint(_session->timecode_frames_per_second()) * _session->frames_per_timecode_frame() * 60);
2806
2807         switch (_snap_type) {
2808         case SnapToTimecodeFrame:
2809                 if (((direction == 0) && (fmod((double)start, (double)_session->frames_per_timecode_frame()) > (_session->frames_per_timecode_frame() / 2))) || (direction > 0)) {
2810                         start = (framepos_t) (ceil ((double) start / _session->frames_per_timecode_frame()) * _session->frames_per_timecode_frame());
2811                 } else {
2812                         start = (framepos_t) (floor ((double) start / _session->frames_per_timecode_frame()) *  _session->frames_per_timecode_frame());
2813                 }
2814                 break;
2815
2816         case SnapToTimecodeSeconds:
2817                 if (_session->timecode_offset_negative())
2818                 {
2819                         start += _session->timecode_offset ();
2820                 } else {
2821                         start -= _session->timecode_offset ();
2822                 }
2823                 if (((direction == 0) && (start % one_timecode_second > one_timecode_second / 2)) || direction > 0) {
2824                         start = (framepos_t) ceil ((double) start / one_timecode_second) * one_timecode_second;
2825                 } else {
2826                         start = (framepos_t) floor ((double) start / one_timecode_second) * one_timecode_second;
2827                 }
2828
2829                 if (_session->timecode_offset_negative())
2830                 {
2831                         start -= _session->timecode_offset ();
2832                 } else {
2833                         start += _session->timecode_offset ();
2834                 }
2835                 break;
2836
2837         case SnapToTimecodeMinutes:
2838                 if (_session->timecode_offset_negative())
2839                 {
2840                         start += _session->timecode_offset ();
2841                 } else {
2842                         start -= _session->timecode_offset ();
2843                 }
2844                 if (((direction == 0) && (start % one_timecode_minute > one_timecode_minute / 2)) || direction > 0) {
2845                         start = (framepos_t) ceil ((double) start / one_timecode_minute) * one_timecode_minute;
2846                 } else {
2847                         start = (framepos_t) floor ((double) start / one_timecode_minute) * one_timecode_minute;
2848                 }
2849                 if (_session->timecode_offset_negative())
2850                 {
2851                         start -= _session->timecode_offset ();
2852                 } else {
2853                         start += _session->timecode_offset ();
2854                 }
2855                 break;
2856         default:
2857                 fatal << "Editor::smpte_snap_to_internal() called with non-timecode snap type!" << endmsg;
2858                 /*NOTREACHED*/
2859         }
2860 }
2861
2862 void
2863 Editor::snap_to_internal (framepos_t& start, int32_t direction, bool for_mark)
2864 {
2865         const framepos_t one_second = _session->frame_rate();
2866         const framepos_t one_minute = _session->frame_rate() * 60;
2867         framepos_t presnap = start;
2868         framepos_t before;
2869         framepos_t after;
2870
2871         switch (_snap_type) {
2872         case SnapToTimecodeFrame:
2873         case SnapToTimecodeSeconds:
2874         case SnapToTimecodeMinutes:
2875                 return timecode_snap_to_internal (start, direction, for_mark);
2876
2877         case SnapToCDFrame:
2878                 if (((direction == 0) && (start % (one_second/75) > (one_second/75) / 2)) || (direction > 0)) {
2879                         start = (framepos_t) ceil ((double) start / (one_second / 75)) * (one_second / 75);
2880                 } else {
2881                         start = (framepos_t) floor ((double) start / (one_second / 75)) * (one_second / 75);
2882                 }
2883                 break;
2884
2885         case SnapToSeconds:
2886                 if (((direction == 0) && (start % one_second > one_second / 2)) || (direction > 0)) {
2887                         start = (framepos_t) ceil ((double) start / one_second) * one_second;
2888                 } else {
2889                         start = (framepos_t) floor ((double) start / one_second) * one_second;
2890                 }
2891                 break;
2892
2893         case SnapToMinutes:
2894                 if (((direction == 0) && (start % one_minute > one_minute / 2)) || (direction > 0)) {
2895                         start = (framepos_t) ceil ((double) start / one_minute) * one_minute;
2896                 } else {
2897                         start = (framepos_t) floor ((double) start / one_minute) * one_minute;
2898                 }
2899                 break;
2900
2901         case SnapToBar:
2902                 start = _session->tempo_map().round_to_bar (start, direction);
2903                 break;
2904
2905         case SnapToBeat:
2906                 start = _session->tempo_map().round_to_beat (start, direction);
2907                 break;
2908
2909         case SnapToBeatDiv32:
2910                 start = _session->tempo_map().round_to_beat_subdivision (start, 32, direction);
2911                 break;
2912         case SnapToBeatDiv28:
2913                 start = _session->tempo_map().round_to_beat_subdivision (start, 28, direction);
2914                 break;
2915         case SnapToBeatDiv24:
2916                 start = _session->tempo_map().round_to_beat_subdivision (start, 24, direction);
2917                 break;
2918         case SnapToBeatDiv20:
2919                 start = _session->tempo_map().round_to_beat_subdivision (start, 20, direction);
2920                 break;
2921         case SnapToBeatDiv16:
2922                 start = _session->tempo_map().round_to_beat_subdivision (start, 16, direction);
2923                 break;
2924         case SnapToBeatDiv14:
2925                 start = _session->tempo_map().round_to_beat_subdivision (start, 14, direction);
2926                 break;
2927         case SnapToBeatDiv12:
2928                 start = _session->tempo_map().round_to_beat_subdivision (start, 12, direction);
2929                 break;
2930         case SnapToBeatDiv10:
2931                 start = _session->tempo_map().round_to_beat_subdivision (start, 10, direction);
2932                 break;
2933         case SnapToBeatDiv8:
2934                 start = _session->tempo_map().round_to_beat_subdivision (start, 8, direction);
2935                 break;
2936         case SnapToBeatDiv7:
2937                 start = _session->tempo_map().round_to_beat_subdivision (start, 7, direction);
2938                 break;
2939         case SnapToBeatDiv6:
2940                 start = _session->tempo_map().round_to_beat_subdivision (start, 6, direction);
2941                 break;
2942         case SnapToBeatDiv5:
2943                 start = _session->tempo_map().round_to_beat_subdivision (start, 5, direction);
2944                 break;
2945         case SnapToBeatDiv4:
2946                 start = _session->tempo_map().round_to_beat_subdivision (start, 4, direction);
2947                 break;
2948         case SnapToBeatDiv3:
2949                 start = _session->tempo_map().round_to_beat_subdivision (start, 3, direction);
2950                 break;
2951         case SnapToBeatDiv2:
2952                 start = _session->tempo_map().round_to_beat_subdivision (start, 2, direction);
2953                 break;
2954
2955         case SnapToMark:
2956                 if (for_mark) {
2957                         return;
2958                 }
2959
2960                 _session->locations()->marks_either_side (start, before, after);
2961
2962                 if (before == max_framepos) {
2963                         start = after;
2964                 } else if (after == max_framepos) {
2965                         start = before;
2966                 } else if (before != max_framepos && after != max_framepos) {
2967                         /* have before and after */
2968                         if ((start - before) < (after - start)) {
2969                                 start = before;
2970                         } else {
2971                                 start = after;
2972                         }
2973                 }
2974
2975                 break;
2976
2977         case SnapToRegionStart:
2978         case SnapToRegionEnd:
2979         case SnapToRegionSync:
2980         case SnapToRegionBoundary:
2981                 if (!region_boundary_cache.empty()) {
2982
2983                         vector<framepos_t>::iterator prev = region_boundary_cache.end ();
2984                         vector<framepos_t>::iterator next = region_boundary_cache.end ();
2985
2986                         if (direction > 0) {
2987                                 next = std::upper_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2988                         } else {
2989                                 next = std::lower_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2990                         }
2991
2992                         if (next != region_boundary_cache.begin ()) {
2993                                 prev = next;
2994                                 prev--;
2995                         }
2996
2997                         framepos_t const p = (prev == region_boundary_cache.end()) ? region_boundary_cache.front () : *prev;
2998                         framepos_t const n = (next == region_boundary_cache.end()) ? region_boundary_cache.back () : *next;
2999
3000                         if (start > (p + n) / 2) {
3001                                 start = n;
3002                         } else {
3003                                 start = p;
3004                         }
3005                 }
3006                 break;
3007         }
3008
3009         switch (_snap_mode) {
3010         case SnapNormal:
3011                 return;
3012
3013         case SnapMagnetic:
3014
3015                 if (presnap > start) {
3016                         if (presnap > (start + unit_to_frame(snap_threshold))) {
3017                                 start = presnap;
3018                         }
3019
3020                 } else if (presnap < start) {
3021                         if (presnap < (start - unit_to_frame(snap_threshold))) {
3022                                 start = presnap;
3023                         }
3024                 }
3025
3026         default:
3027                 /* handled at entry */
3028                 return;
3029
3030         }
3031 }
3032
3033
3034 void
3035 Editor::setup_toolbar ()
3036 {
3037         string pixmap_path;
3038
3039         /* Mode Buttons (tool selection) */
3040
3041         mouse_move_button.set_relief(Gtk::RELIEF_NONE);
3042         mouse_select_button.set_relief(Gtk::RELIEF_NONE);
3043         mouse_gain_button.set_relief(Gtk::RELIEF_NONE);
3044         mouse_zoom_button.set_relief(Gtk::RELIEF_NONE);
3045         mouse_timefx_button.set_relief(Gtk::RELIEF_NONE);
3046         mouse_audition_button.set_relief(Gtk::RELIEF_NONE);
3047         // internal_edit_button.set_relief(Gtk::RELIEF_NONE);
3048         join_object_range_button.set_relief(Gtk::RELIEF_NONE);
3049
3050         HBox* mode_box = manage(new HBox);
3051         mode_box->set_border_width (2);
3052         mode_box->set_spacing(4);
3053
3054         /* table containing mode buttons */
3055
3056         HBox* mouse_mode_button_box = manage (new HBox ());
3057
3058         if (Profile->get_sae()) {
3059                 mouse_mode_button_box->pack_start (mouse_move_button);
3060         } else {
3061                 mouse_mode_button_box->pack_start (mouse_move_button);
3062                 mouse_mode_button_box->pack_start (join_object_range_button);
3063                 mouse_mode_button_box->pack_start (mouse_select_button);
3064         }
3065
3066         mouse_mode_button_box->pack_start (mouse_zoom_button);
3067
3068         if (!Profile->get_sae()) {
3069                 mouse_mode_button_box->pack_start (mouse_gain_button);
3070         }
3071
3072         mouse_mode_button_box->pack_start (mouse_timefx_button);
3073         mouse_mode_button_box->pack_start (mouse_audition_button);
3074         mouse_mode_button_box->pack_start (internal_edit_button);
3075
3076         vector<string> edit_mode_strings;
3077         edit_mode_strings.push_back (edit_mode_to_string (Slide));
3078         if (!Profile->get_sae()) {
3079                 edit_mode_strings.push_back (edit_mode_to_string (Splice));
3080         }
3081         edit_mode_strings.push_back (edit_mode_to_string (Lock));
3082
3083         edit_mode_selector.set_name ("EditModeSelector");
3084         set_popdown_strings (edit_mode_selector, edit_mode_strings, true);
3085         edit_mode_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::edit_mode_selection_done));
3086
3087         mode_box->pack_start (edit_mode_selector);
3088         mode_box->pack_start (*mouse_mode_button_box);
3089
3090         _mouse_mode_tearoff = manage (new TearOff (*mode_box));
3091         _mouse_mode_tearoff->set_name ("MouseModeBase");
3092         _mouse_mode_tearoff->tearoff_window().signal_key_press_event().connect (sigc::bind (sigc::ptr_fun (relay_key_press), &_mouse_mode_tearoff->tearoff_window()), false);
3093
3094         if (Profile->get_sae()) {
3095                 _mouse_mode_tearoff->set_can_be_torn_off (false);
3096         }
3097
3098         _mouse_mode_tearoff->Detach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
3099                                                          &_mouse_mode_tearoff->tearoff_window()));
3100         _mouse_mode_tearoff->Attach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3101                                                          &_mouse_mode_tearoff->tearoff_window(), 1));
3102         _mouse_mode_tearoff->Hidden.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
3103                                                          &_mouse_mode_tearoff->tearoff_window()));
3104         _mouse_mode_tearoff->Visible.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3105                                                           &_mouse_mode_tearoff->tearoff_window(), 1));
3106
3107         mouse_move_button.set_mode (false);
3108         mouse_select_button.set_mode (false);
3109         mouse_gain_button.set_mode (false);
3110         mouse_zoom_button.set_mode (false);
3111         mouse_timefx_button.set_mode (false);
3112         mouse_audition_button.set_mode (false);
3113         join_object_range_button.set_mode (false);
3114
3115         mouse_move_button.set_name ("MouseModeButton");
3116         mouse_select_button.set_name ("MouseModeButton");
3117         mouse_gain_button.set_name ("MouseModeButton");
3118         mouse_zoom_button.set_name ("MouseModeButton");
3119         mouse_timefx_button.set_name ("MouseModeButton");
3120         mouse_audition_button.set_name ("MouseModeButton");
3121         internal_edit_button.set_name ("MouseModeButton");
3122         join_object_range_button.set_name ("MouseModeButton");
3123
3124         mouse_move_button.unset_flags (CAN_FOCUS);
3125         mouse_select_button.unset_flags (CAN_FOCUS);
3126         mouse_gain_button.unset_flags (CAN_FOCUS);
3127         mouse_zoom_button.unset_flags (CAN_FOCUS);
3128         mouse_timefx_button.unset_flags (CAN_FOCUS);
3129         mouse_audition_button.unset_flags (CAN_FOCUS);
3130         internal_edit_button.unset_flags (CAN_FOCUS);
3131         join_object_range_button.unset_flags (CAN_FOCUS);
3132
3133         /* Zoom */
3134
3135         _zoom_box.set_spacing (1);
3136         _zoom_box.set_border_width (0);
3137
3138         zoom_in_button.set_name ("EditorTimeButton");
3139         zoom_in_button.set_image (*(manage (new Image (Stock::ZOOM_IN, Gtk::ICON_SIZE_MENU))));
3140         zoom_in_button.signal_clicked().connect (sigc::bind (sigc::mem_fun(*this, &Editor::temporal_zoom_step), false));
3141
3142         zoom_out_button.set_name ("EditorTimeButton");
3143         zoom_out_button.set_image (*(manage (new Image (Stock::ZOOM_OUT, Gtk::ICON_SIZE_MENU))));
3144         zoom_out_button.signal_clicked().connect (sigc::bind (sigc::mem_fun(*this, &Editor::temporal_zoom_step), true));
3145
3146         zoom_out_full_button.set_name ("EditorTimeButton");
3147         zoom_out_full_button.set_image (*(manage (new Image (Stock::ZOOM_100, Gtk::ICON_SIZE_MENU))));
3148         zoom_out_full_button.signal_clicked().connect (sigc::mem_fun(*this, &Editor::temporal_zoom_session));
3149
3150         zoom_focus_selector.set_name ("ZoomFocusSelector");
3151         set_popdown_strings (zoom_focus_selector, zoom_focus_strings, true);
3152         zoom_focus_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::zoom_focus_selection_done));
3153
3154         _zoom_box.pack_start (zoom_out_button, false, false);
3155         _zoom_box.pack_start (zoom_in_button, false, false);
3156         _zoom_box.pack_start (zoom_out_full_button, false, false);
3157
3158         _zoom_box.pack_start (zoom_focus_selector);
3159         
3160         /* Track zoom buttons */
3161         tav_expand_button.set_name ("TrackHeightButton");
3162         tav_expand_button.set_size_request(-1,20);
3163         tav_expand_button.add (*(manage (new Image (::get_icon("tav_exp")))));
3164         tav_expand_button.signal_clicked().connect (sigc::bind (sigc::mem_fun(*this, &Editor::tav_zoom_step), true));
3165
3166         tav_shrink_button.set_name ("TrackHeightButton");
3167         tav_shrink_button.set_size_request(-1,20);
3168         tav_shrink_button.add (*(manage (new Image (::get_icon("tav_shrink")))));
3169         tav_shrink_button.signal_clicked().connect (sigc::bind (sigc::mem_fun(*this, &Editor::tav_zoom_step), false));
3170
3171         _zoom_box.pack_start (tav_shrink_button);
3172         _zoom_box.pack_start (tav_expand_button);
3173         
3174         _zoom_tearoff = manage (new TearOff (_zoom_box));
3175
3176         _zoom_tearoff->Detach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
3177                                                    &_zoom_tearoff->tearoff_window()));
3178         _zoom_tearoff->Attach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3179                                                    &_zoom_tearoff->tearoff_window(), 0));
3180         _zoom_tearoff->Hidden.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
3181                                                    &_zoom_tearoff->tearoff_window()));
3182         _zoom_tearoff->Visible.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3183                                                     &_zoom_tearoff->tearoff_window(), 0));
3184         
3185         snap_box.set_spacing (1);
3186         snap_box.set_border_width (2);
3187
3188         snap_type_selector.set_name ("SnapTypeSelector");
3189         set_popdown_strings (snap_type_selector, snap_type_strings, true);
3190         snap_type_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::snap_type_selection_done));
3191
3192         snap_mode_selector.set_name ("SnapModeSelector");
3193         set_popdown_strings (snap_mode_selector, snap_mode_strings, true);
3194         snap_mode_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::snap_mode_selection_done));
3195
3196         edit_point_selector.set_name ("EditPointSelector");
3197         set_popdown_strings (edit_point_selector, edit_point_strings, true);
3198         edit_point_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::edit_point_selection_done));
3199
3200         snap_box.pack_start (snap_mode_selector, false, false);
3201         snap_box.pack_start (snap_type_selector, false, false);
3202         snap_box.pack_start (edit_point_selector, false, false);
3203
3204         /* Nudge */
3205
3206         HBox *nudge_box = manage (new HBox);
3207         nudge_box->set_spacing(1);
3208         nudge_box->set_border_width (2);
3209
3210         nudge_forward_button.signal_button_release_event().connect (sigc::mem_fun(*this, &Editor::nudge_forward_release), false);
3211         nudge_backward_button.signal_button_release_event().connect (sigc::mem_fun(*this, &Editor::nudge_backward_release), false);
3212
3213         nudge_box->pack_start (nudge_backward_button, false, false);
3214         nudge_box->pack_start (nudge_forward_button, false, false);
3215         nudge_box->pack_start (nudge_clock, false, false);
3216
3217
3218         /* Pack everything in... */
3219
3220         HBox* hbox = manage (new HBox);
3221         hbox->set_spacing(10);
3222
3223         _tools_tearoff = manage (new TearOff (*hbox));
3224         _tools_tearoff->set_name ("MouseModeBase");
3225         _tools_tearoff->tearoff_window().signal_key_press_event().connect (sigc::bind (sigc::ptr_fun (relay_key_press), &_tools_tearoff->tearoff_window()), false);
3226         
3227         if (Profile->get_sae()) {
3228                 _tools_tearoff->set_can_be_torn_off (false);
3229         }
3230
3231         _tools_tearoff->Detach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
3232                                                     &_tools_tearoff->tearoff_window()));
3233         _tools_tearoff->Attach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3234                                                     &_tools_tearoff->tearoff_window(), 0));
3235         _tools_tearoff->Hidden.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
3236                                                     &_tools_tearoff->tearoff_window()));
3237         _tools_tearoff->Visible.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3238                                                      &_tools_tearoff->tearoff_window(), 0));
3239
3240         toolbar_hbox.set_spacing (10);
3241         toolbar_hbox.set_border_width (1);
3242
3243         toolbar_hbox.pack_start (*_mouse_mode_tearoff, false, false);
3244         toolbar_hbox.pack_start (*_zoom_tearoff, false, false);
3245         toolbar_hbox.pack_start (*_tools_tearoff, false, false);
3246
3247         hbox->pack_start (snap_box, false, false);
3248         hbox->pack_start (*nudge_box, false, false);
3249         hbox->pack_start (panic_box, false, false);
3250
3251         hbox->show_all ();
3252
3253         toolbar_base.set_name ("ToolBarBase");
3254         toolbar_base.add (toolbar_hbox);
3255
3256         toolbar_frame.set_shadow_type (SHADOW_OUT);
3257         toolbar_frame.set_name ("BaseFrame");
3258         toolbar_frame.add (toolbar_base);
3259 }
3260
3261 void
3262 Editor::setup_tooltips ()
3263 {
3264         ARDOUR_UI::instance()->set_tip (mouse_move_button, _("Select/Move Objects"));
3265         ARDOUR_UI::instance()->set_tip (mouse_gain_button, _("Draw Region Gain"));
3266         ARDOUR_UI::instance()->set_tip (mouse_zoom_button, _("Select Zoom Range"));
3267         ARDOUR_UI::instance()->set_tip (mouse_timefx_button, _("Stretch/Shrink Regions and MIDI Notes"));
3268         ARDOUR_UI::instance()->set_tip (mouse_audition_button, _("Listen to Specific Regions"));
3269         ARDOUR_UI::instance()->set_tip (join_object_range_button, _("Select/Move Objects or Ranges"));
3270         ARDOUR_UI::instance()->set_tip (internal_edit_button, _("Edit Region Contents (e.g. notes)"));
3271         ARDOUR_UI::instance()->set_tip (*_group_tabs, _("Groups: context-click for possible operations"));
3272         ARDOUR_UI::instance()->set_tip (nudge_forward_button, _("Nudge Region/Selection Forwards"));
3273         ARDOUR_UI::instance()->set_tip (nudge_backward_button, _("Nudge Region/Selection Backwards"));
3274         ARDOUR_UI::instance()->set_tip (zoom_in_button, _("Zoom In"));
3275         ARDOUR_UI::instance()->set_tip (zoom_out_button, _("Zoom Out"));
3276         ARDOUR_UI::instance()->set_tip (zoom_out_full_button, _("Zoom to Session"));
3277         ARDOUR_UI::instance()->set_tip (zoom_focus_selector, _("Zoom focus"));
3278         ARDOUR_UI::instance()->set_tip (tav_expand_button, _("Expand Tracks"));
3279         ARDOUR_UI::instance()->set_tip (tav_shrink_button, _("Shrink Tracks"));
3280         ARDOUR_UI::instance()->set_tip (snap_type_selector, _("Snap/Grid Units"));
3281         ARDOUR_UI::instance()->set_tip (snap_mode_selector, _("Snap/Grid Mode"));
3282         ARDOUR_UI::instance()->set_tip (edit_point_selector, _("Edit point"));
3283         ARDOUR_UI::instance()->set_tip (midi_sound_notes, _("Sound Notes"));
3284         ARDOUR_UI::instance()->set_tip (midi_panic_button, _("Send note off and reset controller messages on all MIDI channels"));
3285         ARDOUR_UI::instance()->set_tip (edit_mode_selector, _("Edit Mode"));
3286 }
3287
3288 void
3289 Editor::midi_panic ()
3290 {
3291         cerr << "MIDI panic\n";
3292
3293         if (_session) {
3294                 _session->midi_panic();
3295         }
3296 }
3297
3298 void
3299 Editor::setup_midi_toolbar ()
3300 {
3301         RefPtr<Action> act;
3302
3303         /* Midi sound notes */
3304         midi_sound_notes.add (*(manage (new Image (::get_icon("midi_sound_notes")))));
3305         midi_sound_notes.set_relief(Gtk::RELIEF_NONE);
3306         midi_sound_notes.unset_flags (CAN_FOCUS);
3307
3308         /* Panic */
3309
3310         act = ActionManager::get_action (X_("MIDI"), X_("panic"));
3311         midi_panic_button.set_name("MidiPanicButton");
3312         act->connect_proxy (midi_panic_button);
3313
3314         panic_box.pack_start (midi_sound_notes , true, true);
3315         panic_box.pack_start (midi_panic_button, true, true);
3316 }
3317
3318 int
3319 Editor::convert_drop_to_paths (
3320                 vector<string>&                paths,
3321                 const RefPtr<Gdk::DragContext>& /*context*/,
3322                 gint                            /*x*/,
3323                 gint                            /*y*/,
3324                 const SelectionData&            data,
3325                 guint                           /*info*/,
3326                 guint                           /*time*/)
3327 {
3328         if (_session == 0) {
3329                 return -1;
3330         }
3331         
3332         vector<string> uris = data.get_uris();
3333
3334         if (uris.empty()) {
3335
3336                 /* This is seriously fucked up. Nautilus doesn't say that its URI lists
3337                    are actually URI lists. So do it by hand.
3338                 */
3339
3340                 if (data.get_target() != "text/plain") {
3341                         return -1;
3342                 }
3343
3344                 /* Parse the "uri-list" format that Nautilus provides,
3345                    where each pathname is delimited by \r\n.
3346
3347                    THERE MAY BE NO NULL TERMINATING CHAR!!!
3348                 */
3349
3350                 string txt = data.get_text();
3351                 const char* p;
3352                 const char* q;
3353
3354                 p = (const char *) malloc (txt.length() + 1);
3355                 txt.copy ((char *) p, txt.length(), 0);
3356                 ((char*)p)[txt.length()] = '\0';
3357
3358                 while (p)
3359                 {
3360                         if (*p != '#')
3361                         {
3362                                 while (g_ascii_isspace (*p))
3363                                         p++;
3364
3365                                 q = p;
3366                                 while (*q && (*q != '\n') && (*q != '\r')) {
3367                                         q++;
3368                                 }
3369
3370                                 if (q > p)
3371                                 {
3372                                         q--;
3373                                         while (q > p && g_ascii_isspace (*q))
3374                                                 q--;
3375
3376                                         if (q > p)
3377                                         {
3378                                                 uris.push_back (string (p, q - p + 1));
3379                                         }
3380                                 }
3381                         }
3382                         p = strchr (p, '\n');
3383                         if (p)
3384                                 p++;
3385                 }
3386
3387                 free ((void*)p);
3388
3389                 if (uris.empty()) {
3390                         return -1;
3391                 }
3392         }
3393
3394         for (vector<string>::iterator i = uris.begin(); i != uris.end(); ++i) {
3395
3396                 if ((*i).substr (0,7) == "file://") {
3397
3398                         string p = *i;
3399                         PBD::url_decode (p);
3400
3401                         // scan forward past three slashes
3402
3403                         string::size_type slashcnt = 0;
3404                         string::size_type n = 0;
3405                         string::iterator x = p.begin();
3406
3407                         while (slashcnt < 3 && x != p.end()) {
3408                                 if ((*x) == '/') {
3409                                         slashcnt++;
3410                                 } else if (slashcnt == 3) {
3411                                         break;
3412                                 }
3413                                 ++n;
3414                                 ++x;
3415                         }
3416
3417                         if (slashcnt != 3 || x == p.end()) {
3418                                 error << _("malformed URL passed to drag-n-drop code") << endmsg;
3419                                 continue;
3420                         }
3421
3422                         paths.push_back (p.substr (n - 1));
3423                 }
3424         }
3425
3426         return 0;
3427 }
3428
3429 void
3430 Editor::new_tempo_section ()
3431
3432 {
3433 }
3434
3435 void
3436 Editor::map_transport_state ()
3437 {
3438         ENSURE_GUI_THREAD (*this, &Editor::map_transport_state)
3439
3440         if (_session && _session->transport_stopped()) {
3441                 have_pending_keyboard_selection = false;
3442         }
3443
3444         update_loop_range_view (true);
3445 }
3446
3447 /* UNDO/REDO */
3448
3449 Editor::State::State (PublicEditor const * e)
3450 {
3451         selection = new Selection (e);
3452 }
3453
3454 Editor::State::~State ()
3455 {
3456         delete selection;
3457 }
3458
3459 void
3460 Editor::begin_reversible_command (string name)
3461 {
3462         if (_session) {
3463                 _session->begin_reversible_command (name);
3464         }
3465 }
3466
3467 void
3468 Editor::commit_reversible_command ()
3469 {
3470         if (_session) {
3471                 _session->commit_reversible_command ();
3472         }
3473 }
3474
3475 void
3476 Editor::set_route_group_solo (Route& route, bool yn)
3477 {
3478         RouteGroup *route_group;
3479
3480         if ((route_group = route.route_group()) != 0) {
3481                 route_group->apply (&Route::set_solo, yn, this);
3482         } else {
3483                 route.set_solo (yn, this);
3484         }
3485 }
3486
3487 void
3488 Editor::set_route_group_mute (Route& route, bool yn)
3489 {
3490         RouteGroup *route_group = 0;
3491
3492         if ((route_group = route.route_group()) != 0) {
3493                 route_group->apply (&Route::set_mute, yn, this);
3494         } else {
3495                 route.set_mute (yn, this);
3496         }
3497 }
3498
3499 void
3500 Editor::history_changed ()
3501 {
3502         string label;
3503
3504         if (undo_action && _session) {
3505                 if (_session->undo_depth() == 0) {
3506                         label = _("Undo");
3507                 } else {
3508                         label = string_compose(_("Undo (%1)"), _session->next_undo());
3509                 }
3510                 undo_action->property_label() = label;
3511         }
3512
3513         if (redo_action && _session) {
3514                 if (_session->redo_depth() == 0) {
3515                         label = _("Redo");
3516                 } else {
3517                         label = string_compose(_("Redo (%1)"), _session->next_redo());
3518                 }
3519                 redo_action->property_label() = label;
3520         }
3521 }
3522
3523 void
3524 Editor::duplicate_dialog (bool with_dialog)
3525 {
3526         float times = 1.0f;
3527
3528         if (mouse_mode == MouseRange) {
3529                 if (selection->time.length() == 0) {
3530                         return;
3531                 }
3532         }
3533
3534         RegionSelection rs;
3535         get_regions_for_action (rs);
3536
3537         if (mouse_mode != MouseRange) {
3538
3539                 if (rs.empty()) {
3540                         return;
3541                 }
3542         }
3543
3544         if (with_dialog) {
3545
3546                 ArdourDialog win (_("Duplicate"));
3547                 Label label (_("Number of duplications:"));
3548                 Adjustment adjustment (1.0, 1.0, 1000000.0, 1.0, 5.0);
3549                 SpinButton spinner (adjustment, 0.0, 1);
3550                 HBox hbox;
3551
3552                 win.get_vbox()->set_spacing (12);
3553                 win.get_vbox()->pack_start (hbox);
3554                 hbox.set_border_width (6);
3555                 hbox.pack_start (label, PACK_EXPAND_PADDING, 12);
3556
3557                 /* dialogs have ::add_action_widget() but that puts the spinner in the wrong
3558                    place, visually. so do this by hand.
3559                 */
3560
3561                 hbox.pack_start (spinner, PACK_EXPAND_PADDING, 12);
3562                 spinner.signal_activate().connect (sigc::bind (sigc::mem_fun (win, &ArdourDialog::response), RESPONSE_ACCEPT));
3563                 spinner.grab_focus();
3564
3565                 hbox.show ();
3566                 label.show ();
3567                 spinner.show ();
3568
3569                 win.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3570                 win.add_button (_("Duplicate"), RESPONSE_ACCEPT);
3571                 win.set_default_response (RESPONSE_ACCEPT);
3572
3573                 win.set_position (WIN_POS_MOUSE);
3574
3575                 spinner.grab_focus ();
3576
3577                 switch (win.run ()) {
3578                 case RESPONSE_ACCEPT:
3579                         break;
3580                 default:
3581                         return;
3582                 }
3583
3584                 times = adjustment.get_value();
3585         }
3586
3587         if (mouse_mode == MouseRange) {
3588                 duplicate_selection (times);
3589         } else {
3590                 duplicate_some_regions (rs, times);
3591         }
3592 }
3593
3594 void
3595 Editor::show_verbose_canvas_cursor ()
3596 {
3597         verbose_canvas_cursor->raise_to_top();
3598         verbose_canvas_cursor->show();
3599         verbose_cursor_visible = true;
3600 }
3601
3602 void
3603 Editor::hide_verbose_canvas_cursor ()
3604 {
3605         verbose_canvas_cursor->hide();
3606         verbose_cursor_visible = false;
3607 }
3608
3609 double
3610 Editor::clamp_verbose_cursor_x (double x)
3611 {
3612         if (x < 0) {
3613                 x = 0;
3614         } else {
3615                 x = min (_canvas_width - 200.0, x);
3616         }
3617         return x;
3618 }
3619
3620 double
3621 Editor::clamp_verbose_cursor_y (double y)
3622 {
3623         if (y < canvas_timebars_vsize) {
3624                 y = canvas_timebars_vsize;
3625         } else {
3626                 y = min (_canvas_height - 50, y);
3627         }
3628         return y;
3629 }
3630
3631 void
3632 Editor::show_verbose_canvas_cursor_with (const string & txt, int32_t xoffset, int32_t yoffset)
3633 {
3634         verbose_canvas_cursor->property_text() = txt.c_str();
3635
3636         int x, y;
3637         double wx, wy;
3638
3639         track_canvas->get_pointer (x, y);
3640         track_canvas->window_to_world (x, y, wx, wy);
3641
3642         wx += xoffset;
3643         wy += yoffset;
3644
3645         /* don't get too close to the edge */
3646         verbose_canvas_cursor->property_x() = clamp_verbose_cursor_x (wx);
3647         verbose_canvas_cursor->property_y() = clamp_verbose_cursor_y (wy);
3648
3649         show_verbose_canvas_cursor ();
3650 }
3651
3652 void
3653 Editor::set_verbose_canvas_cursor (const string & txt, double x, double y)
3654 {
3655         verbose_canvas_cursor->property_text() = txt.c_str();
3656         /* don't get too close to the edge */
3657         verbose_canvas_cursor->property_x() = clamp_verbose_cursor_x (x);
3658         verbose_canvas_cursor->property_y() = clamp_verbose_cursor_y (y);
3659 }
3660
3661 void
3662 Editor::set_verbose_canvas_cursor_text (const string & txt)
3663 {
3664         verbose_canvas_cursor->property_text() = txt.c_str();
3665 }
3666
3667 void
3668 Editor::set_edit_mode (EditMode m)
3669 {
3670         Config->set_edit_mode (m);
3671 }
3672
3673 void
3674 Editor::cycle_edit_mode ()
3675 {
3676         switch (Config->get_edit_mode()) {
3677         case Slide:
3678                 if (Profile->get_sae()) {
3679                         Config->set_edit_mode (Lock);
3680                 } else {
3681                         Config->set_edit_mode (Splice);
3682                 }
3683                 break;
3684         case Splice:
3685                 Config->set_edit_mode (Lock);
3686                 break;
3687         case Lock:
3688                 Config->set_edit_mode (Slide);
3689                 break;
3690         }
3691 }
3692
3693 void
3694 Editor::edit_mode_selection_done ()
3695 {
3696         Config->set_edit_mode (string_to_edit_mode (edit_mode_selector.get_active_text ()));
3697 }
3698
3699 void
3700 Editor::snap_type_selection_done ()
3701 {
3702         string choice = snap_type_selector.get_active_text();
3703         SnapType snaptype = SnapToBeat;
3704
3705         if (choice == _("Beats/2")) {
3706                 snaptype = SnapToBeatDiv2;
3707         } else if (choice == _("Beats/3")) {
3708                 snaptype = SnapToBeatDiv3;
3709         } else if (choice == _("Beats/4")) {
3710                 snaptype = SnapToBeatDiv4;
3711         } else if (choice == _("Beats/5")) {
3712                 snaptype = SnapToBeatDiv5;
3713         } else if (choice == _("Beats/6")) {
3714                 snaptype = SnapToBeatDiv6;
3715         } else if (choice == _("Beats/7")) {
3716                 snaptype = SnapToBeatDiv7;
3717         } else if (choice == _("Beats/8")) {
3718                 snaptype = SnapToBeatDiv8;
3719         } else if (choice == _("Beats/10")) {
3720                 snaptype = SnapToBeatDiv10;
3721         } else if (choice == _("Beats/12")) {
3722                 snaptype = SnapToBeatDiv12;
3723         } else if (choice == _("Beats/14")) {
3724                 snaptype = SnapToBeatDiv14;
3725         } else if (choice == _("Beats/16")) {
3726                 snaptype = SnapToBeatDiv16;
3727         } else if (choice == _("Beats/20")) {
3728                 snaptype = SnapToBeatDiv20;
3729         } else if (choice == _("Beats/24")) {
3730                 snaptype = SnapToBeatDiv24;
3731         } else if (choice == _("Beats/28")) {
3732                 snaptype = SnapToBeatDiv28;
3733         } else if (choice == _("Beats/32")) {
3734                 snaptype = SnapToBeatDiv32;
3735         } else if (choice == _("Beats")) {
3736                 snaptype = SnapToBeat;
3737         } else if (choice == _("Bars")) {
3738                 snaptype = SnapToBar;
3739         } else if (choice == _("Marks")) {
3740                 snaptype = SnapToMark;
3741         } else if (choice == _("Region starts")) {
3742                 snaptype = SnapToRegionStart;
3743         } else if (choice == _("Region ends")) {
3744                 snaptype = SnapToRegionEnd;
3745         } else if (choice == _("Region bounds")) {
3746                 snaptype = SnapToRegionBoundary;
3747         } else if (choice == _("Region syncs")) {
3748                 snaptype = SnapToRegionSync;
3749         } else if (choice == _("CD Frames")) {
3750                 snaptype = SnapToCDFrame;
3751         } else if (choice == _("Timecode Frames")) {
3752                 snaptype = SnapToTimecodeFrame;
3753         } else if (choice == _("Timecode Seconds")) {
3754                 snaptype = SnapToTimecodeSeconds;
3755         } else if (choice == _("Timecode Minutes")) {
3756                 snaptype = SnapToTimecodeMinutes;
3757         } else if (choice == _("Seconds")) {
3758                 snaptype = SnapToSeconds;
3759         } else if (choice == _("Minutes")) {
3760                 snaptype = SnapToMinutes;
3761         }
3762
3763         RefPtr<RadioAction> ract = snap_type_action (snaptype);
3764         if (ract) {
3765                 ract->set_active ();
3766         }
3767 }
3768
3769 void
3770 Editor::snap_mode_selection_done ()
3771 {
3772         string choice = snap_mode_selector.get_active_text();
3773         SnapMode mode = SnapNormal;
3774
3775         if (choice == _("No Grid")) {
3776                 mode = SnapOff;
3777         } else if (choice == _("Grid")) {
3778                 mode = SnapNormal;
3779         } else if (choice == _("Magnetic")) {
3780                 mode = SnapMagnetic;
3781         }
3782
3783         RefPtr<RadioAction> ract = snap_mode_action (mode);
3784
3785         if (ract) {
3786                 ract->set_active (true);
3787         }
3788 }
3789
3790 void
3791 Editor::cycle_edit_point (bool with_marker)
3792 {
3793         switch (_edit_point) {
3794         case EditAtMouse:
3795                 set_edit_point_preference (EditAtPlayhead);
3796                 break;
3797         case EditAtPlayhead:
3798                 if (with_marker) {
3799                         set_edit_point_preference (EditAtSelectedMarker);
3800                 } else {
3801                         set_edit_point_preference (EditAtMouse);
3802                 }
3803                 break;
3804         case EditAtSelectedMarker:
3805                 set_edit_point_preference (EditAtMouse);
3806                 break;
3807         }
3808 }
3809
3810 void
3811 Editor::edit_point_selection_done ()
3812 {
3813         string choice = edit_point_selector.get_active_text();
3814         EditPoint ep = EditAtSelectedMarker;
3815
3816         if (choice == _("Marker")) {
3817                 set_edit_point_preference (EditAtSelectedMarker);
3818         } else if (choice == _("Playhead")) {
3819                 set_edit_point_preference (EditAtPlayhead);
3820         } else {
3821                 set_edit_point_preference (EditAtMouse);
3822         }
3823
3824         RefPtr<RadioAction> ract = edit_point_action (ep);
3825
3826         if (ract) {
3827                 ract->set_active (true);
3828         }
3829 }
3830
3831 void
3832 Editor::zoom_focus_selection_done ()
3833 {
3834         string choice = zoom_focus_selector.get_active_text();
3835         ZoomFocus focus_type = ZoomFocusLeft;
3836
3837         if (choice == _("Left")) {
3838                 focus_type = ZoomFocusLeft;
3839         } else if (choice == _("Right")) {
3840                 focus_type = ZoomFocusRight;
3841         } else if (choice == _("Center")) {
3842                 focus_type = ZoomFocusCenter;
3843         } else if (choice == _("Playhead")) {
3844                 focus_type = ZoomFocusPlayhead;
3845         } else if (choice == _("Mouse")) {
3846                 focus_type = ZoomFocusMouse;
3847         } else if (choice == _("Edit point")) {
3848                 focus_type = ZoomFocusEdit;
3849         }
3850
3851         RefPtr<RadioAction> ract = zoom_focus_action (focus_type);
3852
3853         if (ract) {
3854                 ract->set_active ();
3855         }
3856 }
3857
3858 gint
3859 Editor::edit_controls_button_release (GdkEventButton* ev)
3860 {
3861         if (Keyboard::is_context_menu_event (ev)) {
3862                 ARDOUR_UI::instance()->add_route (this);
3863         }
3864         return TRUE;
3865 }
3866
3867 gint
3868 Editor::mouse_select_button_release (GdkEventButton* ev)
3869 {
3870         /* this handles just right-clicks */
3871
3872         if (ev->button != 3) {
3873                 return false;
3874         }
3875
3876         return true;
3877 }
3878
3879 void
3880 Editor::set_zoom_focus (ZoomFocus f)
3881 {
3882         string str = zoom_focus_strings[(int)f];
3883
3884         if (str != zoom_focus_selector.get_active_text()) {
3885                 zoom_focus_selector.set_active_text (str);
3886         }
3887
3888         if (zoom_focus != f) {
3889                 zoom_focus = f;
3890
3891                 ZoomFocusChanged (); /* EMIT_SIGNAL */
3892
3893                 instant_save ();
3894         }
3895 }
3896
3897 void
3898 Editor::ensure_float (Window& win)
3899 {
3900         win.set_transient_for (*this);
3901 }
3902
3903 void
3904 Editor::pane_allocation_handler (Allocation &alloc, Paned* which)
3905 {
3906         /* recover or initialize pane positions. do this here rather than earlier because
3907            we don't want the positions to change the child allocations, which they seem to do.
3908          */
3909
3910         int pos;
3911         XMLProperty* prop;
3912         char buf[32];
3913         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
3914         int width, height;
3915
3916         enum Pane {
3917                 Horizontal = 0x1,
3918                 Vertical = 0x2
3919         };
3920
3921         static Pane done;
3922         
3923         XMLNode* geometry;
3924
3925         width = default_width;
3926         height = default_height;
3927
3928         if ((geometry = find_named_node (*node, "geometry")) != 0) {
3929
3930                 prop = geometry->property ("x-size");
3931                 if (prop) {
3932                         width = atoi (prop->value());
3933                 }
3934                 prop = geometry->property ("y-size");
3935                 if (prop) {
3936                         height = atoi (prop->value());
3937                 }
3938         }
3939
3940         if (which == static_cast<Paned*> (&edit_pane)) {
3941
3942                 if (done & Horizontal) {
3943                         return;
3944                 }
3945
3946                 if (!geometry || (prop = geometry->property ("edit-horizontal-pane-pos")) == 0) {
3947                         /* initial allocation is 90% to canvas, 10% to notebook */
3948                         pos = (int) floor (alloc.get_width() * 0.90f);
3949                         snprintf (buf, sizeof(buf), "%d", pos);
3950                 } else {
3951                         pos = atoi (prop->value());
3952                 }
3953
3954                 if (GTK_WIDGET(edit_pane.gobj())->allocation.width > pos) {
3955                         edit_pane.set_position (pos);
3956                         pre_maximal_horizontal_pane_position = pos;
3957                 }
3958
3959                 done = (Pane) (done | Horizontal);
3960                 
3961         } else if (which == static_cast<Paned*> (&editor_summary_pane)) {
3962
3963                 if (done & Vertical) {
3964                         return;
3965                 }
3966
3967                 if (!geometry || (prop = geometry->property ("edit-vertical-pane-pos")) == 0) {
3968                         /* initial allocation is 90% to canvas, 10% to summary */
3969                         pos = (int) floor (alloc.get_height() * 0.90f);
3970                         snprintf (buf, sizeof(buf), "%d", pos);
3971                 } else {
3972                         pos = atoi (prop->value());
3973                 }
3974
3975                 if (GTK_WIDGET(editor_summary_pane.gobj())->allocation.height > pos) {
3976                         editor_summary_pane.set_position (pos);
3977                         pre_maximal_vertical_pane_position = pos;
3978                 }
3979
3980                 done = (Pane) (done | Vertical);
3981         }
3982 }
3983
3984 void
3985 Editor::detach_tearoff (Box* /*b*/, Window* /*w*/)
3986 {
3987         if (_tools_tearoff->torn_off() && _mouse_mode_tearoff->torn_off()) {
3988                 top_hbox.remove (toolbar_frame);
3989         }
3990 }
3991
3992 void
3993 Editor::reattach_tearoff (Box* /*b*/, Window* /*w*/, int32_t /*n*/)
3994 {
3995         if (toolbar_frame.get_parent() == 0) {
3996                 top_hbox.pack_end (toolbar_frame);
3997         }
3998 }
3999
4000 void
4001 Editor::set_show_measures (bool yn)
4002 {
4003         if (_show_measures != yn) {
4004                 hide_measures ();
4005
4006                 if ((_show_measures = yn) == true) {
4007                         if (tempo_lines)
4008                                 tempo_lines->show();
4009                         draw_measures ();
4010                 }
4011                 instant_save ();
4012         }
4013 }
4014
4015 void
4016 Editor::toggle_follow_playhead ()
4017 {
4018         RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
4019         if (act) {
4020                 RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
4021                 set_follow_playhead (tact->get_active());
4022         }
4023 }
4024
4025 void
4026 Editor::set_follow_playhead (bool yn)
4027 {
4028         if (_follow_playhead != yn) {
4029                 if ((_follow_playhead = yn) == true) {
4030                         /* catch up */
4031                         reset_x_origin_to_follow_playhead ();
4032                 }
4033                 instant_save ();
4034         }
4035 }
4036
4037 void
4038 Editor::toggle_stationary_playhead ()
4039 {
4040        RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-stationary-playhead"));
4041        if (act) {
4042                RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
4043                set_stationary_playhead (tact->get_active());
4044        }
4045 }
4046
4047 void
4048 Editor::set_stationary_playhead (bool yn)
4049 {
4050        if (_stationary_playhead != yn) {
4051                if ((_stationary_playhead = yn) == true) {
4052                        /* catch up */
4053                        // FIXME need a 3.0 equivalent of this 2.X call
4054                        // update_current_screen ();
4055                }
4056                instant_save ();
4057        }
4058 }
4059
4060 void
4061 Editor::toggle_xfade_active (boost::weak_ptr<Crossfade> wxfade)
4062 {
4063         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
4064         if (xfade) {
4065                 xfade->set_active (!xfade->active());
4066         }
4067 }
4068
4069 void
4070 Editor::toggle_xfade_length (boost::weak_ptr<Crossfade> wxfade)
4071 {
4072         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
4073         if (xfade) {
4074                 xfade->set_follow_overlap (!xfade->following_overlap());
4075         }
4076 }
4077
4078 void
4079 Editor::edit_xfade (boost::weak_ptr<Crossfade> wxfade)
4080 {
4081         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
4082
4083         if (!xfade) {
4084                 return;
4085         }
4086
4087         CrossfadeEditor cew (_session, xfade, xfade->fade_in().get_min_y(), 1.0);
4088
4089         ensure_float (cew);
4090
4091         switch (cew.run ()) {
4092         case RESPONSE_ACCEPT:
4093                 break;
4094         default:
4095                 return;
4096         }
4097
4098         cew.apply ();
4099         PropertyChange all_crossfade_properties;
4100         all_crossfade_properties.add (ARDOUR::Properties::active);
4101         all_crossfade_properties.add (ARDOUR::Properties::follow_overlap);
4102         xfade->PropertyChanged (all_crossfade_properties);
4103 }
4104
4105 PlaylistSelector&
4106 Editor::playlist_selector () const
4107 {
4108         return *_playlist_selector;
4109 }
4110
4111 Evoral::MusicalTime
4112 Editor::get_grid_type_as_beats (bool& success, framepos_t position)
4113 {
4114         success = true;
4115
4116         switch (_snap_type) {
4117         case SnapToBeat:
4118                 return 1.0;
4119                 break;
4120
4121         case SnapToBeatDiv32:
4122                 return 1.0/32.0;
4123                 break;
4124         case SnapToBeatDiv28:
4125                 return 1.0/28.0;
4126                 break;
4127         case SnapToBeatDiv24:
4128                 return 1.0/24.0;
4129                 break;
4130         case SnapToBeatDiv20:
4131                 return 1.0/20.0;
4132                 break;
4133         case SnapToBeatDiv16:
4134                 return 1.0/16.0;
4135                 break;
4136         case SnapToBeatDiv14:
4137                 return 1.0/14.0;
4138                 break;
4139         case SnapToBeatDiv12:
4140                 return 1.0/12.0;
4141                 break;
4142         case SnapToBeatDiv10:
4143                 return 1.0/10.0;
4144                 break;
4145         case SnapToBeatDiv8:
4146                 return 1.0/8.0;
4147                 break;
4148         case SnapToBeatDiv7:
4149                 return 1.0/7.0;
4150                 break;
4151         case SnapToBeatDiv6:
4152                 return 1.0/6.0;
4153                 break;
4154         case SnapToBeatDiv5:
4155                 return 1.0/5.0;
4156                 break;
4157         case SnapToBeatDiv4:
4158                 return 1.0/4.0;
4159                 break;
4160         case SnapToBeatDiv3:
4161                 return 1.0/3.0;
4162                 break;
4163         case SnapToBeatDiv2:
4164                 return 1.0/2.0;
4165                 break;
4166
4167         case SnapToBar:
4168                 if (_session) {
4169                         return _session->tempo_map().meter_at (position).beats_per_bar();
4170                 }
4171                 break;
4172
4173         case SnapToCDFrame:
4174         case SnapToTimecodeFrame:
4175         case SnapToTimecodeSeconds:
4176         case SnapToTimecodeMinutes:
4177         case SnapToSeconds:
4178         case SnapToMinutes:
4179         case SnapToRegionStart:
4180         case SnapToRegionEnd:
4181         case SnapToRegionSync:
4182         case SnapToRegionBoundary:
4183         default:
4184                 success = false;
4185                 break;
4186         }
4187
4188         return 0.0;
4189 }
4190
4191 framecnt_t
4192 Editor::get_nudge_distance (framepos_t pos, framecnt_t& next)
4193 {
4194         framecnt_t ret;
4195
4196         ret = nudge_clock.current_duration (pos);
4197         next = ret + 1; /* XXXX fix me */
4198
4199         return ret;
4200 }
4201
4202 int
4203 Editor::playlist_deletion_dialog (boost::shared_ptr<Playlist> pl)
4204 {
4205         ArdourDialog dialog (_("Playlist Deletion"));
4206         Label  label (string_compose (_("Playlist %1 is currently unused.\n"
4207                                         "If left alone, no audio files used by it will be cleaned.\n"
4208                                         "If deleted, audio files used by it alone by will cleaned."),
4209                                       pl->name()));
4210
4211         dialog.set_position (WIN_POS_CENTER);
4212         dialog.get_vbox()->pack_start (label);
4213
4214         label.show ();
4215
4216         dialog.add_button (_("Delete playlist"), RESPONSE_ACCEPT);
4217         dialog.add_button (_("Keep playlist"), RESPONSE_REJECT);
4218         dialog.add_button (_("Cancel"), RESPONSE_CANCEL);
4219
4220         switch (dialog.run ()) {
4221         case RESPONSE_ACCEPT:
4222                 /* delete the playlist */
4223                 return 0;
4224                 break;
4225
4226         case RESPONSE_REJECT:
4227                 /* keep the playlist */
4228                 return 1;
4229                 break;
4230
4231         default:
4232                 break;
4233         }
4234
4235         return -1;
4236 }
4237
4238 bool
4239 Editor::audio_region_selection_covers (framepos_t where)
4240 {
4241         for (RegionSelection::iterator a = selection->regions.begin(); a != selection->regions.end(); ++a) {
4242                 if ((*a)->region()->covers (where)) {
4243                         return true;
4244                 }
4245         }
4246
4247         return false;
4248 }
4249
4250 void
4251 Editor::prepare_for_cleanup ()
4252 {
4253         cut_buffer->clear_regions ();
4254         cut_buffer->clear_playlists ();
4255
4256         selection->clear_regions ();
4257         selection->clear_playlists ();
4258
4259         _regions->suspend_redisplay ();
4260 }
4261
4262 void
4263 Editor::finish_cleanup ()
4264 {
4265         _regions->resume_redisplay ();
4266 }
4267
4268 Location*
4269 Editor::transport_loop_location()
4270 {
4271         if (_session) {
4272                 return _session->locations()->auto_loop_location();
4273         } else {
4274                 return 0;
4275         }
4276 }
4277
4278 Location*
4279 Editor::transport_punch_location()
4280 {
4281         if (_session) {
4282                 return _session->locations()->auto_punch_location();
4283         } else {
4284                 return 0;
4285         }
4286 }
4287
4288 bool
4289 Editor::control_layout_scroll (GdkEventScroll* ev)
4290 {
4291         if (Keyboard::some_magic_widget_has_focus()) {
4292                 return false;
4293         }
4294
4295         switch (ev->direction) {
4296         case GDK_SCROLL_UP:
4297                 scroll_tracks_up_line ();
4298                 return true;
4299                 break;
4300
4301         case GDK_SCROLL_DOWN:
4302                 scroll_tracks_down_line ();
4303                 return true;
4304
4305         default:
4306                 /* no left/right handling yet */
4307                 break;
4308         }
4309
4310         return false;
4311 }
4312
4313 void
4314 Editor::session_state_saved (string)
4315 {
4316         update_title ();        
4317         _snapshots->redisplay ();
4318 }
4319
4320 void
4321 Editor::maximise_editing_space ()
4322 {
4323         _mouse_mode_tearoff->set_visible (false);
4324         _tools_tearoff->set_visible (false);
4325         _zoom_tearoff->set_visible (false);
4326
4327         pre_maximal_horizontal_pane_position = edit_pane.get_position ();
4328         pre_maximal_vertical_pane_position = editor_summary_pane.get_position ();
4329         pre_maximal_editor_width = this->get_width ();
4330         pre_maximal_editor_height = this->get_height ();
4331
4332         if (post_maximal_horizontal_pane_position == 0) {
4333                 post_maximal_horizontal_pane_position = edit_pane.get_width();
4334         }
4335
4336         if (post_maximal_vertical_pane_position == 0) {
4337                 post_maximal_vertical_pane_position = editor_summary_pane.get_height();
4338         }
4339         
4340         fullscreen ();
4341
4342         if (post_maximal_editor_width) {
4343                 edit_pane.set_position (post_maximal_horizontal_pane_position -
4344                         abs(post_maximal_editor_width - pre_maximal_editor_width));
4345         } else {
4346                 edit_pane.set_position (post_maximal_horizontal_pane_position);
4347         }
4348
4349         if (post_maximal_editor_height) {
4350                 editor_summary_pane.set_position (post_maximal_vertical_pane_position -
4351                         abs(post_maximal_editor_height - pre_maximal_editor_height));
4352         } else {
4353                 editor_summary_pane.set_position (post_maximal_vertical_pane_position);
4354         }
4355
4356         if (Config->get_keep_tearoffs()) {
4357                 _mouse_mode_tearoff->set_visible (true);
4358                 _tools_tearoff->set_visible (true);
4359                 _zoom_tearoff->set_visible (true);
4360         }
4361 }
4362
4363 void
4364 Editor::restore_editing_space ()
4365 {
4366         // user changed width/height of panes during fullscreen
4367
4368         if (post_maximal_horizontal_pane_position != edit_pane.get_position()) {
4369                 post_maximal_horizontal_pane_position = edit_pane.get_position();
4370         }
4371
4372         if (post_maximal_vertical_pane_position != editor_summary_pane.get_position()) {
4373                 post_maximal_vertical_pane_position = editor_summary_pane.get_position();
4374         }
4375         
4376         unfullscreen();
4377
4378         _mouse_mode_tearoff->set_visible (true);
4379         _tools_tearoff->set_visible (true);
4380         _zoom_tearoff->set_visible (true);
4381         post_maximal_editor_width = this->get_width();
4382         post_maximal_editor_height = this->get_height();
4383
4384         edit_pane.set_position (pre_maximal_horizontal_pane_position + abs(this->get_width() - pre_maximal_editor_width));
4385         editor_summary_pane.set_position (pre_maximal_vertical_pane_position + abs(this->get_height() - pre_maximal_editor_height));
4386 }
4387
4388 /**
4389  *  Make new playlists for a given track and also any others that belong
4390  *  to the same active route group with the `edit' property.
4391  *  @param v Track.
4392  */
4393
4394 void
4395 Editor::new_playlists (TimeAxisView* v)
4396 {
4397         begin_reversible_command (_("new playlists"));
4398         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4399         _session->playlists->get (playlists);
4400         mapover_tracks (sigc::bind (sigc::mem_fun (*this, &Editor::mapped_use_new_playlist), playlists), v, ARDOUR::Properties::edit.property_id);
4401         commit_reversible_command ();
4402 }
4403
4404 /**
4405  *  Use a copy of the current playlist for a given track and also any others that belong
4406  *  to the same active route group with the `edit' property.
4407  *  @param v Track.
4408  */
4409
4410 void
4411 Editor::copy_playlists (TimeAxisView* v)
4412 {
4413         begin_reversible_command (_("copy playlists"));
4414         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4415         _session->playlists->get (playlists);
4416         mapover_tracks (sigc::bind (sigc::mem_fun (*this, &Editor::mapped_use_copy_playlist), playlists), v, ARDOUR::Properties::edit.property_id);
4417         commit_reversible_command ();
4418 }
4419
4420 /** Clear the current playlist for a given track and also any others that belong
4421  *  to the same active route group with the `edit' property.
4422  *  @param v Track.
4423  */
4424
4425 void
4426 Editor::clear_playlists (TimeAxisView* v)
4427 {
4428         begin_reversible_command (_("clear playlists"));
4429         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4430         _session->playlists->get (playlists);
4431         mapover_tracks (sigc::mem_fun (*this, &Editor::mapped_clear_playlist), v, ARDOUR::Properties::edit.property_id);
4432         commit_reversible_command ();
4433 }
4434
4435 void
4436 Editor::mapped_use_new_playlist (RouteTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4437 {
4438         atv.use_new_playlist (sz > 1 ? false : true, playlists);
4439 }
4440
4441 void
4442 Editor::mapped_use_copy_playlist (RouteTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4443 {
4444         atv.use_copy_playlist (sz > 1 ? false : true, playlists);
4445 }
4446
4447 void
4448 Editor::mapped_clear_playlist (RouteTimeAxisView& atv, uint32_t /*sz*/)
4449 {
4450         atv.clear_playlist ();
4451 }
4452
4453 bool
4454 Editor::on_key_press_event (GdkEventKey* ev)
4455 {
4456         return key_press_focus_accelerator_handler (*this, ev);
4457 }
4458
4459 bool
4460 Editor::on_key_release_event (GdkEventKey* ev)
4461 {
4462         return Gtk::Window::on_key_release_event (ev);
4463         // return key_press_focus_accelerator_handler (*this, ev);
4464 }
4465
4466 /** Queue up a change to the viewport x origin.
4467  *  @param frame New x origin.
4468  */
4469 void
4470 Editor::reset_x_origin (framepos_t frame)
4471 {
4472         queue_visual_change (frame);
4473 }
4474
4475 void
4476 Editor::reset_y_origin (double y)
4477 {
4478         queue_visual_change_y (y);
4479 }
4480
4481 void
4482 Editor::reset_zoom (double fpu)
4483 {
4484         queue_visual_change (fpu);
4485 }
4486
4487 void
4488 Editor::reposition_and_zoom (framepos_t frame, double fpu)
4489 {
4490         reset_x_origin (frame);
4491         reset_zoom (fpu);
4492
4493         if (!no_save_visual) {
4494                 undo_visual_stack.push_back (current_visual_state(false));
4495         }
4496 }
4497
4498 Editor::VisualState*
4499 Editor::current_visual_state (bool with_tracks)
4500 {
4501         VisualState* vs = new VisualState;
4502         vs->y_position = vertical_adjustment.get_value();
4503         vs->frames_per_unit = frames_per_unit;
4504         vs->leftmost_frame = leftmost_frame;
4505         vs->zoom_focus = zoom_focus;
4506
4507         if (with_tracks) {
4508                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4509                         vs->track_states.push_back (TAVState ((*i), &(*i)->get_state()));
4510                 }
4511         }
4512
4513         return vs;
4514 }
4515
4516 void
4517 Editor::undo_visual_state ()
4518 {
4519         if (undo_visual_stack.empty()) {
4520                 return;
4521         }
4522
4523         redo_visual_stack.push_back (current_visual_state());
4524
4525         VisualState* vs = undo_visual_stack.back();
4526         undo_visual_stack.pop_back();
4527         use_visual_state (*vs);
4528 }
4529
4530 void
4531 Editor::redo_visual_state ()
4532 {
4533         if (redo_visual_stack.empty()) {
4534                 return;
4535         }
4536
4537         undo_visual_stack.push_back (current_visual_state());
4538
4539         VisualState* vs = redo_visual_stack.back();
4540         redo_visual_stack.pop_back();
4541         use_visual_state (*vs);
4542 }
4543
4544 void
4545 Editor::swap_visual_state ()
4546 {
4547         if (undo_visual_stack.empty()) {
4548                 redo_visual_state ();
4549         } else {
4550                 undo_visual_state ();
4551         }
4552 }
4553
4554 void
4555 Editor::use_visual_state (VisualState& vs)
4556 {
4557         no_save_visual = true;
4558
4559         _routes->suspend_redisplay ();
4560
4561         vertical_adjustment.set_value (vs.y_position);
4562
4563         set_zoom_focus (vs.zoom_focus);
4564         reposition_and_zoom (vs.leftmost_frame, vs.frames_per_unit);
4565
4566         for (list<TAVState>::iterator i = vs.track_states.begin(); i != vs.track_states.end(); ++i) {
4567                 TrackViewList::iterator t;
4568
4569                 /* check if the track still exists - it could have been deleted */
4570
4571                 if ((t = find (track_views.begin(), track_views.end(), i->first)) != track_views.end()) {
4572                         (*t)->set_state (*(i->second), Stateful::loading_state_version);
4573                 }
4574         }
4575
4576
4577         if (!vs.track_states.empty()) {
4578                 _routes->update_visibility ();
4579         }
4580
4581         _routes->resume_redisplay ();
4582
4583         no_save_visual = false;
4584 }
4585
4586 void
4587 Editor::set_frames_per_unit (double fpu)
4588 {
4589         /* this is the core function that controls the zoom level of the canvas. it is called
4590            whenever one or more calls are made to reset_zoom(). it executes in an idle handler.
4591         */
4592
4593         if (fpu == frames_per_unit) {
4594                 return;
4595         }
4596
4597         if (fpu < 2.0) {
4598                 fpu = 2.0;
4599         }
4600
4601
4602         /* don't allow zooms that fit more than the maximum number
4603            of frames into an 800 pixel wide space.
4604         */
4605
4606         if (max_framepos / fpu < 800.0) {
4607                 return;
4608         }
4609
4610         if (tempo_lines)
4611                 tempo_lines->tempo_map_changed();
4612
4613         frames_per_unit = fpu;
4614         post_zoom ();
4615 }
4616
4617 void
4618 Editor::post_zoom ()
4619 {
4620         // convert fpu to frame count
4621
4622         framepos_t frames = (framepos_t) floor (frames_per_unit * _canvas_width);
4623
4624         if (frames_per_unit != zoom_range_clock.current_duration()) {
4625                 zoom_range_clock.set (frames);
4626         }
4627
4628         if (mouse_mode == MouseRange && selection->time.start () != selection->time.end_frame ()) {
4629                 for (TrackViewList::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4630                         (*i)->reshow_selection (selection->time);
4631                 }
4632         }
4633
4634         ZoomChanged (); /* EMIT_SIGNAL */
4635
4636         //reset_scrolling_region ();
4637
4638         if (playhead_cursor) {
4639                 playhead_cursor->set_position (playhead_cursor->current_frame);
4640         }
4641
4642         refresh_location_display();
4643         _summary->set_overlays_dirty ();
4644
4645         instant_save ();
4646 }
4647
4648 void
4649 Editor::queue_visual_change (framepos_t where)
4650 {
4651         pending_visual_change.add (VisualChange::TimeOrigin);
4652         pending_visual_change.time_origin = where;
4653         ensure_visual_change_idle_handler ();
4654 }
4655
4656 void
4657 Editor::queue_visual_change (double fpu)
4658 {
4659         pending_visual_change.add (VisualChange::ZoomLevel);
4660         pending_visual_change.frames_per_unit = fpu;
4661
4662         ensure_visual_change_idle_handler ();
4663 }
4664
4665 void
4666 Editor::queue_visual_change_y (double y)
4667 {
4668         pending_visual_change.add (VisualChange::YOrigin);
4669         pending_visual_change.y_origin = y;
4670
4671         ensure_visual_change_idle_handler ();
4672 }
4673
4674 void
4675 Editor::ensure_visual_change_idle_handler ()
4676 {
4677         if (pending_visual_change.idle_handler_id < 0) {
4678                 pending_visual_change.idle_handler_id = g_idle_add (_idle_visual_changer, this);
4679         }
4680 }
4681
4682 int
4683 Editor::_idle_visual_changer (void* arg)
4684 {
4685         return static_cast<Editor*>(arg)->idle_visual_changer ();
4686 }
4687
4688 int
4689 Editor::idle_visual_changer ()
4690 {
4691         VisualChange::Type p = pending_visual_change.pending;
4692         pending_visual_change.pending = (VisualChange::Type) 0;
4693
4694         double last_time_origin = horizontal_position ();
4695
4696         if (p & VisualChange::ZoomLevel) {
4697                 set_frames_per_unit (pending_visual_change.frames_per_unit);
4698
4699                 compute_fixed_ruler_scale ();
4700                 compute_current_bbt_points(pending_visual_change.time_origin, pending_visual_change.time_origin + current_page_frames());
4701                 compute_bbt_ruler_scale (pending_visual_change.time_origin, pending_visual_change.time_origin + current_page_frames());
4702                 update_tempo_based_rulers ();
4703         }
4704         if (p & VisualChange::TimeOrigin) {
4705                 set_horizontal_position (pending_visual_change.time_origin / frames_per_unit);
4706         }
4707         if (p & VisualChange::YOrigin) {
4708                 vertical_adjustment.set_value (pending_visual_change.y_origin);
4709         }
4710
4711         if (last_time_origin == horizontal_position ()) {
4712                 /* changed signal not emitted */
4713                 update_fixed_rulers ();
4714                 redisplay_tempo (true);
4715         }
4716
4717         _summary->set_overlays_dirty ();
4718
4719         pending_visual_change.idle_handler_id = -1;
4720         return 0; /* this is always a one-shot call */
4721 }
4722
4723 struct EditorOrderTimeAxisSorter {
4724     bool operator() (const TimeAxisView* a, const TimeAxisView* b) const {
4725             return a->order () < b->order ();
4726     }
4727 };
4728
4729 void
4730 Editor::sort_track_selection (TrackViewList* sel)
4731 {
4732         EditorOrderTimeAxisSorter cmp;
4733
4734         if (sel) {
4735                 sel->sort (cmp);
4736         } else {
4737                 selection->tracks.sort (cmp);
4738         }
4739 }
4740
4741 framepos_t
4742 Editor::get_preferred_edit_position (bool ignore_playhead)
4743 {
4744         bool ignored;
4745         framepos_t where = 0;
4746         EditPoint ep = _edit_point;
4747
4748         if (entered_marker) {
4749                 return entered_marker->position();
4750         }
4751
4752         if (ignore_playhead && ep == EditAtPlayhead) {
4753                 ep = EditAtSelectedMarker;
4754         }
4755
4756         switch (ep) {
4757         case EditAtPlayhead:
4758                 where = _session->audible_frame();
4759                 break;
4760
4761         case EditAtSelectedMarker:
4762                 if (!selection->markers.empty()) {
4763                         bool is_start;
4764                         Location* loc = find_location_from_marker (selection->markers.front(), is_start);
4765                         if (loc) {
4766                                 if (is_start) {
4767                                         where =  loc->start();
4768                                 } else {
4769                                         where = loc->end();
4770                                 }
4771                                 break;
4772                         }
4773                 }
4774                 /* fallthru */
4775
4776         default:
4777         case EditAtMouse:
4778                 if (!mouse_frame (where, ignored)) {
4779                         /* XXX not right but what can we do ? */
4780                         return 0;
4781                 }
4782                 snap_to (where);
4783                 break;
4784         }
4785
4786         return where;
4787 }
4788
4789 void
4790 Editor::set_loop_range (framepos_t start, framepos_t end, string cmd)
4791 {
4792         if (!_session) return;
4793
4794         begin_reversible_command (cmd);
4795
4796         Location* tll;
4797
4798         if ((tll = transport_loop_location()) == 0) {
4799                 Location* loc = new Location (*_session, start, end, _("Loop"),  Location::IsAutoLoop);
4800                 XMLNode &before = _session->locations()->get_state();
4801                 _session->locations()->add (loc, true);
4802                 _session->set_auto_loop_location (loc);
4803                 XMLNode &after = _session->locations()->get_state();
4804                 _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
4805         } else {
4806                 XMLNode &before = tll->get_state();
4807                 tll->set_hidden (false, this);
4808                 tll->set (start, end);
4809                 XMLNode &after = tll->get_state();
4810                 _session->add_command (new MementoCommand<Location>(*tll, &before, &after));
4811         }
4812
4813         commit_reversible_command ();
4814 }
4815
4816 void
4817 Editor::set_punch_range (framepos_t start, framepos_t end, string cmd)
4818 {
4819         if (!_session) return;
4820
4821         begin_reversible_command (cmd);
4822
4823         Location* tpl;
4824
4825         if ((tpl = transport_punch_location()) == 0) {
4826                 Location* loc = new Location (*_session, start, end, _("Loop"),  Location::IsAutoPunch);
4827                 XMLNode &before = _session->locations()->get_state();
4828                 _session->locations()->add (loc, true);
4829                 _session->set_auto_loop_location (loc);
4830                 XMLNode &after = _session->locations()->get_state();
4831                 _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
4832         }
4833         else {
4834                 XMLNode &before = tpl->get_state();
4835                 tpl->set_hidden (false, this);
4836                 tpl->set (start, end);
4837                 XMLNode &after = tpl->get_state();
4838                 _session->add_command (new MementoCommand<Location>(*tpl, &before, &after));
4839         }
4840
4841         commit_reversible_command ();
4842 }
4843
4844 /** Find regions which exist at a given time, and optionally on a given list of tracks.
4845  *  @param rs List to which found regions are added.
4846  *  @param where Time to look at.
4847  *  @param ts Tracks to look on; if this is empty, all tracks are examined.
4848  */
4849 void
4850 Editor::get_regions_at (RegionSelection& rs, framepos_t where, const TrackViewList& ts) const
4851 {
4852         const TrackViewList* tracks;
4853
4854         if (ts.empty()) {
4855                 tracks = &track_views;
4856         } else {
4857                 tracks = &ts;
4858         }
4859
4860         for (TrackViewList::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
4861                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*t);
4862                 if (rtv) {
4863                         boost::shared_ptr<Track> tr;
4864                         boost::shared_ptr<Playlist> pl;
4865
4866                         if ((tr = rtv->track()) && ((pl = tr->playlist()))) {
4867
4868                                 Playlist::RegionList* regions = pl->regions_at (
4869                                                 (framepos_t) floor ( (double)where * tr->speed()));
4870
4871                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
4872                                         RegionView* rv = rtv->view()->find_view (*i);
4873                                         if (rv) {
4874                                                 rs.add (rv);
4875                                         }
4876                                 }
4877
4878                                 delete regions;
4879                         }
4880                 }
4881         }
4882 }
4883
4884 void
4885 Editor::get_regions_after (RegionSelection& rs, framepos_t where, const TrackViewList& ts) const
4886 {
4887         const TrackViewList* tracks;
4888
4889         if (ts.empty()) {
4890                 tracks = &track_views;
4891         } else {
4892                 tracks = &ts;
4893         }
4894
4895         for (TrackViewList::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
4896                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*t);
4897                 if (rtv) {
4898                         boost::shared_ptr<Track> tr;
4899                         boost::shared_ptr<Playlist> pl;
4900
4901                         if ((tr = rtv->track()) && ((pl = tr->playlist()))) {
4902
4903                                 Playlist::RegionList* regions = pl->regions_touched (
4904                                         (framepos_t) floor ( (double)where * tr->speed()), max_framepos);
4905
4906                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
4907
4908                                         RegionView* rv = rtv->view()->find_view (*i);
4909
4910                                         if (rv) {
4911                                                 rs.push_back (rv);
4912                                         }
4913                                 }
4914
4915                                 delete regions;
4916                         }
4917                 }
4918         }
4919 }
4920
4921 /** Find all regions which are either:
4922  *      - selected or
4923  *      - the entered_regionview (if allow_entered == true) or
4924  *      - under the preferred edit position AND on a selected track, or on a track
4925  *        which is in the same active edit-enable route group as a selected region (if allow_edit_position == true)
4926  *  @param rs Returned region list.
4927  *  @param allow_entered true to include the entered_regionview in the list.
4928  */
4929 void
4930 Editor::get_regions_for_action (RegionSelection& rs, bool allow_entered, bool allow_edit_position)
4931 {
4932         /* Start with selected regions */
4933         rs = selection->regions;
4934
4935         /* Add the entered_regionview, if requested */
4936         if (allow_entered && entered_regionview) {
4937                 rs.add (entered_regionview);
4938         }
4939
4940         if (allow_edit_position) {
4941
4942                 TrackViewList tracks = selection->tracks;
4943
4944                 /* tracks is currently the set of selected tracks; add any other tracks that
4945                  * have regions that are in the same edit-activated route group as one of
4946                  * our regions */
4947                 for (RegionSelection::iterator i = rs.begin (); i != rs.end(); ++i) {
4948
4949                         RouteGroup* g = (*i)->get_time_axis_view().route_group ();
4950                         if (g && g->is_active() && g->is_edit()) {
4951                                 tracks.add (axis_views_from_routes (g->route_list()));
4952                         }
4953                         
4954                 }
4955
4956                 if (!tracks.empty()) {
4957                         /* now find regions that are at the edit position on those tracks */
4958                         framepos_t const where = get_preferred_edit_position ();
4959                         get_regions_at (rs, where, tracks);
4960                 }
4961         }
4962 }
4963
4964 void
4965 Editor::get_regions_corresponding_to (boost::shared_ptr<Region> region, vector<RegionView*>& regions)
4966 {
4967         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4968
4969                 RouteTimeAxisView* tatv;
4970
4971                 if ((tatv = dynamic_cast<RouteTimeAxisView*> (*i)) != 0) {
4972
4973                         boost::shared_ptr<Playlist> pl;
4974                         vector<boost::shared_ptr<Region> > results;
4975                         RegionView* marv;
4976                         boost::shared_ptr<Track> tr;
4977
4978                         if ((tr = tatv->track()) == 0) {
4979                                 /* bus */
4980                                 continue;
4981                         }
4982
4983                         if ((pl = (tr->playlist())) != 0) {
4984                                 pl->get_region_list_equivalent_regions (region, results);
4985                         }
4986
4987                         for (vector<boost::shared_ptr<Region> >::iterator ir = results.begin(); ir != results.end(); ++ir) {
4988                                 if ((marv = tatv->view()->find_view (*ir)) != 0) {
4989                                         regions.push_back (marv);
4990                                 }
4991                         }
4992
4993                 }
4994         }
4995 }
4996
4997 void
4998 Editor::show_rhythm_ferret ()
4999 {
5000         if (rhythm_ferret == 0) {
5001                 rhythm_ferret = new RhythmFerret(*this);
5002         }
5003
5004         rhythm_ferret->set_session (_session);
5005         rhythm_ferret->show ();
5006         rhythm_ferret->present ();
5007 }
5008
5009 void
5010 Editor::first_idle ()
5011 {
5012         MessageDialog* dialog = 0;
5013
5014         if (track_views.size() > 1) {
5015                 dialog = new MessageDialog (*this,
5016                                             string_compose (_("Please wait while %1 loads visual data"), PROGRAM_NAME),
5017                                             true,
5018                                             Gtk::MESSAGE_INFO,
5019                                             Gtk::BUTTONS_NONE);
5020                 dialog->present ();
5021                 ARDOUR_UI::instance()->flush_pending ();
5022         }
5023
5024         for (TrackViewList::iterator t = track_views.begin(); t != track_views.end(); ++t) {
5025                 (*t)->first_idle();
5026         }
5027
5028         // first idle adds route children (automation tracks), so we need to redisplay here
5029         _routes->redisplay ();
5030
5031         delete dialog;
5032
5033         _have_idled = true;
5034 }
5035
5036 gboolean
5037 Editor::_idle_resize (gpointer arg)
5038 {
5039         return ((Editor*)arg)->idle_resize ();
5040 }
5041
5042 void
5043 Editor::add_to_idle_resize (TimeAxisView* view, int32_t h)
5044 {
5045         if (resize_idle_id < 0) {
5046                 resize_idle_id = g_idle_add (_idle_resize, this);
5047                 _pending_resize_amount = 0;
5048         }
5049
5050         /* make a note of the smallest resulting height, so that we can clamp the
5051            lower limit at TimeAxisView::hSmall */
5052
5053         int32_t min_resulting = INT32_MAX;
5054
5055         _pending_resize_amount += h;
5056         _pending_resize_view = view;
5057
5058         min_resulting = min (min_resulting, int32_t (_pending_resize_view->current_height()) + _pending_resize_amount);
5059
5060         if (selection->tracks.contains (_pending_resize_view)) {
5061                 for (TrackViewList::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
5062                         min_resulting = min (min_resulting, int32_t ((*i)->current_height()) + _pending_resize_amount);
5063                 }
5064         }
5065
5066         if (min_resulting < 0) {
5067                 min_resulting = 0;
5068         }
5069
5070         /* clamp */
5071         if (uint32_t (min_resulting) < TimeAxisView::preset_height (HeightSmall)) {
5072                 _pending_resize_amount += TimeAxisView::preset_height (HeightSmall) - min_resulting;
5073         }
5074 }
5075
5076 /** Handle pending resizing of tracks */
5077 bool
5078 Editor::idle_resize ()
5079 {
5080         _pending_resize_view->idle_resize (_pending_resize_view->current_height() + _pending_resize_amount);
5081
5082         if (dynamic_cast<AutomationTimeAxisView*> (_pending_resize_view) == 0 &&
5083             selection->tracks.contains (_pending_resize_view)) {
5084
5085                 for (TrackViewList::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
5086                         if (*i != _pending_resize_view) {
5087                                 (*i)->idle_resize ((*i)->current_height() + _pending_resize_amount);
5088                         }
5089                 }
5090         }
5091
5092         _pending_resize_amount = 0;
5093         flush_canvas ();
5094         _group_tabs->set_dirty ();
5095         resize_idle_id = -1;
5096
5097         return false;
5098 }
5099
5100 void
5101 Editor::located ()
5102 {
5103         ENSURE_GUI_THREAD (*this, &Editor::located);
5104
5105         playhead_cursor->set_position (_session->audible_frame ());
5106         if (_follow_playhead && !_pending_initial_locate) {
5107                 reset_x_origin_to_follow_playhead ();
5108         }
5109
5110         _pending_locate_request = false;
5111         _pending_initial_locate = false;
5112 }
5113
5114 void
5115 Editor::region_view_added (RegionView *)
5116 {
5117         _summary->set_dirty ();
5118 }
5119
5120 TimeAxisView*
5121 Editor::axis_view_from_route (boost::shared_ptr<Route> r) const
5122 {
5123         TrackViewList::const_iterator j = track_views.begin ();
5124         while (j != track_views.end()) {
5125                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*j);
5126                 if (rtv && rtv->route() == r) {
5127                         return rtv;
5128                 }
5129                 ++j;
5130         }
5131
5132         return 0;
5133 }
5134
5135
5136 TrackViewList
5137 Editor::axis_views_from_routes (boost::shared_ptr<RouteList> r) const
5138 {
5139         TrackViewList t;
5140
5141         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
5142                 TimeAxisView* tv = axis_view_from_route (*i);
5143                 if (tv) {
5144                         t.push_back (tv);
5145                 }
5146         }
5147
5148         return t;
5149 }
5150
5151
5152 void
5153 Editor::handle_new_route (RouteList& routes)
5154 {
5155         ENSURE_GUI_THREAD (*this, &Editor::handle_new_route, routes)
5156
5157         RouteTimeAxisView *rtv;
5158         list<RouteTimeAxisView*> new_views;
5159
5160         for (RouteList::iterator x = routes.begin(); x != routes.end(); ++x) {
5161                 boost::shared_ptr<Route> route = (*x);
5162
5163                 if (route->is_hidden() || route->is_monitor()) {
5164                         continue;
5165                 }
5166
5167                 DataType dt = route->input()->default_type();
5168
5169                 if (dt == ARDOUR::DataType::AUDIO) {
5170                         rtv = new AudioTimeAxisView (*this, _session, route, *track_canvas);
5171                 } else if (dt == ARDOUR::DataType::MIDI) {
5172                         rtv = new MidiTimeAxisView (*this, _session, route, *track_canvas);
5173                 } else {
5174                         throw unknown_type();
5175                 }
5176
5177                 new_views.push_back (rtv);
5178                 track_views.push_back (rtv);
5179
5180                 rtv->effective_gain_display ();
5181
5182                 rtv->view()->RegionViewAdded.connect (sigc::mem_fun (*this, &Editor::region_view_added));
5183         }
5184
5185         _routes->routes_added (new_views);
5186
5187         if (show_editor_mixer_when_tracks_arrive) {
5188                 show_editor_mixer (true);
5189         }
5190
5191         editor_list_button.set_sensitive (true);
5192
5193         _summary->set_dirty ();
5194 }
5195
5196 void
5197 Editor::timeaxisview_deleted (TimeAxisView *tv)
5198 {
5199         if (_session && _session->deletion_in_progress()) {
5200                 /* the situation is under control */
5201                 return;
5202         }
5203
5204         ENSURE_GUI_THREAD (*this, &Editor::timeaxisview_deleted, tv);
5205
5206         RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (tv);
5207         
5208         _routes->route_removed (tv);
5209
5210         if (tv == entered_track) {
5211                 entered_track = 0;
5212         }
5213
5214         TimeAxisView::Children c = tv->get_child_list ();
5215         for (TimeAxisView::Children::const_iterator i = c.begin(); i != c.end(); ++i) {
5216                 if (entered_track == i->get()) {
5217                         entered_track = 0;
5218                 }
5219         }
5220
5221         /* remove it from the list of track views */
5222
5223         TrackViewList::iterator i;
5224
5225         if ((i = find (track_views.begin(), track_views.end(), tv)) != track_views.end()) {
5226                 i = track_views.erase (i);
5227         }
5228
5229         /* update whatever the current mixer strip is displaying, if revelant */
5230
5231         boost::shared_ptr<Route> route;
5232
5233         if (rtav) {
5234                 route = rtav->route ();
5235         } 
5236
5237         if (current_mixer_strip && current_mixer_strip->route() == route) {
5238
5239                 TimeAxisView* next_tv;
5240
5241                 if (track_views.empty()) {
5242                         next_tv = 0;
5243                 } else if (i == track_views.end()) {
5244                         next_tv = track_views.front();
5245                 } else {
5246                         next_tv = (*i);
5247                 }
5248                 
5249                 
5250                 if (next_tv) {
5251                         set_selected_mixer_strip (*next_tv);
5252                 } else {
5253                         /* make the editor mixer strip go away setting the
5254                          * button to inactive (which also unticks the menu option)
5255                          */
5256                         
5257                         ActionManager::uncheck_toggleaction ("<Actions>/Editor/show-editor-mixer");
5258                 }
5259         } 
5260 }
5261
5262 void
5263 Editor::hide_track_in_display (TimeAxisView* tv, bool /*temponly*/)
5264 {
5265         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (tv);
5266
5267         if (rtv && current_mixer_strip && (rtv->route() == current_mixer_strip->route())) {
5268                 // this will hide the mixer strip
5269                 set_selected_mixer_strip (*tv);
5270         }
5271
5272         _routes->hide_track_in_display (*tv);
5273 }
5274
5275 bool
5276 Editor::sync_track_view_list_and_routes ()
5277 {
5278         track_views = TrackViewList (_routes->views ());
5279
5280         _summary->set_dirty ();
5281         _group_tabs->set_dirty ();
5282
5283         return false; // do not call again (until needed)
5284 }
5285
5286 void
5287 Editor::foreach_time_axis_view (sigc::slot<void,TimeAxisView&> theslot)
5288 {
5289         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5290                 theslot (**i);
5291         }
5292 }
5293
5294 /** Find a RouteTimeAxisView by the ID of its route */
5295 RouteTimeAxisView*
5296 Editor::get_route_view_by_route_id (PBD::ID& id) const
5297 {
5298         RouteTimeAxisView* v;
5299
5300         for (TrackViewList::const_iterator i = track_views.begin(); i != track_views.end(); ++i) {
5301                 if((v = dynamic_cast<RouteTimeAxisView*>(*i)) != 0) {
5302                         if(v->route()->id() == id) {
5303                                 return v;
5304                         }
5305                 }
5306         }
5307
5308         return 0;
5309 }
5310
5311 void
5312 Editor::fit_route_group (RouteGroup *g)
5313 {
5314         TrackViewList ts = axis_views_from_routes (g->route_list ());
5315         fit_tracks (ts);
5316 }
5317
5318 void
5319 Editor::consider_auditioning (boost::shared_ptr<Region> region)
5320 {
5321         boost::shared_ptr<AudioRegion> r = boost::dynamic_pointer_cast<AudioRegion> (region);
5322
5323         if (r == 0) {
5324                 _session->cancel_audition ();
5325                 return;
5326         }
5327
5328         if (_session->is_auditioning()) {
5329                 _session->cancel_audition ();
5330                 if (r == last_audition_region) {
5331                         return;
5332                 }
5333         }
5334
5335         _session->audition_region (r);
5336         last_audition_region = r;
5337 }
5338
5339
5340 void
5341 Editor::hide_a_region (boost::shared_ptr<Region> r)
5342 {
5343         r->set_hidden (true);
5344 }
5345
5346 void
5347 Editor::show_a_region (boost::shared_ptr<Region> r)
5348 {
5349         r->set_hidden (false);
5350 }
5351
5352 void
5353 Editor::audition_region_from_region_list ()
5354 {
5355         _regions->selection_mapover (sigc::mem_fun (*this, &Editor::consider_auditioning));
5356 }
5357
5358 void
5359 Editor::hide_region_from_region_list ()
5360 {
5361         _regions->selection_mapover (sigc::mem_fun (*this, &Editor::hide_a_region));
5362 }
5363
5364 void
5365 Editor::show_region_in_region_list ()
5366 {
5367         _regions->selection_mapover (sigc::mem_fun (*this, &Editor::show_a_region));
5368 }
5369
5370 void
5371 Editor::step_edit_status_change (bool yn)
5372 {
5373         if (yn) {
5374                 start_step_editing ();
5375         } else {
5376                 stop_step_editing ();
5377         }
5378 }
5379
5380 void
5381 Editor::start_step_editing ()
5382 {
5383         step_edit_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &Editor::check_step_edit), 20);
5384 }
5385
5386 void
5387 Editor::stop_step_editing ()
5388 {
5389         step_edit_connection.disconnect ();
5390 }
5391
5392 bool
5393 Editor::check_step_edit ()
5394 {
5395         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5396                 MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*> (*i);
5397                 if (mtv) {
5398                         mtv->check_step_edit ();
5399                 }
5400         }
5401
5402         return true; // do it again, till we stop
5403 }
5404
5405 bool
5406 Editor::horizontal_scroll_left_press ()
5407 {
5408         ++_scroll_callbacks;
5409         
5410         if (_scroll_connection.connected() && _scroll_callbacks < 5) {
5411                 /* delay the first auto-repeat */
5412                 return true;
5413         }
5414                 
5415         double x = leftmost_position() - current_page_frames() / 5;
5416         if (x < 0) {
5417                 x = 0;
5418         }
5419         
5420         reset_x_origin (x);
5421
5422         /* do hacky auto-repeat */
5423         if (!_scroll_connection.connected ()) {
5424                 _scroll_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_left_press), 100);
5425                 _scroll_callbacks = 0;
5426         }
5427
5428         return true;
5429 }
5430
5431 void
5432 Editor::horizontal_scroll_left_release ()
5433 {
5434         _scroll_connection.disconnect ();
5435 }
5436
5437 bool
5438 Editor::horizontal_scroll_right_press ()
5439 {
5440         ++_scroll_callbacks;
5441         
5442         if (_scroll_connection.connected() && _scroll_callbacks < 5) {
5443                 /* delay the first auto-repeat */
5444                 return true;
5445         }
5446
5447         reset_x_origin (leftmost_position() + current_page_frames() / 5);
5448
5449         /* do hacky auto-repeat */
5450         if (!_scroll_connection.connected ()) {
5451                 _scroll_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_right_press), 100);
5452                 _scroll_callbacks = 0;
5453         }
5454
5455         return true;
5456 }
5457
5458 void
5459 Editor::horizontal_scroll_right_release ()
5460 {
5461         _scroll_connection.disconnect ();
5462 }
5463
5464 /** Queue a change for the Editor viewport x origin to follow the playhead */
5465 void
5466 Editor::reset_x_origin_to_follow_playhead ()
5467 {
5468         framepos_t const frame = playhead_cursor->current_frame;
5469
5470         if (frame < leftmost_frame || frame > leftmost_frame + current_page_frames()) {
5471
5472                 if (_session->transport_speed() < 0) {
5473                         
5474                         if (frame > (current_page_frames() / 2)) {
5475                                 center_screen (frame-(current_page_frames()/2));
5476                         } else {
5477                                 center_screen (current_page_frames()/2);
5478                         }
5479                         
5480                 } else {
5481                                                 
5482                         if (frame < leftmost_frame) {
5483                                 /* moving left */
5484                                 framepos_t l = 0;
5485                                 if (_session->transport_rolling()) {
5486                                         /* rolling; end up with the playhead at the right of the page */
5487                                         l = frame - current_page_frames ();
5488                                 } else {
5489                                         /* not rolling: end up with the playhead 3/4 of the way along the page */
5490                                         l = frame - (3 * current_page_frames() / 4);
5491                                 }
5492                                 
5493                                 if (l < 0) {
5494                                         l = 0;
5495                                 }
5496                                 
5497                                 center_screen_internal (l + (current_page_frames() / 2), current_page_frames ());
5498                         } else {
5499                                 /* moving right */
5500                                 if (_session->transport_rolling()) {
5501                                         /* rolling: end up with the playhead on the left of the page */
5502                                         center_screen_internal (frame + (current_page_frames() / 2), current_page_frames ());
5503                                 } else {
5504                                         /* not rolling: end up with the playhead 1/4 of the way along the page */
5505                                         center_screen_internal (frame + (current_page_frames() / 4), current_page_frames ());
5506                                 }
5507                         }
5508                 }
5509         }
5510 }
5511
5512 void
5513 Editor::super_rapid_screen_update ()
5514 {
5515         if (!_session || !_session->engine().running()) {
5516                 return;
5517         }
5518
5519         /* METERING / MIXER STRIPS */
5520
5521         /* update track meters, if required */
5522         if (is_mapped() && meters_running) {
5523                 RouteTimeAxisView* rtv;
5524                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5525                         if ((rtv = dynamic_cast<RouteTimeAxisView*>(*i)) != 0) {
5526                                 rtv->fast_update ();
5527                         }
5528                 }
5529         }
5530
5531         /* and any current mixer strip */
5532         if (current_mixer_strip) {
5533                 current_mixer_strip->fast_update ();
5534         }
5535
5536         /* PLAYHEAD AND VIEWPORT */
5537
5538         framepos_t const frame = _session->audible_frame();
5539
5540         /* There are a few reasons why we might not update the playhead / viewport stuff:
5541          *
5542          * 1.  we don't update things when there's a pending locate request, otherwise
5543          *     when the editor requests a locate there is a chance that this method
5544          *     will move the playhead before the locate request is processed, causing
5545          *     a visual glitch.
5546          * 2.  if we're not rolling, there's nothing to do here (locates are handled elsewhere).
5547          * 3.  if we're still at the same frame that we were last time, there's nothing to do.
5548          */
5549
5550         if (!_pending_locate_request && _session->transport_speed() != 0 && frame != last_update_frame) {
5551
5552                 last_update_frame = frame;
5553
5554                 if (!_dragging_playhead) {
5555                         playhead_cursor->set_position (frame);
5556                 }
5557
5558                 if (!_stationary_playhead) {
5559
5560                         if (!_dragging_playhead && _follow_playhead && _session->requested_return_frame() < 0) {
5561                                 reset_x_origin_to_follow_playhead ();
5562                         }
5563
5564                 } else {
5565                         
5566                         /* don't do continuous scroll till the new position is in the rightmost quarter of the
5567                            editor canvas
5568                         */
5569 #if 0                        
5570                         // FIXME DO SOMETHING THAT WORKS HERE - this is 2.X code                         
5571                         double target = ((double)frame - (double)current_page_frames()/2.0) / frames_per_unit;
5572                         if (target <= 0.0) {
5573                                 target = 0.0;
5574                         }
5575                         if (fabs(target - current) < current_page_frames() / frames_per_unit) {
5576                                 target = (target * 0.15) + (current * 0.85);
5577                         } else {
5578                                 /* relax */
5579                         }
5580                         
5581                         current = target;
5582                         set_horizontal_position (current);
5583 #endif
5584                 }
5585                 
5586         }
5587 }
5588
5589
5590 void
5591 Editor::session_going_away ()
5592 {
5593         _have_idled = false;
5594
5595         _session_connections.drop_connections ();
5596
5597         super_rapid_screen_update_connection.disconnect ();
5598         
5599         selection->clear ();
5600         cut_buffer->clear ();
5601
5602         clicked_regionview = 0;
5603         clicked_axisview = 0;
5604         clicked_routeview = 0;
5605         clicked_crossfadeview = 0;
5606         entered_regionview = 0;
5607         entered_track = 0;
5608         last_update_frame = 0;
5609         _drags->abort ();
5610
5611         playhead_cursor->canvas_item.hide ();
5612
5613         /* rip everything out of the list displays */
5614
5615         _regions->clear ();
5616         _routes->clear ();
5617         _route_groups->clear ();
5618
5619         /* do this first so that deleting a track doesn't reset cms to null
5620            and thus cause a leak.
5621         */
5622
5623         if (current_mixer_strip) {
5624                 if (current_mixer_strip->get_parent() != 0) {
5625                         global_hpacker.remove (*current_mixer_strip);
5626                 }
5627                 delete current_mixer_strip;
5628                 current_mixer_strip = 0;
5629         }
5630
5631         /* delete all trackviews */
5632
5633         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5634                 delete *i;
5635         }
5636         track_views.clear ();
5637
5638         zoom_range_clock.set_session (0);
5639         nudge_clock.set_session (0);
5640
5641         editor_list_button.set_active(false);
5642         editor_list_button.set_sensitive(false);
5643
5644         /* clear tempo/meter rulers */
5645         remove_metric_marks ();
5646         hide_measures ();
5647         clear_marker_display ();
5648
5649         delete current_bbt_points;
5650         current_bbt_points = 0;
5651
5652         /* get rid of any existing editor mixer strip */
5653
5654         WindowTitle title(Glib::get_application_name());
5655         title += _("Editor");
5656
5657         set_title (title.get_string());
5658
5659         SessionHandlePtr::session_going_away ();
5660 }
5661
5662
5663 void
5664 Editor::show_editor_list (bool yn)
5665 {
5666         if (yn) {
5667                 the_notebook.show();
5668         } else {
5669                 the_notebook.hide();
5670         }
5671 }
5672
5673 void
5674 Editor::change_region_layering_order (framepos_t position)
5675 {
5676         if (!clicked_routeview) {
5677                 if (layering_order_editor) {
5678                         layering_order_editor->hide ();
5679                 }
5680                 return;
5681         }
5682
5683         boost::shared_ptr<Track> track = boost::dynamic_pointer_cast<Track> (clicked_routeview->route());
5684
5685         if (!track) {
5686                 return;
5687         }
5688
5689         boost::shared_ptr<Playlist> pl = track->playlist();
5690
5691         if (!pl) {
5692                 return;
5693         }
5694                 
5695         if (layering_order_editor == 0) {
5696                 layering_order_editor = new RegionLayeringOrderEditor(*this);
5697         }
5698
5699         layering_order_editor->set_context (clicked_routeview->name(), _session, pl, position);
5700         layering_order_editor->maybe_present ();
5701 }
5702
5703 void
5704 Editor::update_region_layering_order_editor (framepos_t frame)
5705 {
5706         if (layering_order_editor && layering_order_editor->is_visible ()) {
5707                 change_region_layering_order (frame);
5708         }
5709 }
5710
5711 void
5712 Editor::setup_fade_images ()
5713 {
5714         _fade_in_images[FadeLinear] = new Gtk::Image (get_icon_path (X_("crossfade-in-linear")));
5715         _fade_in_images[FadeFast] = new Gtk::Image (get_icon_path (X_("crossfade-in-short-cut")));
5716         _fade_in_images[FadeLogB] = new Gtk::Image (get_icon_path (X_("crossfade-in-slow-cut")));
5717         _fade_in_images[FadeLogA] = new Gtk::Image (get_icon_path (X_("crossfade-in-fast-cut")));
5718         _fade_in_images[FadeSlow] = new Gtk::Image (get_icon_path (X_("crossfade-in-long-cut")));
5719
5720         _fade_out_images[FadeLinear] = new Gtk::Image (get_icon_path (X_("crossfade-out-linear")));
5721         _fade_out_images[FadeFast] = new Gtk::Image (get_icon_path (X_("crossfade-out-short-cut")));
5722         _fade_out_images[FadeLogB] = new Gtk::Image (get_icon_path (X_("crossfade-out-slow-cut")));
5723         _fade_out_images[FadeLogA] = new Gtk::Image (get_icon_path (X_("crossfade-out-fast-cut")));
5724         _fade_out_images[FadeSlow] = new Gtk::Image (get_icon_path (X_("crossfade-out-long-cut")));
5725 }
5726