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