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