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