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