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