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