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