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