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