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