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