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