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