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