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