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