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