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