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