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