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