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