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