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