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