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