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