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