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