76731ea439a188918e32a3c6384692bb4bb35d0c
[ardour.git] / gtk2_ardour / editor.cc
1 /*
2     Copyright (C) 2000-2006 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     $Id$
19 */
20
21 #include <unistd.h>
22 #include <cstdlib>
23 #include <cmath>
24 #include <string>
25 #include <algorithm>
26
27 #include <sigc++/bind.h>
28
29 #include <pbd/convert.h>
30 #include <pbd/error.h>
31 #include <pbd/memento_command.h>
32
33 #include <gtkmm/image.h>
34 #include <gdkmm/color.h>
35 #include <gdkmm/bitmap.h>
36
37 #include <gtkmm2ext/gtk_ui.h>
38 #include <gtkmm2ext/tearoff.h>
39 #include <gtkmm2ext/utils.h>
40
41 #include <ardour/audio_track.h>
42 #include <ardour/audio_diskstream.h>
43 #include <ardour/plugin_manager.h>
44 #include <ardour/location.h>
45 #include <ardour/audioplaylist.h>
46 #include <ardour/audioregion.h>
47 #include <ardour/region.h>
48 #include <ardour/session_route.h>
49 #include <ardour/tempo.h>
50 #include <ardour/utils.h>
51
52 #include <control_protocol/control_protocol.h>
53
54 #include "ardour_ui.h"
55 #include "editor.h"
56 #include "grouped_buttons.h"
57 #include "keyboard.h"
58 #include "marker.h"
59 #include "playlist_selector.h"
60 #include "audio_region_view.h"
61 #include "rgb_macros.h"
62 #include "selection.h"
63 #include "audio_streamview.h"
64 #include "time_axis_view.h"
65 #include "utils.h"
66 #include "crossfade_view.h"
67 #include "editing.h"
68 #include "public_editor.h"
69 #include "crossfade_edit.h"
70 #include "audio_time_axis.h"
71 #include "canvas_impl.h"
72 #include "actions.h"
73 #include "gui_thread.h"
74
75 #ifdef FFT_ANALYSIS
76 #include "analysis_window.h"
77 #endif
78
79 #include "i18n.h"
80
81 /* <CMT Additions> */
82 #include "imageframe_socket_handler.h"
83 /* </CMT Additions> */
84
85 using namespace std;
86 using namespace sigc;
87 using namespace ARDOUR;
88 using namespace PBD;
89 using namespace Gtk;
90 using namespace Glib;
91 using namespace Gtkmm2ext;
92 using namespace Editing;
93
94 using PBD::atoi;
95
96 const double Editor::timebar_height = 15.0;
97
98 #include "editor_xpms"
99
100 static const gchar *_snap_type_strings[] = {
101         N_("None"),
102         N_("CD Frames"),
103         N_("SMPTE Frames"),
104         N_("SMPTE Seconds"),
105         N_("SMPTE Minutes"),
106         N_("Seconds"),
107         N_("Minutes"),
108         N_("Beats/32"),
109         N_("Beats/16"),
110         N_("Beats/8"),
111         N_("Beats/4"),
112         N_("Beats/3"),
113         N_("Beats"),
114         N_("Bars"),
115         N_("Marks"),
116         N_("Edit Cursor"),
117         N_("Region starts"),
118         N_("Region ends"),
119         N_("Region syncs"),
120         N_("Region bounds"),
121         0
122 };
123
124 static const gchar *_snap_mode_strings[] = {
125         N_("Normal"),
126         N_("Magnetic"),
127         0
128 };
129
130 static const gchar *_zoom_focus_strings[] = {
131         N_("Left"),
132         N_("Right"),
133         N_("Center"),
134         N_("Playhead"),
135         N_("Edit Cursor"),
136         0
137 };
138
139 /* Soundfile  drag-n-drop */
140
141 Gdk::Cursor* Editor::cross_hair_cursor = 0;
142 Gdk::Cursor* Editor::selector_cursor = 0;
143 Gdk::Cursor* Editor::trimmer_cursor = 0;
144 Gdk::Cursor* Editor::grabber_cursor = 0;
145 Gdk::Cursor* Editor::zoom_cursor = 0;
146 Gdk::Cursor* Editor::time_fx_cursor = 0;
147 Gdk::Cursor* Editor::fader_cursor = 0;
148 Gdk::Cursor* Editor::speaker_cursor = 0;
149 Gdk::Cursor* Editor::wait_cursor = 0;
150 Gdk::Cursor* Editor::timebar_cursor = 0;
151
152 void
153 show_me_the_size (Requisition* r, const char* what)
154 {
155         cerr << "size of " << what << " = " << r->width << " x " << r->height << endl;
156 }
157
158 void 
159 check_adjustment (Gtk::Adjustment* adj)
160 {
161         cerr << "CHANGE adj  = " 
162              << adj->get_lower () <<  ' '
163              << adj->get_upper () <<  ' '
164              << adj->get_value () <<  ' '
165              << adj->get_step_increment () <<  ' '
166              << adj->get_page_increment () <<  ' '
167              << adj->get_page_size () <<  ' '
168              << endl;
169
170 }
171
172 Editor::Editor (AudioEngine& eng) 
173         : engine (eng),
174
175           /* time display buttons */
176
177           minsec_label (_("Mins:Secs")),
178           bbt_label (_("Bars:Beats")),
179           smpte_label (_("SMPTE")),
180           frame_label (_("Frames")),
181           tempo_label (_("Tempo")),
182           meter_label (_("Meter")),
183           mark_label (_("Location Markers")),
184           range_mark_label (_("Range Markers")),
185           transport_mark_label (_("Loop/Punch Ranges")),
186
187           edit_packer (3, 3, false),
188
189           /* the values here don't matter: layout widgets
190              reset them as needed.
191           */
192
193           vertical_adjustment (0.0, 0.0, 10.0, 400.0),
194           horizontal_adjustment (0.0, 0.0, 20.0, 1200.0),
195
196           /* tool bar related */
197
198           edit_cursor_clock (X_("EditCursorClock"), true),
199           zoom_range_clock (X_("ZoomRangeClock"), true, true),
200           
201           toolbar_selection_clock_table (2,3),
202           
203           automation_mode_button (_("mode")),
204           global_automation_button (_("automation")),
205
206           /* <CMT Additions> */
207           image_socket_listener(0),
208           /* </CMT Additions> */
209
210           /* nudge */
211
212           nudge_clock (X_("NudgeClock"), true, true)
213
214 {
215         constructed = false;
216
217         /* we are a singleton */
218
219         PublicEditor::_instance = this;
220
221         session = 0;
222
223         selection = new Selection;
224         cut_buffer = new Selection;
225
226         selection->TimeChanged.connect (mem_fun(*this, &Editor::time_selection_changed));
227         selection->TracksChanged.connect (mem_fun(*this, &Editor::track_selection_changed));
228         selection->RegionsChanged.connect (mem_fun(*this, &Editor::region_selection_changed));
229         selection->PointsChanged.connect (mem_fun(*this, &Editor::point_selection_changed));
230
231         clicked_regionview = 0;
232         clicked_trackview = 0;
233         clicked_audio_trackview = 0;
234         clicked_crossfadeview = 0;
235         clicked_control_point = 0;
236         latest_regionview = 0;
237         last_update_frame = 0;
238         drag_info.item = 0;
239         current_mixer_strip = 0;
240         current_bbt_points = 0;
241
242         snap_type_strings = I18N (_snap_type_strings);
243         snap_mode_strings = I18N (_snap_mode_strings);
244         zoom_focus_strings = I18N(_zoom_focus_strings);
245
246         snap_type = SnapToFrame;
247         set_snap_to (snap_type);
248         snap_mode = SnapNormal;
249         set_snap_mode (snap_mode);
250         snap_threshold = 5.0;
251         bbt_beat_subdivision = 4;
252         canvas_width = 0;
253         canvas_height = 0;
254         autoscroll_active = false;
255         autoscroll_timeout_tag = -1;
256         interthread_progress_window = 0;
257
258 #ifdef FFT_ANALYSIS
259         analysis_window = 0;
260 #endif
261
262         current_interthread_info = 0;
263         _show_measures = true;
264         _show_waveforms = true;
265         _show_waveforms_recording = true;
266         first_action_message = 0;
267         export_dialog = 0;
268         show_gain_after_trim = false;
269         ignore_route_list_reorder = false;
270         no_route_list_redisplay = false;
271         verbose_cursor_on = true;
272         route_removal = false;
273         track_spacing = 0;
274         show_automatic_regions_in_region_list = true;
275         region_list_sort_type = (Editing::RegionListSortType) 0; 
276         have_pending_keyboard_selection = false;
277         _follow_playhead = true;
278         _xfade_visibility = true;
279         editor_ruler_menu = 0;
280         no_ruler_shown_update = false;
281         edit_group_list_menu = 0;
282         route_list_menu = 0;
283         region_list_menu = 0;
284         marker_menu = 0;
285         range_marker_menu = 0;
286         marker_menu_item = 0;
287         tm_marker_menu = 0;
288         transport_marker_menu = 0;
289         new_transport_marker_menu = 0;
290         editor_mixer_strip_width = Wide;
291         repos_zoom_queued = false;
292         region_edit_menu_split_item = 0;
293         temp_location = 0;
294         region_edit_menu_split_multichannel_item = 0;
295         leftmost_frame = 0;
296         ignore_mouse_mode_toggle = false;
297         current_stepping_trackview = 0;
298         entered_track = 0;
299         entered_regionview = 0;
300         clear_entered_track = false;
301         _new_regionviews_show_envelope = false;
302         current_timestretch = 0;
303         in_edit_group_row_change = false;
304         last_canvas_frame = 0;
305         edit_cursor = 0;
306         playhead_cursor = 0;
307         button_release_can_deselect = true;
308
309         location_marker_color = color_map[cLocationMarker];
310         location_range_color = color_map[cLocationRange];
311         location_cd_marker_color = color_map[cLocationCDMarker];
312         location_loop_color = color_map[cLocationLoop];
313         location_punch_color = color_map[cLocationPunch];
314
315         range_marker_drag_rect = 0;
316         marker_drag_line = 0;
317         
318         set_mouse_mode (MouseObject, true);
319
320         frames_per_unit = 2048; /* too early to use set_frames_per_unit */
321         reset_hscrollbar_stepping ();
322         
323         zoom_focus = ZoomFocusLeft;
324         set_zoom_focus (ZoomFocusLeft);
325         zoom_range_clock.ValueChanged.connect (mem_fun(*this, &Editor::zoom_adjustment_changed));
326
327         initialize_rulers ();
328         initialize_canvas ();
329
330         edit_controls_vbox.set_spacing (0);
331         horizontal_adjustment.signal_value_changed().connect (mem_fun(*this, &Editor::canvas_horizontally_scrolled));
332         vertical_adjustment.signal_value_changed().connect (mem_fun(*this, &Editor::tie_vertical_scrolling));
333         
334         track_canvas.set_hadjustment (horizontal_adjustment);
335         track_canvas.set_vadjustment (vertical_adjustment);
336         time_canvas.set_hadjustment (horizontal_adjustment);
337
338         track_canvas.signal_map_event().connect (mem_fun (*this, &Editor::track_canvas_map_handler));
339         time_canvas.signal_map_event().connect (mem_fun (*this, &Editor::time_canvas_map_handler));
340         
341         controls_layout.add (edit_controls_vbox);
342         controls_layout.set_name ("EditControlsBase");
343         controls_layout.add_events (Gdk::SCROLL_MASK);
344         controls_layout.signal_scroll_event().connect (mem_fun(*this, &Editor::control_layout_scroll), false);
345         
346         controls_layout.add_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK|Gdk::ENTER_NOTIFY_MASK|Gdk::LEAVE_NOTIFY_MASK);
347         controls_layout.signal_button_release_event().connect (mem_fun(*this, &Editor::edit_controls_button_release));
348         controls_layout.signal_size_request().connect (mem_fun (*this, &Editor::controls_layout_size_request));
349
350         edit_vscrollbar.set_adjustment (vertical_adjustment);
351         edit_hscrollbar.set_adjustment (horizontal_adjustment);
352
353         edit_hscrollbar.signal_button_press_event().connect (mem_fun(*this, &Editor::hscrollbar_button_press));
354         edit_hscrollbar.signal_button_release_event().connect (mem_fun(*this, &Editor::hscrollbar_button_release));
355         edit_hscrollbar.signal_size_allocate().connect (mem_fun(*this, &Editor::hscrollbar_allocate));
356
357         build_cursors ();
358         setup_toolbar ();
359
360         edit_cursor_clock.ValueChanged.connect (mem_fun(*this, &Editor::edit_cursor_clock_changed));
361         
362         time_canvas_vbox.pack_start (*minsec_ruler, false, false);
363         time_canvas_vbox.pack_start (*smpte_ruler, false, false);
364         time_canvas_vbox.pack_start (*frames_ruler, false, false);
365         time_canvas_vbox.pack_start (*bbt_ruler, false, false);
366         time_canvas_vbox.pack_start (time_canvas, true, true);
367         time_canvas_vbox.set_size_request (-1, (int)(timebar_height * visible_timebars));
368
369         bbt_label.set_name ("EditorTimeButton");
370         bbt_label.set_size_request (-1, (int)timebar_height);
371         bbt_label.set_alignment (1.0, 0.5);
372         bbt_label.set_padding (5,0);
373         minsec_label.set_name ("EditorTimeButton");
374         minsec_label.set_size_request (-1, (int)timebar_height);
375         minsec_label.set_alignment (1.0, 0.5);
376         minsec_label.set_padding (5,0);
377         smpte_label.set_name ("EditorTimeButton");
378         smpte_label.set_size_request (-1, (int)timebar_height);
379         smpte_label.set_alignment (1.0, 0.5);
380         smpte_label.set_padding (5,0);
381         frame_label.set_name ("EditorTimeButton");
382         frame_label.set_size_request (-1, (int)timebar_height);
383         frame_label.set_alignment (1.0, 0.5);
384         frame_label.set_padding (5,0);
385         tempo_label.set_name ("EditorTimeButton");
386         tempo_label.set_size_request (-1, (int)timebar_height);
387         tempo_label.set_alignment (1.0, 0.5);
388         tempo_label.set_padding (5,0);
389         meter_label.set_name ("EditorTimeButton");
390         meter_label.set_size_request (-1, (int)timebar_height);
391         meter_label.set_alignment (1.0, 0.5);
392         meter_label.set_padding (5,0);
393         mark_label.set_name ("EditorTimeButton");
394         mark_label.set_size_request (-1, (int)timebar_height);
395         mark_label.set_alignment (1.0, 0.5);
396         mark_label.set_padding (5,0);
397         range_mark_label.set_name ("EditorTimeButton");
398         range_mark_label.set_size_request (-1, (int)timebar_height);
399         range_mark_label.set_alignment (1.0, 0.5);
400         range_mark_label.set_padding (5,0);
401         transport_mark_label.set_name ("EditorTimeButton");
402         transport_mark_label.set_size_request (-1, (int)timebar_height);
403         transport_mark_label.set_alignment (1.0, 0.5);
404         transport_mark_label.set_padding (5,0);
405         
406         time_button_vbox.pack_start (minsec_label, false, false);
407         time_button_vbox.pack_start (smpte_label, false, false);
408         time_button_vbox.pack_start (frame_label, false, false);
409         time_button_vbox.pack_start (bbt_label, false, false);
410         time_button_vbox.pack_start (meter_label, false, false);
411         time_button_vbox.pack_start (tempo_label, false, false);
412         time_button_vbox.pack_start (mark_label, false, false);
413
414         time_button_event_box.add (time_button_vbox);
415         
416         time_button_event_box.set_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK);
417         time_button_event_box.set_name ("TimebarLabelBase");
418         time_button_event_box.signal_button_release_event().connect (mem_fun(*this, &Editor::ruler_label_button_release));
419
420         /* these enable us to have a dedicated window (for cursor setting, etc.) 
421            for the canvas areas.
422         */
423
424         track_canvas_event_box.add (track_canvas);
425
426         time_canvas_event_box.add (time_canvas_vbox);
427         time_canvas_event_box.set_events (Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK|Gdk::POINTER_MOTION_MASK);
428         
429         edit_packer.set_col_spacings (0);
430         edit_packer.set_row_spacings (0);
431         edit_packer.set_homogeneous (false);
432         edit_packer.set_border_width (0);
433         edit_packer.set_name ("EditorWindow");
434         
435         edit_packer.attach (edit_vscrollbar,         0, 1, 1, 3,    FILL,        FILL|EXPAND, 0, 0);
436
437         edit_packer.attach (time_button_event_box,   1, 2, 0, 1,    FILL,        FILL, 0, 0);
438         edit_packer.attach (time_canvas_event_box,   2, 3, 0, 1,    FILL|EXPAND, FILL, 0, 0);
439
440         edit_packer.attach (controls_layout,         1, 2, 1, 2,    FILL,        FILL|EXPAND, 0, 0);
441         edit_packer.attach (track_canvas_event_box,  2, 3, 1, 2,    FILL|EXPAND, FILL|EXPAND, 0, 0);
442
443         edit_packer.attach (edit_hscrollbar,         2, 3, 2, 3,    FILL|EXPAND,  FILL, 0, 0);
444
445         bottom_hbox.set_border_width (2);
446         bottom_hbox.set_spacing (3);
447
448         route_display_model = ListStore::create(route_display_columns);
449         route_list_display.set_model (route_display_model);
450         route_list_display.append_column (_("Visible"), route_display_columns.visible);
451         route_list_display.append_column (_("Name"), route_display_columns.text);
452         route_list_display.get_column (0)->set_data (X_("colnum"), GUINT_TO_POINTER(0));
453         route_list_display.get_column (1)->set_data (X_("colnum"), GUINT_TO_POINTER(1));
454         route_list_display.set_headers_visible (true);
455         route_list_display.set_name ("TrackListDisplay");
456         route_list_display.get_selection()->set_mode (SELECTION_NONE);
457         route_list_display.set_reorderable (true);
458         route_list_display.set_size_request (100,-1);
459
460         CellRendererToggle* route_list_visible_cell = dynamic_cast<CellRendererToggle*>(route_list_display.get_column_cell_renderer (0));
461         route_list_visible_cell->property_activatable() = true;
462         route_list_visible_cell->property_radio() = false;
463         
464         route_display_model->signal_row_deleted().connect (mem_fun (*this, &Editor::route_list_delete));
465         route_display_model->signal_row_changed().connect (mem_fun (*this, &Editor::route_list_change));
466
467         route_list_display.signal_button_press_event().connect (mem_fun (*this, &Editor::route_list_display_button_press), false);
468
469         route_list_scroller.add (route_list_display);
470         route_list_scroller.set_policy (POLICY_NEVER, POLICY_AUTOMATIC);
471
472         group_model = ListStore::create(group_columns);
473         edit_group_display.set_model (group_model);
474         edit_group_display.append_column (_("Name"), group_columns.text);
475         edit_group_display.append_column (_("Active"), group_columns.is_active);
476         edit_group_display.append_column (_("Visible"), group_columns.is_visible);
477         edit_group_display.get_column (0)->set_data (X_("colnum"), GUINT_TO_POINTER(0));
478         edit_group_display.get_column (1)->set_data (X_("colnum"), GUINT_TO_POINTER(1));
479         edit_group_display.get_column (2)->set_data (X_("colnum"), GUINT_TO_POINTER(2));
480         edit_group_display.get_column (0)->set_expand (true);
481         edit_group_display.get_column (1)->set_expand (false);
482         edit_group_display.get_column (2)->set_expand (false);
483         edit_group_display.set_headers_visible (true);
484
485         /* name is directly editable */
486
487         CellRendererText* name_cell = dynamic_cast<CellRendererText*>(edit_group_display.get_column_cell_renderer (0));
488         name_cell->property_editable() = true;
489         name_cell->signal_edited().connect (mem_fun (*this, &Editor::edit_group_name_edit));
490
491         /* use checkbox for the active + visible columns */
492
493         CellRendererToggle* active_cell = dynamic_cast<CellRendererToggle*>(edit_group_display.get_column_cell_renderer (1));
494         active_cell->property_activatable() = true;
495         active_cell->property_radio() = false;
496
497         active_cell = dynamic_cast<CellRendererToggle*>(edit_group_display.get_column_cell_renderer (1));
498         active_cell->property_activatable() = true;
499         active_cell->property_radio() = false;
500
501         edit_group_display.set_name ("EditGroupList");
502
503         group_model->signal_row_changed().connect (mem_fun (*this, &Editor::edit_group_row_change));
504
505         edit_group_display.set_name ("EditGroupList");
506         edit_group_display.get_selection()->set_mode (SELECTION_SINGLE);
507         edit_group_display.set_reorderable (false);
508         edit_group_display.set_rules_hint (true);
509         edit_group_display.set_size_request (75, -1);
510
511         edit_group_display_scroller.add (edit_group_display);
512         edit_group_display_scroller.set_policy (POLICY_AUTOMATIC, POLICY_AUTOMATIC);
513
514         edit_group_display.signal_button_press_event().connect (mem_fun(*this, &Editor::edit_group_list_button_press_event), false);
515
516         VBox* edit_group_display_packer = manage (new VBox());
517         HButtonBox* edit_group_display_button_box = manage (new HButtonBox());
518         edit_group_display_button_box->set_homogeneous (true);
519
520         Button* edit_group_add_button = manage (new Button ());
521         Button* edit_group_remove_button = manage (new Button ());
522
523         Widget* w;
524
525         w = manage (new Image (Stock::ADD, ICON_SIZE_BUTTON));
526         w->show();
527         edit_group_add_button->add (*w);
528
529         w = manage (new Image (Stock::REMOVE, ICON_SIZE_BUTTON));
530         w->show();
531         edit_group_remove_button->add (*w);
532
533         edit_group_add_button->signal_clicked().connect (mem_fun (*this, &Editor::new_edit_group));
534         edit_group_remove_button->signal_clicked().connect (mem_fun (*this, &Editor::remove_selected_edit_group));
535         
536         edit_group_display_button_box->pack_start (*edit_group_add_button);
537         edit_group_display_button_box->pack_start (*edit_group_remove_button);
538
539         edit_group_display_packer->pack_start (edit_group_display_scroller, true, true);
540         edit_group_display_packer->pack_start (*edit_group_display_button_box, false, false);
541
542         region_list_display.set_size_request (100, -1);
543         region_list_display.set_name ("RegionListDisplay");
544
545         region_list_model = TreeStore::create (region_list_columns);
546         region_list_model->set_sort_func (0, mem_fun (*this, &Editor::region_list_sorter));
547         region_list_model->set_sort_column (0, SORT_ASCENDING);
548
549         region_list_display.set_model (region_list_model);
550         region_list_display.append_column (_("Regions"), region_list_columns.name);
551         region_list_display.set_headers_visible (false);
552         region_list_display.set_hover_expand (true);
553
554         region_list_display.get_selection()->set_select_function (mem_fun (*this, &Editor::region_list_selection_filter));
555         
556         TreeViewColumn* tv_col = region_list_display.get_column(0);
557         CellRendererText* renderer = dynamic_cast<CellRendererText*>(region_list_display.get_column_cell_renderer (0));
558         tv_col->add_attribute(renderer->property_text(), region_list_columns.name);
559         tv_col->add_attribute(renderer->property_foreground_gdk(), region_list_columns.color_);
560         
561         region_list_display.get_selection()->set_mode (SELECTION_MULTIPLE);
562         region_list_display.add_object_drag (region_list_columns.region.index(), "regions");
563
564         /* setup DnD handling */
565         
566         list<TargetEntry> region_list_target_table;
567         
568         region_list_target_table.push_back (TargetEntry ("text/plain"));
569         region_list_target_table.push_back (TargetEntry ("text/uri-list"));
570         region_list_target_table.push_back (TargetEntry ("application/x-rootwin-drop"));
571         
572         region_list_display.add_drop_targets (region_list_target_table);
573         region_list_display.signal_drag_data_received().connect (mem_fun(*this, &Editor::region_list_display_drag_data_received));
574
575         region_list_scroller.add (region_list_display);
576         region_list_scroller.set_policy (POLICY_NEVER, POLICY_AUTOMATIC);
577
578         region_list_display.signal_key_press_event().connect (mem_fun(*this, &Editor::region_list_display_key_press));
579         region_list_display.signal_key_release_event().connect (mem_fun(*this, &Editor::region_list_display_key_release));
580         region_list_display.signal_button_press_event().connect (mem_fun(*this, &Editor::region_list_display_button_press), false);
581         region_list_display.signal_button_release_event().connect (mem_fun(*this, &Editor::region_list_display_button_release));
582         region_list_display.get_selection()->signal_changed().connect (mem_fun(*this, &Editor::region_list_selection_changed));
583         // region_list_display.signal_popup_menu().connect (bind (mem_fun (*this, &Editor::show_region_list_display_context_menu), 1, 0));
584         
585         named_selection_scroller.add (named_selection_display);
586         named_selection_scroller.set_policy (POLICY_NEVER, POLICY_AUTOMATIC);
587
588         named_selection_model = TreeStore::create (named_selection_columns);
589         named_selection_display.set_model (named_selection_model);
590         named_selection_display.append_column (_("Chunks"), named_selection_columns.text);
591         named_selection_display.set_headers_visible (false);
592         named_selection_display.set_size_request (100, -1);
593         named_selection_display.set_name ("RegionListDisplay");
594         
595         named_selection_display.get_selection()->set_mode (SELECTION_SINGLE);
596         named_selection_display.set_size_request (100, -1);
597         named_selection_display.signal_button_press_event().connect (mem_fun(*this, &Editor::named_selection_display_button_press), false);
598         named_selection_display.get_selection()->signal_changed().connect (mem_fun (*this, &Editor::named_selection_display_selection_changed));
599
600         /* SNAPSHOTS */
601
602         snapshot_display_model = ListStore::create (snapshot_display_columns);
603         snapshot_display.set_model (snapshot_display_model);
604         snapshot_display.append_column (X_("snapshot"), snapshot_display_columns.visible_name);
605         snapshot_display.set_name ("SnapshotDisplayList");
606         snapshot_display.set_size_request (75, -1);
607         snapshot_display.set_headers_visible (false);
608         snapshot_display.set_reorderable (false);
609         snapshot_display_scroller.add (snapshot_display);
610         snapshot_display_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
611
612         snapshot_display.get_selection()->signal_changed().connect (mem_fun(*this, &Editor::snapshot_display_selection_changed));
613         snapshot_display.signal_button_press_event().connect (mem_fun (*this, &Editor::snapshot_display_button_press), false);
614
615         Gtk::Label* nlabel;
616
617         nlabel = manage (new Label (_("Regions")));
618         nlabel->set_angle (-90);
619         the_notebook.append_page (region_list_scroller, *nlabel);
620         nlabel = manage (new Label (_("Tracks/Busses")));
621         nlabel->set_angle (-90);
622         the_notebook.append_page (route_list_scroller, *nlabel);
623         nlabel = manage (new Label (_("Snapshots")));
624         nlabel->set_angle (-90);
625         the_notebook.append_page (snapshot_display_scroller, *nlabel);
626         nlabel = manage (new Label (_("Edit Groups")));
627         nlabel->set_angle (-90);
628         the_notebook.append_page (*edit_group_display_packer, *nlabel);
629         nlabel = manage (new Label (_("Chunks")));
630         nlabel->set_angle (-90);
631         the_notebook.append_page (named_selection_scroller, *nlabel);
632
633         the_notebook.set_show_tabs (true);
634         the_notebook.set_scrollable (true);
635         the_notebook.popup_enable ();
636         the_notebook.set_tab_pos (Gtk::POS_RIGHT);
637
638         edit_pane.pack1 (edit_packer, true, true);
639         edit_pane.pack2 (the_notebook, false, true);
640         
641         edit_pane.signal_size_allocate().connect (bind (mem_fun(*this, &Editor::pane_allocation_handler), static_cast<Paned*> (&edit_pane)));
642
643         top_hbox.pack_start (toolbar_frame, true, true);
644
645         HBox *hbox = manage (new HBox);
646         hbox->pack_start (edit_pane, true, true);
647
648         global_vpacker.pack_start (top_hbox, false, false);
649         global_vpacker.pack_start (*hbox, true, true);
650
651         global_hpacker.pack_start (global_vpacker, true, true);
652
653         set_name ("EditorWindow");
654         add_accel_group (ActionManager::ui_manager->get_accel_group());
655
656         vpacker.pack_end (global_hpacker, true, true);
657
658         /* register actions now so that set_state() can find them and set toggles/checks etc */
659         
660         register_actions ();
661         
662         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
663         set_state (*node);
664
665         _playlist_selector = new PlaylistSelector();
666         _playlist_selector->signal_delete_event().connect (bind (sigc::ptr_fun (just_hide_it), static_cast<Window *> (_playlist_selector)));
667
668         RegionView::RegionViewGoingAway.connect (mem_fun(*this, &Editor::catch_vanishing_regionview));
669
670         /* nudge stuff */
671
672         nudge_forward_button.add (*(manage (new Image (::get_icon("nudge_right")))));
673         nudge_backward_button.add (*(manage (new Image (::get_icon("nudge_left")))));
674
675         ARDOUR_UI::instance()->tooltips().set_tip (nudge_forward_button, _("Nudge Region/Selection Forwards"));
676         ARDOUR_UI::instance()->tooltips().set_tip (nudge_backward_button, _("Nudge Region/Selection Backwards"));
677
678         nudge_forward_button.set_name ("TransportButton");
679         nudge_backward_button.set_name ("TransportButton");
680
681         fade_context_menu.set_name ("ArdourContextMenu");
682
683         set_title (_("ardour: editor"));
684         set_wmclass (_("ardour_editor"), "Ardour");
685
686         add (vpacker);
687         add_events (Gdk::KEY_PRESS_MASK|Gdk::KEY_RELEASE_MASK);
688
689         signal_configure_event().connect (mem_fun (*ARDOUR_UI::instance(), &ARDOUR_UI::configure_handler));
690         signal_delete_event().connect (mem_fun (*ARDOUR_UI::instance(), &ARDOUR_UI::exit_on_main_window_close));
691
692         /* allow external control surfaces/protocols to do various things */
693
694         ControlProtocol::ZoomToSession.connect (mem_fun (*this, &Editor::temporal_zoom_session));
695         ControlProtocol::ZoomIn.connect (bind (mem_fun (*this, &Editor::temporal_zoom_step), false));
696         ControlProtocol::ZoomOut.connect (bind (mem_fun (*this, &Editor::temporal_zoom_step), true));
697         ControlProtocol::ScrollTimeline.connect (mem_fun (*this, &Editor::control_scroll));
698
699         Config->ParameterChanged.connect (mem_fun (*this, &Editor::parameter_changed));
700
701         constructed = true;
702         instant_save ();
703 }
704
705 Editor::~Editor()
706 {
707         /* <CMT Additions> */
708         if(image_socket_listener)
709         {
710                 if(image_socket_listener->is_connected())
711                 {
712                         image_socket_listener->close_connection() ;
713                 }
714                 
715                 delete image_socket_listener ;
716                 image_socket_listener = 0 ;
717         }
718         /* </CMT Additions> */
719 }
720
721 void
722 Editor::add_toplevel_controls (Container& cont)
723 {
724         vpacker.pack_start (cont, false, false);
725         cont.show_all ();
726 }
727
728 void
729 Editor::catch_vanishing_regionview (RegionView *rv)
730 {
731         /* note: the selection will take care of the vanishing
732            audioregionview by itself.
733         */
734
735         if (clicked_regionview == rv) {
736                 clicked_regionview = 0;
737         }
738
739         if (entered_regionview == rv) {
740                 set_entered_regionview (0);
741         }
742 }
743
744 void
745 Editor::set_entered_regionview (RegionView* rv)
746 {
747         if (rv == entered_regionview) {
748                 return;
749         }
750
751         if (entered_regionview) {
752                 entered_regionview->exited ();
753         }
754
755         if ((entered_regionview = rv) != 0) {
756                 entered_regionview->entered ();
757         }
758 }
759
760 void
761 Editor::set_entered_track (TimeAxisView* tav)
762 {
763         if (entered_track) {
764                 entered_track->exited ();
765         }
766
767         if ((entered_track = tav) != 0) {
768                 entered_track->entered ();
769         }
770 }
771
772 void
773 Editor::show_window ()
774 {
775         show_all ();
776         present ();
777
778         /* now reset all audio_time_axis heights, because widgets might need
779            to be re-hidden
780         */
781         
782         TimeAxisView *tv;
783         
784         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
785                 tv = (static_cast<TimeAxisView*>(*i));
786                 tv->reset_height ();
787         }
788 }
789
790 void
791 Editor::tie_vertical_scrolling ()
792 {
793         double y1 = vertical_adjustment.get_value();
794         controls_layout.get_vadjustment()->set_value (y1);
795         playhead_cursor->set_y_axis(y1);
796         edit_cursor->set_y_axis(y1);
797 }
798
799 void
800 Editor::set_frames_per_unit (double fpu)
801 {
802         nframes_t frames;
803
804         if (fpu == frames_per_unit) {
805                 return;
806         }
807
808         if (fpu < 2.0) {
809                 fpu = 2.0;
810         }
811
812         // convert fpu to frame count
813
814         frames = (nframes_t) floor (fpu * canvas_width);
815         
816         /* don't allow zooms that fit more than the maximum number
817            of frames into an 800 pixel wide space.
818         */
819
820         if (max_frames / fpu < 800.0) {
821                 return;
822         }
823
824         if (fpu == frames_per_unit) {
825                 return;
826         }
827
828         frames_per_unit = fpu;
829
830         if (frames != zoom_range_clock.current_duration()) {
831                 zoom_range_clock.set (frames);
832         }
833
834         if (mouse_mode == MouseRange && selection->time.start () != selection->time.end_frame ()) {
835                 if (!selection->tracks.empty()) {
836                         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
837                                 (*i)->reshow_selection (selection->time);
838                         }
839                 } else {
840                         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
841                                 (*i)->reshow_selection (selection->time);
842                         }
843                 }
844         }
845
846         ZoomChanged (); /* EMIT_SIGNAL */
847
848         reset_hscrollbar_stepping ();
849         reset_scrolling_region ();
850         
851         if (edit_cursor) edit_cursor->set_position (edit_cursor->current_frame);
852         if (playhead_cursor) playhead_cursor->set_position (playhead_cursor->current_frame);
853
854         instant_save ();
855
856 }
857
858 void
859 Editor::instant_save ()
860 {
861         if (!constructed || !ARDOUR_UI::instance()->session_loaded) {
862                 return;
863         }
864
865         if (session) {
866                 session->add_instant_xml(get_state(), session->path());
867         } else {
868                 Config->add_instant_xml(get_state(), get_user_ardour_path());
869         }
870 }
871
872 void
873 Editor::reposition_x_origin (nframes_t frame)
874 {
875         if (frame != leftmost_frame) {
876                 leftmost_frame = frame;
877                 
878                 nframes_t rightmost_frame = leftmost_frame + current_page_frames ();
879
880                 if (rightmost_frame > last_canvas_frame) {
881                         last_canvas_frame = rightmost_frame;
882                         reset_scrolling_region ();
883                 }
884
885                 horizontal_adjustment.set_value (frame/frames_per_unit);
886         } else {
887                 update_fixed_rulers();
888                 tempo_map_changed (Change (0));
889         }
890 }
891
892 void
893 Editor::edit_cursor_clock_changed()
894 {
895         if (edit_cursor->current_frame != edit_cursor_clock.current_time()) {
896                 edit_cursor->set_position (edit_cursor_clock.current_time());
897         }
898 }
899
900
901 void
902 Editor::zoom_adjustment_changed ()
903 {
904         if (session == 0) {
905                 return;
906         }
907
908         double fpu = zoom_range_clock.current_duration() / canvas_width;
909
910         if (fpu < 1.0) {
911                 fpu = 1.0;
912                 zoom_range_clock.set ((nframes_t) floor (fpu * canvas_width));
913         } else if (fpu > session->current_end_frame() / canvas_width) {
914                 fpu = session->current_end_frame() / canvas_width;
915                 zoom_range_clock.set ((nframes_t) floor (fpu * canvas_width));
916         }
917         
918         temporal_zoom (fpu);
919 }
920
921 void
922 Editor::control_scroll (float fraction)
923 {
924         ENSURE_GUI_THREAD(bind (mem_fun (*this, &Editor::control_scroll), fraction));
925
926         if (!session) {
927                 return;
928         }
929
930         double step = fraction * current_page_frames();
931         nframes_t target;
932
933         if ((fraction < 0.0f) && (session->transport_frame() < (nframes_t) fabs(step))) {
934                 target = 0;
935         } else if ((fraction > 0.0f) && (max_frames - session->transport_frame() < step)) {
936                 target = (max_frames - (current_page_frames()*2)); // allow room for slop in where the PH is on the screen
937         } else {
938                 target = (session->transport_frame() + (nframes_t) floor ((fraction * current_page_frames())));
939         }
940
941         /* move visuals, we'll catch up with it later */
942
943         playhead_cursor->set_position (target);
944
945         if (target > (current_page_frames() / 2)) {
946                 /* try to center PH in window */
947                 reposition_x_origin (target - (current_page_frames()/2));
948         } else {
949                 reposition_x_origin (0);
950         }
951
952         /* cancel the existing */
953
954         control_scroll_connection.disconnect ();
955
956         /* add the next one */
957
958         control_scroll_connection = Glib::signal_timeout().connect (bind (mem_fun (*this, &Editor::deferred_control_scroll), target), 50);
959 }
960
961 bool
962 Editor::deferred_control_scroll (nframes_t target)
963 {
964         session->request_locate (target);
965         return false;
966 }
967
968 void 
969 Editor::canvas_horizontally_scrolled ()
970 {
971
972         leftmost_frame = (nframes_t) floor (horizontal_adjustment.get_value() * frames_per_unit);
973         update_fixed_rulers ();
974         tempo_map_changed (Change (0));
975
976 }
977
978 void
979 Editor::reposition_and_zoom (nframes_t frame, double nfpu)
980 {
981         if (!repos_zoom_queued) {
982                 repos_zoom_queued = true;
983                 Glib::signal_idle().connect (bind (mem_fun(*this, &Editor::deferred_reposition_and_zoom), frame, nfpu));
984         }
985 }
986
987 gint
988 Editor::deferred_reposition_and_zoom (nframes_t frame, double nfpu)
989 {
990
991         set_frames_per_unit (nfpu);
992         reposition_x_origin  (frame);
993         repos_zoom_queued = false;
994         
995         return FALSE;
996 }
997
998 void
999 Editor::on_realize ()
1000 {
1001         Window::on_realize ();
1002         Realized ();
1003 }
1004
1005 void
1006 Editor::start_scrolling ()
1007 {
1008         scroll_connection = ARDOUR_UI::instance()->SuperRapidScreenUpdate.connect 
1009                 (mem_fun(*this, &Editor::update_current_screen));
1010 }
1011
1012 void
1013 Editor::stop_scrolling ()
1014 {
1015         scroll_connection.disconnect ();
1016 }
1017
1018 void
1019 Editor::map_position_change (nframes_t frame)
1020 {
1021         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::map_position_change), frame));
1022
1023         if (session == 0 || !_follow_playhead) {
1024                 return;
1025         }
1026
1027         center_screen (frame);
1028         playhead_cursor->set_position (frame);
1029 }       
1030
1031 void
1032 Editor::center_screen (nframes_t frame)
1033 {
1034         double page = canvas_width * frames_per_unit;
1035
1036         /* if we're off the page, then scroll.
1037          */
1038         
1039         if (frame < leftmost_frame || frame >= leftmost_frame + page) {
1040                 center_screen_internal (frame, page);
1041         }
1042 }
1043
1044 void
1045 Editor::center_screen_internal (nframes_t frame, float page)
1046 {
1047         page /= 2;
1048                 
1049         if (frame > page) {
1050                 frame -= (nframes_t) page;
1051         } else {
1052                 frame = 0;
1053         }
1054
1055     reposition_x_origin (frame);
1056 }
1057
1058 void
1059 Editor::handle_new_duration ()
1060 {
1061         ENSURE_GUI_THREAD (mem_fun (*this, &Editor::handle_new_duration));
1062
1063         nframes_t new_end = session->get_maximum_extent() + (nframes_t) floorf (current_page_frames() * 0.10f);
1064                                   
1065         if (new_end > last_canvas_frame) {
1066                 last_canvas_frame = new_end;
1067                 reset_scrolling_region ();
1068         }
1069
1070         horizontal_adjustment.set_value (leftmost_frame/frames_per_unit);
1071 }
1072
1073 void
1074 Editor::update_title_s (const string & snap_name)
1075 {
1076         ENSURE_GUI_THREAD(bind (mem_fun(*this, &Editor::update_title_s), snap_name));
1077         
1078         update_title ();
1079 }
1080
1081 void
1082 Editor::update_title ()
1083 {
1084         ENSURE_GUI_THREAD (mem_fun(*this, &Editor::update_title));
1085
1086         if (session) {
1087                 bool dirty = session->dirty();
1088
1089                 string wintitle = _("ardour: editor: ");
1090
1091                 if (dirty) {
1092                         wintitle += '[';
1093                 }
1094
1095                 wintitle += session->name();
1096
1097                 if (session->snap_name() != session->name()) {
1098                         wintitle += ':';
1099                         wintitle += session->snap_name();
1100                 }
1101
1102                 if (dirty) {
1103                         wintitle += ']';
1104                 }
1105
1106                 set_title (wintitle);
1107         }
1108 }
1109
1110 void
1111 Editor::connect_to_session (Session *t)
1112 {
1113         session = t;
1114
1115         if (first_action_message) {
1116                 first_action_message->hide();
1117         }
1118
1119         update_title ();
1120
1121         session->GoingAway.connect (mem_fun(*this, &Editor::session_going_away));
1122
1123         /* These signals can all be emitted by a non-GUI thread. Therefore the
1124            handlers for them must not attempt to directly interact with the GUI,
1125            but use Gtkmm2ext::UI::instance()->call_slot();
1126         */
1127
1128         session_connections.push_back (session->TransportStateChange.connect (mem_fun(*this, &Editor::map_transport_state)));
1129         session_connections.push_back (session->PositionChanged.connect (mem_fun(*this, &Editor::map_position_change)));
1130         session_connections.push_back (session->RouteAdded.connect (mem_fun(*this, &Editor::handle_new_route)));
1131         session_connections.push_back (session->AudioRegionAdded.connect (mem_fun(*this, &Editor::handle_new_audio_region)));
1132         session_connections.push_back (session->AudioRegionRemoved.connect (mem_fun(*this, &Editor::handle_audio_region_removed)));
1133         session_connections.push_back (session->DurationChanged.connect (mem_fun(*this, &Editor::handle_new_duration)));
1134         session_connections.push_back (session->edit_group_added.connect (mem_fun(*this, &Editor::add_edit_group)));
1135         session_connections.push_back (session->edit_group_removed.connect (mem_fun(*this, &Editor::edit_groups_changed)));
1136         session_connections.push_back (session->NamedSelectionAdded.connect (mem_fun(*this, &Editor::handle_new_named_selection)));
1137         session_connections.push_back (session->NamedSelectionRemoved.connect (mem_fun(*this, &Editor::handle_new_named_selection)));
1138         session_connections.push_back (session->DirtyChanged.connect (mem_fun(*this, &Editor::update_title)));
1139         session_connections.push_back (session->StateSaved.connect (mem_fun(*this, &Editor::update_title_s)));
1140         session_connections.push_back (session->AskAboutPlaylistDeletion.connect (mem_fun(*this, &Editor::playlist_deletion_dialog)));
1141         session_connections.push_back (session->RegionHiddenChange.connect (mem_fun(*this, &Editor::region_hidden)));
1142
1143         session_connections.push_back (session->SMPTEOffsetChanged.connect (mem_fun(*this, &Editor::update_just_smpte)));
1144
1145         session_connections.push_back (session->tempo_map().StateChanged.connect (mem_fun(*this, &Editor::tempo_map_changed)));
1146
1147         edit_groups_changed ();
1148
1149         edit_cursor_clock.set_session (session);
1150         zoom_range_clock.set_session (session);
1151         _playlist_selector->set_session (session);
1152         nudge_clock.set_session (session);
1153
1154 #ifdef FFT_ANALYSIS
1155         if (analysis_window != 0)
1156                 analysis_window->set_session (session);
1157 #endif
1158
1159         Location* loc = session->locations()->auto_loop_location();
1160         if (loc == 0) {
1161                 loc = new Location (0, session->current_end_frame(), _("Loop"),(Location::Flags) (Location::IsAutoLoop | Location::IsHidden));
1162                 if (loc->start() == loc->end()) {
1163                         loc->set_end (loc->start() + 1);
1164                 }
1165                 session->locations()->add (loc, false);
1166                 session->set_auto_loop_location (loc);
1167         }
1168         else {
1169                 // force name
1170                 loc->set_name (_("Loop"));
1171         }
1172         
1173         loc = session->locations()->auto_punch_location();
1174         if (loc == 0) {
1175                 loc = new Location (0, session->current_end_frame(), _("Punch"), (Location::Flags) (Location::IsAutoPunch | Location::IsHidden));
1176                 if (loc->start() == loc->end()) {
1177                         loc->set_end (loc->start() + 1);
1178                 }
1179                 session->locations()->add (loc, false);
1180                 session->set_auto_punch_location (loc);
1181         }
1182         else {
1183                 // force name
1184                 loc->set_name (_("Punch"));
1185         }
1186
1187         Config->map_parameters (mem_fun (*this, &Editor::parameter_changed));
1188         
1189         session->StateSaved.connect (mem_fun(*this, &Editor::session_state_saved));
1190         
1191         refresh_location_display ();
1192         session->locations()->added.connect (mem_fun(*this, &Editor::add_new_location));
1193         session->locations()->removed.connect (mem_fun(*this, &Editor::location_gone));
1194         session->locations()->changed.connect (mem_fun(*this, &Editor::refresh_location_display));
1195         session->locations()->StateChanged.connect (mem_fun(*this, &Editor::refresh_location_display_s));
1196         session->locations()->end_location()->changed.connect (mem_fun(*this, &Editor::end_location_changed));
1197
1198         handle_new_duration ();
1199
1200         redisplay_regions ();
1201         redisplay_named_selections ();
1202         redisplay_snapshots ();
1203
1204         initial_route_list_display ();
1205
1206         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
1207                 (static_cast<TimeAxisView*>(*i))->set_samples_per_unit (frames_per_unit);
1208         }
1209
1210         /* ::reposition_x_origin() doesn't work right here, since the old
1211            position may be zero already, and it does nothing in such
1212            circumstances.
1213         */
1214
1215         leftmost_frame = 0;
1216         
1217         horizontal_adjustment.set_value (0);
1218
1219         restore_ruler_visibility ();
1220         //tempo_map_changed (Change (0));
1221         session->tempo_map().apply_with_metrics (*this, &Editor::draw_metric_marks);
1222
1223         edit_cursor->set_position (0);
1224         playhead_cursor->set_position (0);
1225
1226         start_scrolling ();
1227
1228         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
1229         set_state (*node);
1230
1231         /* don't show master bus in a new session */
1232
1233         if (ARDOUR_UI::instance()->session_is_new ()) {
1234
1235                 TreeModel::Children rows = route_display_model->children();
1236                 TreeModel::Children::iterator i;
1237         
1238                 no_route_list_redisplay = true;
1239                 
1240                 for (i = rows.begin(); i != rows.end(); ++i) {
1241                         TimeAxisView *tv =  (*i)[route_display_columns.tv];
1242                         AudioTimeAxisView *atv;
1243                         
1244                         if ((atv = dynamic_cast<AudioTimeAxisView*>(tv)) != 0) {
1245                                 if (atv->route()->master()) {
1246                                         route_list_display.get_selection()->unselect (i);
1247                                 }
1248                         }
1249                 }
1250                 
1251                 no_route_list_redisplay = false;
1252                 redisplay_route_list ();
1253         }
1254
1255         /* register for undo history */
1256
1257         session->register_with_memento_command_factory(_id, this);
1258 }
1259
1260 void
1261 Editor::build_cursors ()
1262 {
1263         using namespace Gdk;
1264         
1265         Gdk::Color mbg ("#000000" ); /* Black */
1266         Gdk::Color mfg ("#0000ff" ); /* Blue. */
1267
1268         {
1269                 RefPtr<Bitmap> source, mask;
1270                 source = Bitmap::create (mag_bits, mag_width, mag_height);
1271                 mask = Bitmap::create (magmask_bits, mag_width, mag_height);
1272                 zoom_cursor = new Gdk::Cursor (source, mask, mfg, mbg, mag_x_hot, mag_y_hot);
1273         }
1274
1275         Gdk::Color fbg ("#ffffff" );
1276         Gdk::Color ffg  ("#000000" );
1277         
1278         {
1279                 RefPtr<Bitmap> source, mask;
1280                 
1281                 source = Bitmap::create (fader_cursor_bits, fader_cursor_width, fader_cursor_height);
1282                 mask = Bitmap::create (fader_cursor_mask_bits, fader_cursor_width, fader_cursor_height);
1283                 fader_cursor = new Gdk::Cursor (source, mask, ffg, fbg, fader_cursor_x_hot, fader_cursor_y_hot);
1284         }
1285         
1286         { 
1287                 RefPtr<Bitmap> source, mask;
1288                 source = Bitmap::create (speaker_cursor_bits, speaker_cursor_width, speaker_cursor_height);
1289                 mask = Bitmap::create (speaker_cursor_mask_bits, speaker_cursor_width, speaker_cursor_height);
1290                 speaker_cursor = new Gdk::Cursor (source, mask, ffg, fbg, speaker_cursor_x_hot, speaker_cursor_y_hot);
1291         }
1292
1293         grabber_cursor = new Gdk::Cursor (HAND2);
1294         cross_hair_cursor = new Gdk::Cursor (CROSSHAIR);
1295         trimmer_cursor =  new Gdk::Cursor (SB_H_DOUBLE_ARROW);
1296         selector_cursor = new Gdk::Cursor (XTERM);
1297         time_fx_cursor = new Gdk::Cursor (SIZING);
1298         wait_cursor = new Gdk::Cursor  (WATCH);
1299         timebar_cursor = new Gdk::Cursor(LEFT_PTR);
1300 }
1301
1302 void
1303 Editor::popup_fade_context_menu (int button, int32_t time, ArdourCanvas::Item* item, ItemType item_type)
1304 {
1305         using namespace Menu_Helpers;
1306         AudioRegionView* arv = static_cast<AudioRegionView*> (item->get_data ("regionview"));
1307
1308         if (arv == 0) {
1309                 fatal << _("programming error: fade in canvas item has no regionview data pointer!") << endmsg;
1310                 /*NOTREACHED*/
1311         }
1312
1313         MenuList& items (fade_context_menu.items());
1314         AudioRegion& ar (*arv->audio_region().get()); // FIXME
1315
1316         items.clear ();
1317
1318         switch (item_type) {
1319         case FadeInItem:
1320         case FadeInHandleItem:
1321                 if (arv->audio_region()->fade_in_active()) {
1322                         items.push_back (MenuElem (_("Deactivate"), bind (mem_fun (*arv, &AudioRegionView::set_fade_in_active), false)));
1323                 } else {
1324                         items.push_back (MenuElem (_("Activate"), bind (mem_fun (*arv, &AudioRegionView::set_fade_in_active), true)));
1325                 }
1326                 
1327                 items.push_back (SeparatorElem());
1328                 
1329                 items.push_back (MenuElem (_("Linear"), bind (mem_fun (ar, &AudioRegion::set_fade_in_shape), AudioRegion::Linear)));
1330                 items.push_back (MenuElem (_("Slowest"), bind (mem_fun (ar, &AudioRegion::set_fade_in_shape), AudioRegion::LogB)));
1331                 items.push_back (MenuElem (_("Slow"), bind (mem_fun (ar, &AudioRegion::set_fade_in_shape), AudioRegion::Fast)));
1332                 items.push_back (MenuElem (_("Fast"), bind (mem_fun (ar, &AudioRegion::set_fade_in_shape), AudioRegion::LogA)));
1333                 items.push_back (MenuElem (_("Fastest"), bind (mem_fun (ar, &AudioRegion::set_fade_in_shape), AudioRegion::Slow)));
1334                 break;
1335
1336         case FadeOutItem:
1337         case FadeOutHandleItem:
1338                 if (arv->audio_region()->fade_out_active()) {
1339                         items.push_back (MenuElem (_("Deactivate"), bind (mem_fun (*arv, &AudioRegionView::set_fade_out_active), false)));
1340                 } else {
1341                         items.push_back (MenuElem (_("Activate"), bind (mem_fun (*arv, &AudioRegionView::set_fade_out_active), true)));
1342                 }
1343                 
1344                 items.push_back (SeparatorElem());
1345                 
1346                 items.push_back (MenuElem (_("Linear"), bind (mem_fun (ar, &AudioRegion::set_fade_out_shape), AudioRegion::Linear)));
1347                 items.push_back (MenuElem (_("Slowest"), bind (mem_fun (ar, &AudioRegion::set_fade_out_shape), AudioRegion::Fast)));
1348                 items.push_back (MenuElem (_("Slow"), bind (mem_fun (ar, &AudioRegion::set_fade_out_shape), AudioRegion::LogB)));
1349                 items.push_back (MenuElem (_("Fast"), bind (mem_fun (ar, &AudioRegion::set_fade_out_shape), AudioRegion::LogA)));
1350                 items.push_back (MenuElem (_("Fastest"), bind (mem_fun (ar, &AudioRegion::set_fade_out_shape), AudioRegion::Slow)));
1351
1352                 break;
1353         default:
1354                 fatal << _("programming error: ")
1355                       << X_("non-fade canvas item passed to popup_fade_context_menu()")
1356                       << endmsg;
1357                 /*NOTREACHED*/
1358         }
1359
1360         fade_context_menu.popup (button, time);
1361 }
1362
1363 void
1364 Editor::popup_track_context_menu (int button, int32_t time, ItemType item_type, bool with_selection, nframes_t frame)
1365 {
1366         using namespace Menu_Helpers;
1367         Menu* (Editor::*build_menu_function)(nframes_t);
1368         Menu *menu;
1369
1370         switch (item_type) {
1371         case RegionItem:
1372         case RegionViewName:
1373         case RegionViewNameHighlight:
1374                 if (with_selection) {
1375                         build_menu_function = &Editor::build_track_selection_context_menu;
1376                 } else {
1377                         build_menu_function = &Editor::build_track_region_context_menu;
1378                 }
1379                 break;
1380
1381         case SelectionItem:
1382                 if (with_selection) {
1383                         build_menu_function = &Editor::build_track_selection_context_menu;
1384                 } else {
1385                         build_menu_function = &Editor::build_track_context_menu;
1386                 }
1387                 break;
1388
1389         case CrossfadeViewItem:
1390                 build_menu_function = &Editor::build_track_crossfade_context_menu;
1391                 break;
1392
1393         case StreamItem:
1394                 if (clicked_audio_trackview->get_diskstream()) {
1395                         build_menu_function = &Editor::build_track_context_menu;
1396                 } else {
1397                         build_menu_function = &Editor::build_track_bus_context_menu;
1398                 }
1399                 break;
1400
1401         default:
1402                 /* probably shouldn't happen but if it does, we don't care */
1403                 return;
1404         }
1405
1406         menu = (this->*build_menu_function)(frame);
1407         menu->set_name ("ArdourContextMenu");
1408         
1409         /* now handle specific situations */
1410
1411         switch (item_type) {
1412         case RegionItem:
1413         case RegionViewName:
1414         case RegionViewNameHighlight:
1415                 if (!with_selection) {
1416                         if (region_edit_menu_split_item) {
1417                                 if (clicked_regionview && clicked_regionview->region()->covers (edit_cursor->current_frame)) {
1418                                         ActionManager::set_sensitive (ActionManager::edit_cursor_in_region_sensitive_actions, true);
1419                                 } else {
1420                                         ActionManager::set_sensitive (ActionManager::edit_cursor_in_region_sensitive_actions, false);
1421                                 }
1422                         }
1423                         /*
1424                         if (region_edit_menu_split_multichannel_item) {
1425                                 if (clicked_regionview && clicked_regionview->region().n_channels() > 1) {
1426                                         // GTK2FIX find the action, change its sensitivity
1427                                         // region_edit_menu_split_multichannel_item->set_sensitive (true);
1428                                 } else {
1429                                         // GTK2FIX see above
1430                                         // region_edit_menu_split_multichannel_item->set_sensitive (false);
1431                                 }
1432                         }*/
1433                 }
1434                 break;
1435
1436         case SelectionItem:
1437                 break;
1438
1439         case CrossfadeViewItem:
1440                 break;
1441
1442         case StreamItem:
1443                 break;
1444
1445         default:
1446                 /* probably shouldn't happen but if it does, we don't care */
1447                 return;
1448         }
1449
1450         if (clicked_audio_trackview && clicked_audio_trackview->audio_track()) {
1451
1452                 /* Bounce to disk */
1453                 
1454                 using namespace Menu_Helpers;
1455                 MenuList& edit_items  = menu->items();
1456                 
1457                 edit_items.push_back (SeparatorElem());
1458
1459                 switch (clicked_audio_trackview->audio_track()->freeze_state()) {
1460                 case AudioTrack::NoFreeze:
1461                         edit_items.push_back (MenuElem (_("Freeze"), mem_fun(*this, &Editor::freeze_route)));
1462                         break;
1463
1464                 case AudioTrack::Frozen:
1465                         edit_items.push_back (MenuElem (_("Unfreeze"), mem_fun(*this, &Editor::unfreeze_route)));
1466                         break;
1467                         
1468                 case AudioTrack::UnFrozen:
1469                         edit_items.push_back (MenuElem (_("Freeze"), mem_fun(*this, &Editor::freeze_route)));
1470                         break;
1471                 }
1472
1473         }
1474
1475         menu->popup (button, time);
1476 }
1477
1478 Menu*
1479 Editor::build_track_context_menu (nframes_t ignored)
1480 {
1481         using namespace Menu_Helpers;
1482
1483         MenuList& edit_items = track_context_menu.items();
1484         edit_items.clear();
1485
1486         add_dstream_context_items (edit_items);
1487         return &track_context_menu;
1488 }
1489
1490 Menu*
1491 Editor::build_track_bus_context_menu (nframes_t ignored)
1492 {
1493         using namespace Menu_Helpers;
1494
1495         MenuList& edit_items = track_context_menu.items();
1496         edit_items.clear();
1497
1498         add_bus_context_items (edit_items);
1499         return &track_context_menu;
1500 }
1501
1502 Menu*
1503 Editor::build_track_region_context_menu (nframes_t frame)
1504 {
1505         using namespace Menu_Helpers;
1506         MenuList& edit_items  = track_region_context_menu.items();
1507         edit_items.clear();
1508
1509         AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*> (clicked_trackview);
1510
1511         if (atv) {
1512                 boost::shared_ptr<Diskstream> ds;
1513                 Playlist* pl;
1514                 
1515                 if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()))) {
1516                         Playlist::RegionList* regions = pl->regions_at ((nframes_t) floor ( (double)frame * ds->speed()));
1517                         for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
1518                                 add_region_context_items (atv->audio_view(), (*i), edit_items);
1519                         }
1520                         delete regions;
1521                 }
1522         }
1523
1524         add_dstream_context_items (edit_items);
1525
1526         return &track_region_context_menu;
1527 }
1528
1529 Menu*
1530 Editor::build_track_crossfade_context_menu (nframes_t frame)
1531 {
1532         using namespace Menu_Helpers;
1533         MenuList& edit_items  = track_crossfade_context_menu.items();
1534         edit_items.clear ();
1535
1536         AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*> (clicked_trackview);
1537
1538         if (atv) {
1539                 boost::shared_ptr<Diskstream> ds;
1540                 Playlist* pl;
1541                 AudioPlaylist* apl;
1542
1543                 if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()) != 0) && ((apl = dynamic_cast<AudioPlaylist*> (pl)) != 0)) {
1544
1545                         Playlist::RegionList* regions = pl->regions_at (frame);
1546                         AudioPlaylist::Crossfades xfades;
1547
1548                         apl->crossfades_at (frame, xfades);
1549
1550                         bool many = xfades.size() > 1;
1551
1552                         for (AudioPlaylist::Crossfades::iterator i = xfades.begin(); i != xfades.end(); ++i) {
1553                                 add_crossfade_context_items (atv->audio_view(), (*i), edit_items, many);
1554                         }
1555
1556                         for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
1557                                 add_region_context_items (atv->audio_view(), (*i), edit_items);
1558                         }
1559
1560                         delete regions;
1561                 }
1562         }
1563
1564         add_dstream_context_items (edit_items);
1565
1566         return &track_crossfade_context_menu;
1567 }
1568
1569 #ifdef FFT_ANALYSIS
1570 void
1571 Editor::analyze_region_selection()
1572 {
1573         if (analysis_window == 0) {
1574                 analysis_window = new AnalysisWindow();
1575
1576                 if (session != 0)
1577                         analysis_window->set_session(session);
1578
1579                 analysis_window->show_all();
1580         }
1581
1582         analysis_window->set_regionmode();
1583         analysis_window->analyze();
1584         
1585         analysis_window->present();
1586 }
1587
1588 void
1589 Editor::analyze_range_selection()
1590 {
1591         if (analysis_window == 0) {
1592                 analysis_window = new AnalysisWindow();
1593
1594                 if (session != 0)
1595                         analysis_window->set_session(session);
1596
1597                 analysis_window->show_all();
1598         }
1599
1600         analysis_window->set_rangemode();
1601         analysis_window->analyze();
1602         
1603         analysis_window->present();
1604 }
1605 #endif /* FFT_ANALYSIS */
1606
1607
1608
1609 Menu*
1610 Editor::build_track_selection_context_menu (nframes_t ignored)
1611 {
1612         using namespace Menu_Helpers;
1613         MenuList& edit_items  = track_selection_context_menu.items();
1614         edit_items.clear ();
1615
1616         add_selection_context_items (edit_items);
1617         add_dstream_context_items (edit_items);
1618
1619         return &track_selection_context_menu;
1620 }
1621
1622 void
1623 Editor::add_crossfade_context_items (AudioStreamView* view, Crossfade* xfade, Menu_Helpers::MenuList& edit_items, bool many)
1624 {
1625         using namespace Menu_Helpers;
1626         Menu     *xfade_menu = manage (new Menu);
1627         MenuList& items       = xfade_menu->items();
1628         xfade_menu->set_name ("ArdourContextMenu");
1629         string str;
1630
1631         if (xfade->active()) {
1632                 str = _("Mute");
1633         } else { 
1634                 str = _("Unmute");
1635         }
1636
1637         items.push_back (MenuElem (str, bind (mem_fun(*this, &Editor::toggle_xfade_active), xfade)));
1638         items.push_back (MenuElem (_("Edit"), bind (mem_fun(*this, &Editor::edit_xfade), xfade)));
1639
1640         if (xfade->can_follow_overlap()) {
1641
1642                 if (xfade->following_overlap()) {
1643                         str = _("Convert to short");
1644                 } else {
1645                         str = _("Convert to full");
1646                 }
1647
1648                 items.push_back (MenuElem (str, bind (mem_fun(*this, &Editor::toggle_xfade_length), xfade)));
1649         }
1650
1651         if (many) {
1652                 str = xfade->out()->name();
1653                 str += "->";
1654                 str += xfade->in()->name();
1655         } else {
1656                 str = _("Crossfade");
1657         }
1658
1659         edit_items.push_back (MenuElem (str, *xfade_menu));
1660         edit_items.push_back (SeparatorElem());
1661 }
1662
1663 void
1664 Editor::xfade_edit_left_region ()
1665 {
1666         if (clicked_crossfadeview) {
1667                 clicked_crossfadeview->left_view.show_region_editor ();
1668         }
1669 }
1670
1671 void
1672 Editor::xfade_edit_right_region ()
1673 {
1674         if (clicked_crossfadeview) {
1675                 clicked_crossfadeview->right_view.show_region_editor ();
1676         }
1677 }
1678
1679 void
1680 Editor::add_region_context_items (AudioStreamView* sv, boost::shared_ptr<Region> region, Menu_Helpers::MenuList& edit_items)
1681 {
1682         using namespace Menu_Helpers;
1683         Menu     *region_menu = manage (new Menu);
1684         MenuList& items       = region_menu->items();
1685         region_menu->set_name ("ArdourContextMenu");
1686         
1687         boost::shared_ptr<AudioRegion> ar;
1688
1689         if (region) {
1690                 ar = boost::dynamic_pointer_cast<AudioRegion> (region);
1691         }
1692
1693         /* when this particular menu pops up, make the relevant region 
1694            become selected.
1695         */
1696
1697         region_menu->signal_map_event().connect (bind (mem_fun(*this, &Editor::set_selected_regionview_from_map_event), sv, boost::weak_ptr<Region>(region)));
1698
1699         items.push_back (MenuElem (_("Popup region editor"), mem_fun(*this, &Editor::edit_region)));
1700         items.push_back (MenuElem (_("Raise to top layer"), mem_fun(*this, &Editor::raise_region_to_top)));
1701         items.push_back (MenuElem (_("Lower to bottom layer"), mem_fun  (*this, &Editor::lower_region_to_bottom)));
1702         items.push_back (SeparatorElem());
1703         items.push_back (MenuElem (_("Define sync point"), mem_fun(*this, &Editor::set_region_sync_from_edit_cursor)));
1704         items.push_back (MenuElem (_("Remove sync point"), mem_fun(*this, &Editor::remove_region_sync)));
1705         items.push_back (SeparatorElem());
1706
1707         items.push_back (MenuElem (_("Audition"), mem_fun(*this, &Editor::audition_selected_region)));
1708         items.push_back (MenuElem (_("Export"), mem_fun(*this, &Editor::export_region)));
1709         items.push_back (MenuElem (_("Bounce"), mem_fun(*this, &Editor::bounce_region_selection)));
1710
1711 #ifdef FFT_ANALYSIS
1712         items.push_back (MenuElem (_("Analyze region"), mem_fun(*this, &Editor::analyze_region_selection)));
1713 #endif
1714
1715         items.push_back (SeparatorElem());
1716
1717         /* XXX hopefully this nonsense will go away with SigC++ 2.X, where the compiler
1718            might be able to figure out which overloaded member function to use in
1719            a bind() call ...
1720         */
1721
1722         void (Editor::*type_A_pmf)(void (Region::*pmf)(bool), bool) = &Editor::region_selection_op;
1723
1724         items.push_back (MenuElem (_("Lock"), bind (mem_fun(*this, type_A_pmf), &Region::set_locked, true)));
1725         items.push_back (MenuElem (_("Unlock"), bind (mem_fun(*this, type_A_pmf), &Region::set_locked, false)));
1726         items.push_back (SeparatorElem());
1727
1728         if (region->muted()) {
1729                 items.push_back (MenuElem (_("Unmute"), bind (mem_fun(*this, type_A_pmf), &Region::set_muted, false)));
1730         } else {
1731                 items.push_back (MenuElem (_("Mute"), bind (mem_fun(*this, type_A_pmf), &Region::set_muted, true)));
1732         }
1733         items.push_back (SeparatorElem());
1734
1735         items.push_back (MenuElem (_("Original position"), mem_fun(*this, &Editor::naturalize)));
1736         items.push_back (SeparatorElem());
1737
1738
1739         if (ar) {
1740
1741                 items.push_back (MenuElem (_("Toggle envelope visibility"), mem_fun(*this, &Editor::toggle_gain_envelope_visibility)));
1742                 items.push_back (MenuElem (_("Toggle envelope active"), mem_fun(*this, &Editor::toggle_gain_envelope_active)));
1743                 items.push_back (SeparatorElem());
1744
1745                 if (ar->scale_amplitude() != 1.0f) {
1746                         items.push_back (MenuElem (_("DeNormalize"), mem_fun(*this, &Editor::denormalize_region)));
1747                 } else {
1748                         items.push_back (MenuElem (_("Normalize"), mem_fun(*this, &Editor::normalize_region)));
1749                 }
1750         }
1751         items.push_back (MenuElem (_("Reverse"), mem_fun(*this, &Editor::reverse_region)));
1752         items.push_back (SeparatorElem());
1753
1754
1755         /* range related stuff */
1756
1757         items.push_back (MenuElem (_("Add Range Markers"), mem_fun (*this, &Editor::add_location_from_audio_region)));
1758         items.push_back (MenuElem (_("Set Range"), mem_fun (*this, &Editor::set_selection_from_audio_region)));
1759         items.push_back (SeparatorElem());
1760                          
1761         /* Nudge region */
1762
1763         Menu *nudge_menu = manage (new Menu());
1764         MenuList& nudge_items = nudge_menu->items();
1765         nudge_menu->set_name ("ArdourContextMenu");
1766         
1767         nudge_items.push_back (MenuElem (_("Nudge fwd"), (bind (mem_fun(*this, &Editor::nudge_forward), false))));
1768         nudge_items.push_back (MenuElem (_("Nudge bwd"), (bind (mem_fun(*this, &Editor::nudge_backward), false))));
1769         nudge_items.push_back (MenuElem (_("Nudge fwd by capture offset"), (mem_fun(*this, &Editor::nudge_forward_capture_offset))));
1770         nudge_items.push_back (MenuElem (_("Nudge bwd by capture offset"), (mem_fun(*this, &Editor::nudge_backward_capture_offset))));
1771
1772         items.push_back (MenuElem (_("Nudge"), *nudge_menu));
1773         items.push_back (SeparatorElem());
1774
1775         Menu *trim_menu = manage (new Menu);
1776         MenuList& trim_items = trim_menu->items();
1777         trim_menu->set_name ("ArdourContextMenu");
1778         
1779         trim_items.push_back (MenuElem (_("Start to edit cursor"), mem_fun(*this, &Editor::trim_region_from_edit_cursor)));
1780         trim_items.push_back (MenuElem (_("Edit cursor to end"), mem_fun(*this, &Editor::trim_region_to_edit_cursor)));
1781                              
1782         items.push_back (MenuElem (_("Trim"), *trim_menu));
1783         items.push_back (SeparatorElem());
1784
1785         items.push_back (MenuElem (_("Split"), (mem_fun(*this, &Editor::split_region))));
1786         region_edit_menu_split_item = &items.back();
1787
1788         items.push_back (MenuElem (_("Make mono regions"), (mem_fun(*this, &Editor::split_multichannel_region))));
1789         region_edit_menu_split_multichannel_item = &items.back();
1790
1791         items.push_back (MenuElem (_("Duplicate"), (bind (mem_fun(*this, &Editor::duplicate_dialog), true))));
1792         items.push_back (MenuElem (_("Fill Track"), (mem_fun(*this, &Editor::region_fill_track))));
1793         items.push_back (SeparatorElem());
1794         items.push_back (MenuElem (_("Remove"), mem_fun(*this, &Editor::remove_clicked_region)));
1795         items.push_back (SeparatorElem());
1796         items.push_back (MenuElem (_("Destroy"), mem_fun(*this, &Editor::destroy_clicked_region)));
1797
1798         /* OK, stick the region submenu at the top of the list, and then add
1799            the standard items.
1800         */
1801
1802         /* we have to hack up the region name because "_" has a special
1803            meaning for menu titles.
1804         */
1805
1806         string::size_type pos = 0;
1807         string menu_item_name = region->name();
1808
1809         while ((pos = menu_item_name.find ("_", pos)) != string::npos) {
1810                 menu_item_name.replace (pos, 1, "__");
1811                 pos += 2;
1812         }
1813         
1814         edit_items.push_back (MenuElem (menu_item_name, *region_menu));
1815         edit_items.push_back (SeparatorElem());
1816 }
1817
1818 void
1819 Editor::add_selection_context_items (Menu_Helpers::MenuList& edit_items)
1820 {
1821         using namespace Menu_Helpers;
1822         Menu     *selection_menu = manage (new Menu);
1823         MenuList& items       = selection_menu->items();
1824         selection_menu->set_name ("ArdourContextMenu");
1825
1826         items.push_back (MenuElem (_("Play range"), mem_fun(*this, &Editor::play_selection)));
1827         items.push_back (MenuElem (_("Loop range"), mem_fun(*this, &Editor::set_route_loop_selection)));
1828
1829 #ifdef FFT_ANALYSIS
1830         items.push_back (SeparatorElem());
1831         items.push_back (MenuElem (_("Analyze range"), mem_fun(*this, &Editor::analyze_range_selection)));
1832 #endif
1833         
1834         items.push_back (SeparatorElem());
1835         items.push_back (MenuElem (_("Separate range to track"), mem_fun(*this, &Editor::separate_region_from_selection)));
1836         items.push_back (MenuElem (_("Separate range to region list"), mem_fun(*this, &Editor::new_region_from_selection)));
1837         
1838         items.push_back (SeparatorElem());
1839         items.push_back (MenuElem (_("Select all in range"), mem_fun(*this, &Editor::select_all_selectables_using_time_selection)));
1840         items.push_back (SeparatorElem());
1841         items.push_back (MenuElem (_("Set range to loop range"), mem_fun(*this, &Editor::set_selection_from_loop)));
1842         items.push_back (MenuElem (_("Set range to punch range"), mem_fun(*this, &Editor::set_selection_from_punch)));
1843         items.push_back (SeparatorElem());
1844         items.push_back (MenuElem (_("Crop region to range"), mem_fun(*this, &Editor::crop_region_to_selection)));
1845         items.push_back (MenuElem (_("Fill range with region"), mem_fun(*this, &Editor::region_fill_selection)));
1846         items.push_back (MenuElem (_("Duplicate range"), bind (mem_fun(*this, &Editor::duplicate_dialog), false)));
1847         items.push_back (MenuElem (_("Create chunk from range"), mem_fun(*this, &Editor::name_selection)));
1848         items.push_back (SeparatorElem());
1849         items.push_back (MenuElem (_("Bounce range"), mem_fun(*this, &Editor::bounce_range_selection)));
1850         items.push_back (MenuElem (_("Export range"), mem_fun(*this, &Editor::export_selection)));
1851
1852         edit_items.push_back (MenuElem (_("Range"), *selection_menu));
1853         edit_items.push_back (SeparatorElem());
1854 }
1855
1856 void
1857 Editor::add_dstream_context_items (Menu_Helpers::MenuList& edit_items)
1858 {
1859         using namespace Menu_Helpers;
1860
1861         /* Playback */
1862
1863         Menu *play_menu = manage (new Menu);
1864         MenuList& play_items = play_menu->items();
1865         play_menu->set_name ("ArdourContextMenu");
1866         
1867         play_items.push_back (MenuElem (_("Play from edit cursor")));
1868         play_items.push_back (MenuElem (_("Play from start"), mem_fun(*this, &Editor::play_from_start)));
1869         play_items.push_back (MenuElem (_("Play region"), mem_fun(*this, &Editor::play_selected_region)));
1870         play_items.push_back (SeparatorElem());
1871         play_items.push_back (MenuElem (_("Loop Region"), mem_fun(*this, &Editor::loop_selected_region)));
1872         
1873         edit_items.push_back (MenuElem (_("Play"), *play_menu));
1874
1875         /* Selection */
1876
1877         Menu *select_menu = manage (new Menu);
1878         MenuList& select_items = select_menu->items();
1879         select_menu->set_name ("ArdourContextMenu");
1880         
1881         select_items.push_back (MenuElem (_("Select All in track"), bind (mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
1882         select_items.push_back (MenuElem (_("Select All"), bind (mem_fun(*this, &Editor::select_all), Selection::Set)));
1883         select_items.push_back (MenuElem (_("Invert selection in track"), mem_fun(*this, &Editor::invert_selection_in_track)));
1884         select_items.push_back (MenuElem (_("Invert selection"), mem_fun(*this, &Editor::invert_selection)));
1885         select_items.push_back (SeparatorElem());
1886         select_items.push_back (MenuElem (_("Set range to loop range"), mem_fun(*this, &Editor::set_selection_from_loop)));
1887         select_items.push_back (MenuElem (_("Set range to punch range"), mem_fun(*this, &Editor::set_selection_from_punch)));
1888         select_items.push_back (SeparatorElem());
1889         select_items.push_back (MenuElem (_("Select all after edit cursor"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), edit_cursor, true)));
1890         select_items.push_back (MenuElem (_("Select all before edit cursor"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), edit_cursor, false)));
1891         select_items.push_back (MenuElem (_("Select all after playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
1892         select_items.push_back (MenuElem (_("Select all before playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
1893         select_items.push_back (MenuElem (_("Select all between cursors"), bind (mem_fun(*this, &Editor::select_all_selectables_between_cursors), playhead_cursor, edit_cursor)));
1894         select_items.push_back (SeparatorElem());
1895
1896         edit_items.push_back (MenuElem (_("Select"), *select_menu));
1897
1898         /* Cut-n-Paste */
1899
1900         Menu *cutnpaste_menu = manage (new Menu);
1901         MenuList& cutnpaste_items = cutnpaste_menu->items();
1902         cutnpaste_menu->set_name ("ArdourContextMenu");
1903         
1904         cutnpaste_items.push_back (MenuElem (_("Cut"), mem_fun(*this, &Editor::cut)));
1905         cutnpaste_items.push_back (MenuElem (_("Copy"), mem_fun(*this, &Editor::copy)));
1906         cutnpaste_items.push_back (MenuElem (_("Paste at edit cursor"), bind (mem_fun(*this, &Editor::paste), 1.0f)));
1907         cutnpaste_items.push_back (MenuElem (_("Paste at mouse"), mem_fun(*this, &Editor::mouse_paste)));
1908
1909         cutnpaste_items.push_back (SeparatorElem());
1910
1911         cutnpaste_items.push_back (MenuElem (_("Align"), bind (mem_fun(*this, &Editor::align), ARDOUR::SyncPoint)));
1912         cutnpaste_items.push_back (MenuElem (_("Align Relative"), bind (mem_fun(*this, &Editor::align_relative), ARDOUR::SyncPoint)));
1913
1914         cutnpaste_items.push_back (SeparatorElem());
1915
1916         cutnpaste_items.push_back (MenuElem (_("Insert chunk"), bind (mem_fun(*this, &Editor::paste_named_selection), 1.0f)));
1917
1918         edit_items.push_back (MenuElem (_("Edit"), *cutnpaste_menu));
1919
1920         /* Adding new material */
1921         
1922         edit_items.push_back (SeparatorElem());
1923         edit_items.push_back (MenuElem (_("Insert Selected Region"), bind (mem_fun(*this, &Editor::insert_region_list_selection), 1.0f)));
1924         edit_items.push_back (MenuElem (_("Insert Existing Audio"), bind (mem_fun(*this, &Editor::add_external_audio_action), ImportToTrack)));
1925
1926         /* Nudge track */
1927
1928         Menu *nudge_menu = manage (new Menu());
1929         MenuList& nudge_items = nudge_menu->items();
1930         nudge_menu->set_name ("ArdourContextMenu");
1931         
1932         edit_items.push_back (SeparatorElem());
1933         nudge_items.push_back (MenuElem (_("Nudge entire track fwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, true))));
1934         nudge_items.push_back (MenuElem (_("Nudge track after edit cursor fwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, true))));
1935         nudge_items.push_back (MenuElem (_("Nudge entire track bwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, false))));
1936         nudge_items.push_back (MenuElem (_("Nudge track after edit cursor bwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, false))));
1937
1938         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
1939 }
1940
1941 void
1942 Editor::add_bus_context_items (Menu_Helpers::MenuList& edit_items)
1943 {
1944         using namespace Menu_Helpers;
1945
1946         /* Playback */
1947
1948         Menu *play_menu = manage (new Menu);
1949         MenuList& play_items = play_menu->items();
1950         play_menu->set_name ("ArdourContextMenu");
1951         
1952         play_items.push_back (MenuElem (_("Play from edit cursor")));
1953         play_items.push_back (MenuElem (_("Play from start"), mem_fun(*this, &Editor::play_from_start)));
1954         edit_items.push_back (MenuElem (_("Play"), *play_menu));
1955
1956         /* Selection */
1957
1958         Menu *select_menu = manage (new Menu);
1959         MenuList& select_items = select_menu->items();
1960         select_menu->set_name ("ArdourContextMenu");
1961         
1962         select_items.push_back (MenuElem (_("Select All in track"), bind (mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
1963         select_items.push_back (MenuElem (_("Select All"), bind (mem_fun(*this, &Editor::select_all), Selection::Set)));
1964         select_items.push_back (MenuElem (_("Invert selection in track"), mem_fun(*this, &Editor::invert_selection_in_track)));
1965         select_items.push_back (MenuElem (_("Invert selection"), mem_fun(*this, &Editor::invert_selection)));
1966         select_items.push_back (SeparatorElem());
1967         select_items.push_back (MenuElem (_("Select all after edit cursor"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), edit_cursor, true)));
1968         select_items.push_back (MenuElem (_("Select all before edit cursor"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), edit_cursor, false)));
1969         select_items.push_back (MenuElem (_("Select all after playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
1970         select_items.push_back (MenuElem (_("Select all before playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
1971
1972         edit_items.push_back (MenuElem (_("Select"), *select_menu));
1973
1974         /* Cut-n-Paste */
1975
1976         Menu *cutnpaste_menu = manage (new Menu);
1977         MenuList& cutnpaste_items = cutnpaste_menu->items();
1978         cutnpaste_menu->set_name ("ArdourContextMenu");
1979         
1980         cutnpaste_items.push_back (MenuElem (_("Cut"), mem_fun(*this, &Editor::cut)));
1981         cutnpaste_items.push_back (MenuElem (_("Copy"), mem_fun(*this, &Editor::copy)));
1982         cutnpaste_items.push_back (MenuElem (_("Paste"), bind (mem_fun(*this, &Editor::paste), 1.0f)));
1983
1984         Menu *nudge_menu = manage (new Menu());
1985         MenuList& nudge_items = nudge_menu->items();
1986         nudge_menu->set_name ("ArdourContextMenu");
1987         
1988         edit_items.push_back (SeparatorElem());
1989         nudge_items.push_back (MenuElem (_("Nudge entire track fwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, true))));
1990         nudge_items.push_back (MenuElem (_("Nudge track after edit cursor fwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, true))));
1991         nudge_items.push_back (MenuElem (_("Nudge entire track bwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, false))));
1992         nudge_items.push_back (MenuElem (_("Nudge track after edit cursor bwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, false))));
1993
1994         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
1995 }
1996
1997 /* CURSOR SETTING AND MARKS AND STUFF */
1998
1999 void
2000 Editor::set_snap_to (SnapType st)
2001 {
2002         snap_type = st;
2003         string str = snap_type_strings[(int) st];
2004
2005         if (str != snap_type_selector.get_active_text()) {
2006                 snap_type_selector.set_active_text (str);
2007         }
2008
2009         instant_save ();
2010
2011         switch (snap_type) {
2012         case SnapToAThirtysecondBeat:
2013         case SnapToASixteenthBeat:
2014         case SnapToAEighthBeat:
2015         case SnapToAQuarterBeat:
2016         case SnapToAThirdBeat:
2017                 update_tempo_based_rulers ();
2018         default:
2019                 /* relax */
2020                 break;
2021     }
2022 }
2023
2024 void
2025 Editor::set_snap_mode (SnapMode mode)
2026 {
2027         snap_mode = mode;
2028         string str = snap_mode_strings[(int)mode];
2029
2030         if (str != snap_mode_selector.get_active_text ()) {
2031                 snap_mode_selector.set_active_text (str);
2032         }
2033
2034         instant_save ();
2035 }
2036
2037 int
2038 Editor::set_state (const XMLNode& node)
2039 {
2040         const XMLProperty* prop;
2041         XMLNode* geometry;
2042         int x, y, xoff, yoff;
2043         Gdk::Geometry g;
2044
2045         if ((prop = node.property ("id")) != 0) {
2046                 _id = prop->value ();
2047         }
2048
2049         if ((geometry = find_named_node (node, "geometry")) == 0) {
2050
2051                 g.base_width = default_width;
2052                 g.base_height = default_height;
2053                 x = 1;
2054                 y = 1;
2055                 xoff = 0;
2056                 yoff = 21;
2057
2058         } else {
2059
2060                 g.base_width = atoi(geometry->property("x_size")->value());
2061                 g.base_height = atoi(geometry->property("y_size")->value());
2062                 x = atoi(geometry->property("x_pos")->value());
2063                 y = atoi(geometry->property("y_pos")->value());
2064                 xoff = atoi(geometry->property("x_off")->value());
2065                 yoff = atoi(geometry->property("y_off")->value());
2066         }
2067
2068         set_default_size (g.base_width, g.base_height);
2069         move (x, y);
2070
2071         if ((prop = node.property ("zoom-focus"))) {
2072                 set_zoom_focus ((ZoomFocus) atoi (prop->value()));
2073         }
2074
2075         if ((prop = node.property ("zoom"))) {
2076                 set_frames_per_unit (PBD::atof (prop->value()));
2077         }
2078
2079         if ((prop = node.property ("snap-to"))) {
2080                 set_snap_to ((SnapType) atoi (prop->value()));
2081         }
2082
2083         if ((prop = node.property ("snap-mode"))) {
2084                 set_snap_mode ((SnapMode) atoi (prop->value()));
2085         }
2086
2087         if ((prop = node.property ("mouse-mode"))) {
2088                 MouseMode m = str2mousemode(prop->value());
2089                 mouse_mode = MouseMode ((int) m + 1); /* lie, force mode switch */
2090                 set_mouse_mode (m, true);
2091         } else {
2092                 mouse_mode = MouseGain; /* lie, to force the mode switch */
2093                 set_mouse_mode (MouseObject, true);
2094         }
2095
2096         if ((prop = node.property ("show-waveforms"))) {
2097                 bool yn = (prop->value() == "yes");
2098                 _show_waveforms = !yn;
2099                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleWaveformVisibility"));
2100                 if (act) {
2101                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2102                         /* do it twice to force the change */
2103                         tact->set_active (!yn);
2104                         tact->set_active (yn);
2105                 }
2106         }
2107
2108         if ((prop = node.property ("show-waveforms-recording"))) {
2109                 bool yn = (prop->value() == "yes");
2110                 _show_waveforms_recording = !yn;
2111                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleWaveformsWhileRecording"));
2112                 if (act) {
2113                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2114                         /* do it twice to force the change */
2115                         tact->set_active (!yn);
2116                         tact->set_active (yn);
2117                 }
2118         }
2119         
2120         if ((prop = node.property ("show-measures"))) {
2121                 bool yn = (prop->value() == "yes");
2122                 _show_measures = !yn;
2123                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleMeasureVisibility"));
2124                 if (act) {
2125                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2126                         /* do it twice to force the change */
2127                         tact->set_active (!yn);
2128                         tact->set_active (yn);
2129                 }
2130         }
2131
2132         if ((prop = node.property ("follow-playhead"))) {
2133                 bool yn = (prop->value() == "yes");
2134                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
2135                 if (act) {
2136                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2137                         /* do it twice to force the change */
2138                         tact->set_active (!yn);
2139                         tact->set_active (yn);
2140                 }
2141         }
2142
2143
2144         if ((prop = node.property ("region-list-sort-type"))) {
2145                 region_list_sort_type = (Editing::RegionListSortType) -1; // force change 
2146                 reset_region_list_sort_type(str2regionlistsorttype(prop->value()));
2147         }
2148
2149         if ((prop = node.property ("xfades-visible"))) {
2150                 bool yn = (prop->value() == "yes");
2151                 _xfade_visibility = !yn;
2152                 // set_xfade_visibility (yn);
2153         }
2154
2155         if ((prop = node.property ("show-editor-mixer"))) {
2156
2157                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2158                 if (act) {
2159                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2160                         bool yn = (prop->value() == X_("yes"));
2161
2162                         /* do it twice to force the change */
2163                         
2164                         tact->set_active (!yn);
2165                         tact->set_active (yn);
2166                 }
2167         }
2168
2169
2170         return 0;
2171 }
2172
2173 XMLNode&
2174 Editor::get_state ()
2175 {
2176         XMLNode* node = new XMLNode ("Editor");
2177         char buf[32];
2178
2179         _id.print (buf, sizeof (buf));
2180         node->add_property ("id", buf);
2181         
2182         if (is_realized()) {
2183                 Glib::RefPtr<Gdk::Window> win = get_window();
2184                 
2185                 int x, y, xoff, yoff, width, height;
2186                 win->get_root_origin(x, y);
2187                 win->get_position(xoff, yoff);
2188                 win->get_size(width, height);
2189                 
2190                 XMLNode* geometry = new XMLNode ("geometry");
2191
2192                 snprintf(buf, sizeof(buf), "%d", width);
2193                 geometry->add_property("x_size", string(buf));
2194                 snprintf(buf, sizeof(buf), "%d", height);
2195                 geometry->add_property("y_size", string(buf));
2196                 snprintf(buf, sizeof(buf), "%d", x);
2197                 geometry->add_property("x_pos", string(buf));
2198                 snprintf(buf, sizeof(buf), "%d", y);
2199                 geometry->add_property("y_pos", string(buf));
2200                 snprintf(buf, sizeof(buf), "%d", xoff);
2201                 geometry->add_property("x_off", string(buf));
2202                 snprintf(buf, sizeof(buf), "%d", yoff);
2203                 geometry->add_property("y_off", string(buf));
2204                 snprintf(buf,sizeof(buf), "%d",gtk_paned_get_position (static_cast<Paned*>(&edit_pane)->gobj()));
2205                 geometry->add_property("edit_pane_pos", string(buf));
2206
2207                 node->add_child_nocopy (*geometry);
2208         }
2209
2210         snprintf (buf, sizeof(buf), "%d", (int) zoom_focus);
2211         node->add_property ("zoom-focus", buf);
2212         snprintf (buf, sizeof(buf), "%f", frames_per_unit);
2213         node->add_property ("zoom", buf);
2214         snprintf (buf, sizeof(buf), "%d", (int) snap_type);
2215         node->add_property ("snap-to", buf);
2216         snprintf (buf, sizeof(buf), "%d", (int) snap_mode);
2217         node->add_property ("snap-mode", buf);
2218
2219         node->add_property ("show-waveforms", _show_waveforms ? "yes" : "no");
2220         node->add_property ("show-waveforms-recording", _show_waveforms_recording ? "yes" : "no");
2221         node->add_property ("show-measures", _show_measures ? "yes" : "no");
2222         node->add_property ("follow-playhead", _follow_playhead ? "yes" : "no");
2223         node->add_property ("xfades-visible", _xfade_visibility ? "yes" : "no");
2224         node->add_property ("region-list-sort-type", enum2str(region_list_sort_type));
2225         node->add_property ("mouse-mode", enum2str(mouse_mode));
2226         
2227         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2228         if (act) {
2229                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2230                 node->add_property (X_("show-editor-mixer"), tact->get_active() ? "yes" : "no");
2231         }
2232
2233         return *node;
2234 }
2235
2236
2237
2238 TimeAxisView *
2239 Editor::trackview_by_y_position (double y)
2240 {
2241         TrackViewList::iterator iter;
2242         TimeAxisView *tv;
2243
2244         for (iter = track_views.begin(); iter != track_views.end(); ++iter) {
2245
2246                 tv = *iter;
2247
2248                 if (tv->hidden()) {
2249                         continue;
2250                 }
2251
2252                 if (tv->y_position <= y && y < ((tv->y_position + tv->height + track_spacing))) {
2253                         return tv;
2254                 }
2255         }
2256
2257         return 0;
2258 }
2259
2260 void
2261 Editor::snap_to (nframes_t& start, int32_t direction, bool for_mark)
2262 {
2263         Location* before = 0;
2264         Location* after = 0;
2265
2266         if (!session) {
2267                 return;
2268         }
2269
2270         const nframes_t one_second = session->frame_rate();
2271         const nframes_t one_minute = session->frame_rate() * 60;
2272
2273         nframes_t presnap = start;
2274
2275         switch (snap_type) {
2276         case SnapToFrame:
2277                 break;
2278
2279         case SnapToCDFrame:
2280                 if (direction) {
2281                         start = (nframes_t) ceil ((double) start / (one_second / 75)) * (one_second / 75);
2282                 } else {
2283                         start = (nframes_t) floor ((double) start / (one_second / 75)) * (one_second / 75);
2284                 }
2285                 break;
2286         case SnapToSMPTEFrame:
2287                 if (direction) {
2288                         start = (nframes_t) (ceil ((double) start / session->frames_per_smpte_frame()) * session->frames_per_smpte_frame());
2289                 } else {
2290                         start = (nframes_t) (floor ((double) start / session->frames_per_smpte_frame()) *  session->frames_per_smpte_frame());
2291                 }
2292                 break;
2293
2294         case SnapToSMPTESeconds:
2295                 if (session->smpte_offset_negative())
2296                 {
2297                         start += session->smpte_offset ();
2298                 } else {
2299                         start -= session->smpte_offset ();
2300                 }    
2301                 if (direction > 0) {
2302                         start = (nframes_t) ceil ((double) start / one_second) * one_second;
2303                 } else {
2304                         start = (nframes_t) floor ((double) start / one_second) * one_second;
2305                 }
2306                 
2307                 if (session->smpte_offset_negative())
2308                 {
2309                         start -= session->smpte_offset ();
2310                 } else {
2311                         start += session->smpte_offset ();
2312                 }
2313                 break;
2314                 
2315         case SnapToSMPTEMinutes:
2316                 if (session->smpte_offset_negative())
2317                 {
2318                         start += session->smpte_offset ();
2319                 } else {
2320                         start -= session->smpte_offset ();
2321                 }
2322                 if (direction) {
2323                         start = (nframes_t) ceil ((double) start / one_minute) * one_minute;
2324                 } else {
2325                         start = (nframes_t) floor ((double) start / one_minute) * one_minute;
2326                 }
2327                 if (session->smpte_offset_negative())
2328                 {
2329                         start -= session->smpte_offset ();
2330                 } else {
2331                         start += session->smpte_offset ();
2332                 }
2333                 break;
2334                 
2335         case SnapToSeconds:
2336                 if (direction) {
2337                         start = (nframes_t) ceil ((double) start / one_second) * one_second;
2338                 } else {
2339                         start = (nframes_t) floor ((double) start / one_second) * one_second;
2340                 }
2341                 break;
2342                 
2343         case SnapToMinutes:
2344                 if (direction) {
2345                         start = (nframes_t) ceil ((double) start / one_minute) * one_minute;
2346                 } else {
2347                         start = (nframes_t) floor ((double) start / one_minute) * one_minute;
2348                 }
2349                 break;
2350
2351         case SnapToBar:
2352                 start = session->tempo_map().round_to_bar (start, direction);
2353                 break;
2354
2355         case SnapToBeat:
2356                 start = session->tempo_map().round_to_beat (start, direction);
2357                 break;
2358
2359         case SnapToAThirtysecondBeat:
2360                 start = session->tempo_map().round_to_beat_subdivision (start, 32);
2361                 break;
2362
2363         case SnapToASixteenthBeat:
2364                 start = session->tempo_map().round_to_beat_subdivision (start, 16);
2365                 break;
2366
2367         case SnapToAEighthBeat:
2368                 start = session->tempo_map().round_to_beat_subdivision (start, 8);
2369                 break;
2370
2371         case SnapToAQuarterBeat:
2372                 start = session->tempo_map().round_to_beat_subdivision (start, 4);
2373                 break;
2374
2375         case SnapToAThirdBeat:
2376                 start = session->tempo_map().round_to_beat_subdivision (start, 3);
2377                 break;
2378
2379         case SnapToEditCursor:
2380                 start = edit_cursor->current_frame;
2381                 break;
2382
2383         case SnapToMark:
2384                 if (for_mark) {
2385                         return;
2386                 }
2387
2388                 before = session->locations()->first_location_before (start);
2389                 after = session->locations()->first_location_after (start);
2390
2391                 if (direction < 0) {
2392                         if (before) {
2393                                 start = before->start();
2394                         } else {
2395                                 start = 0;
2396                         }
2397                 } else if (direction > 0) {
2398                         if (after) {
2399                                 start = after->start();
2400                         } else {
2401                                 start = session->current_end_frame();
2402                         }
2403                 } else {
2404                         if (before) {
2405                                 if (after) {
2406                                         /* find nearest of the two */
2407                                         if ((start - before->start()) < (after->start() - start)) {
2408                                                 start = before->start();
2409                                         } else {
2410                                                 start = after->start();
2411                                         }
2412                                 } else {
2413                                         start = before->start();
2414                                 }
2415                         } else if (after) {
2416                                 start = after->start();
2417                         } else {
2418                                 /* relax */
2419                         }
2420                 }
2421                 break;
2422
2423         case SnapToRegionStart:
2424         case SnapToRegionEnd:
2425         case SnapToRegionSync:
2426         case SnapToRegionBoundary:
2427                 if (!region_boundary_cache.empty()) {
2428                         vector<nframes_t>::iterator i;
2429
2430                         if (direction > 0) {
2431                                 i = std::upper_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2432                         } else {
2433                                 i = std::lower_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2434                         }
2435                         
2436                         if (i != region_boundary_cache.end()) {
2437                                 start = *i;
2438                         } else {
2439                                 start = region_boundary_cache.back();
2440                         }
2441                 }
2442                 break;
2443         }
2444
2445         switch (snap_mode) {
2446         case SnapNormal:
2447                 return;                 
2448                 
2449         case SnapMagnetic:
2450                 
2451                 if (presnap > start) {
2452                         if (presnap > (start + unit_to_frame(snap_threshold))) {
2453                                 start = presnap;
2454                         }
2455                         
2456                 } else if (presnap < start) {
2457                         if (presnap < (start - unit_to_frame(snap_threshold))) {
2458                                 start = presnap;
2459                         }
2460                 }
2461                 
2462         default:
2463                 return;
2464                 
2465         }
2466 }
2467
2468 void
2469 Editor::setup_toolbar ()
2470 {
2471         string pixmap_path;
2472
2473         const guint32 FUDGE = 18; // Combo's are stupid - they steal space from the entry for the button
2474
2475
2476         /* Mode Buttons (tool selection) */
2477
2478         vector<ToggleButton *> mouse_mode_buttons;
2479
2480         mouse_move_button.add (*(manage (new Image (::get_icon("tool_object")))));
2481         mouse_move_button.set_relief(Gtk::RELIEF_NONE);
2482         mouse_mode_buttons.push_back (&mouse_move_button);
2483         mouse_select_button.add (*(manage (new Image (get_xpm("tool_range.xpm")))));
2484         mouse_select_button.set_relief(Gtk::RELIEF_NONE);
2485         mouse_mode_buttons.push_back (&mouse_select_button);
2486         mouse_gain_button.add (*(manage (new Image (::get_icon("tool_gain")))));
2487         mouse_gain_button.set_relief(Gtk::RELIEF_NONE);
2488         mouse_mode_buttons.push_back (&mouse_gain_button);
2489         mouse_zoom_button.add (*(manage (new Image (::get_icon("tool_zoom")))));
2490         mouse_zoom_button.set_relief(Gtk::RELIEF_NONE);
2491         mouse_mode_buttons.push_back (&mouse_zoom_button);
2492         mouse_timefx_button.add (*(manage (new Image (::get_icon("tool_stretch")))));
2493         mouse_timefx_button.set_relief(Gtk::RELIEF_NONE);
2494         mouse_mode_buttons.push_back (&mouse_timefx_button);
2495         mouse_audition_button.add (*(manage (new Image (::get_icon("tool_audition")))));
2496         mouse_audition_button.set_relief(Gtk::RELIEF_NONE);
2497         mouse_mode_buttons.push_back (&mouse_audition_button);
2498         
2499         mouse_mode_button_set = new GroupedButtons (mouse_mode_buttons);
2500
2501         HBox* mode_box = manage(new HBox);
2502         mode_box->set_border_width (2);
2503         mode_box->set_spacing(4);
2504         mouse_mode_button_box.set_spacing(1);
2505         mouse_mode_button_box.pack_start(mouse_move_button, true, true);
2506         mouse_mode_button_box.pack_start(mouse_select_button, true, true);
2507         mouse_mode_button_box.pack_start(mouse_zoom_button, true, true);
2508         mouse_mode_button_box.pack_start(mouse_gain_button, true, true);
2509         mouse_mode_button_box.pack_start(mouse_timefx_button, true, true);
2510         mouse_mode_button_box.pack_start(mouse_audition_button, true, true);
2511         mouse_mode_button_box.set_homogeneous(true);
2512
2513         vector<string> edit_mode_strings;
2514         edit_mode_strings.push_back (edit_mode_to_string (Splice));
2515         edit_mode_strings.push_back (edit_mode_to_string (Slide));
2516
2517         edit_mode_selector.set_name ("EditModeSelector");
2518         Gtkmm2ext::set_size_request_to_display_given_text (edit_mode_selector, longest (edit_mode_strings).c_str(), 2+FUDGE, 10);
2519         set_popdown_strings (edit_mode_selector, edit_mode_strings);
2520         edit_mode_selector.signal_changed().connect (mem_fun(*this, &Editor::edit_mode_selection_done));
2521
2522         mode_box->pack_start(edit_mode_selector);
2523         mode_box->pack_start(mouse_mode_button_box);
2524         
2525         mouse_mode_tearoff = manage (new TearOff (*mode_box));
2526         mouse_mode_tearoff->set_name ("MouseModeBase");
2527
2528         mouse_mode_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2529                                                   &mouse_mode_tearoff->tearoff_window()));
2530         mouse_mode_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2531                                                   &mouse_mode_tearoff->tearoff_window(), 1));
2532         mouse_mode_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2533                                                   &mouse_mode_tearoff->tearoff_window()));
2534         mouse_mode_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2535                                                    &mouse_mode_tearoff->tearoff_window(), 1));
2536
2537         mouse_move_button.set_name ("MouseModeButton");
2538         mouse_select_button.set_name ("MouseModeButton");
2539         mouse_gain_button.set_name ("MouseModeButton");
2540         mouse_zoom_button.set_name ("MouseModeButton");
2541         mouse_timefx_button.set_name ("MouseModeButton");
2542         mouse_audition_button.set_name ("MouseModeButton");
2543
2544         ARDOUR_UI::instance()->tooltips().set_tip (mouse_move_button, _("Select/Move Objects"));
2545         ARDOUR_UI::instance()->tooltips().set_tip (mouse_select_button, _("Select/Move Ranges"));
2546         ARDOUR_UI::instance()->tooltips().set_tip (mouse_gain_button, _("Draw Gain Automation"));
2547         ARDOUR_UI::instance()->tooltips().set_tip (mouse_zoom_button, _("Select Zoom Range"));
2548         ARDOUR_UI::instance()->tooltips().set_tip (mouse_timefx_button, _("Stretch/Shrink Regions"));
2549         ARDOUR_UI::instance()->tooltips().set_tip (mouse_audition_button, _("Listen to Specific Regions"));
2550
2551         mouse_move_button.unset_flags (CAN_FOCUS);
2552         mouse_select_button.unset_flags (CAN_FOCUS);
2553         mouse_gain_button.unset_flags (CAN_FOCUS);
2554         mouse_zoom_button.unset_flags (CAN_FOCUS);
2555         mouse_timefx_button.unset_flags (CAN_FOCUS);
2556         mouse_audition_button.unset_flags (CAN_FOCUS);
2557
2558         mouse_select_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseRange));
2559         mouse_select_button.signal_button_release_event().connect (mem_fun(*this, &Editor::mouse_select_button_release));
2560
2561         mouse_move_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseObject));
2562         mouse_gain_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseGain));
2563         mouse_zoom_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseZoom));
2564         mouse_timefx_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseTimeFX));
2565         mouse_audition_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseAudition));
2566
2567         // mouse_move_button.set_active (true);
2568         
2569
2570         /* Zoom */
2571         
2572         zoom_box.set_spacing (1);
2573         zoom_box.set_border_width (2);
2574
2575         zoom_in_button.set_name ("EditorTimeButton");
2576         zoom_in_button.add (*(manage (new Image (::get_icon("zoom_in")))));
2577         zoom_in_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::temporal_zoom_step), false));
2578         ARDOUR_UI::instance()->tooltips().set_tip (zoom_in_button, _("Zoom In"));
2579         
2580         zoom_out_button.set_name ("EditorTimeButton");
2581         zoom_out_button.add (*(manage (new Image (::get_icon("zoom_out")))));
2582         zoom_out_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::temporal_zoom_step), true));
2583         ARDOUR_UI::instance()->tooltips().set_tip (zoom_out_button, _("Zoom Out"));
2584
2585         zoom_out_full_button.set_name ("EditorTimeButton");
2586         zoom_out_full_button.add (*(manage (new Image (::get_icon("zoom_full")))));
2587         zoom_out_full_button.signal_clicked().connect (mem_fun(*this, &Editor::temporal_zoom_session));
2588         ARDOUR_UI::instance()->tooltips().set_tip (zoom_out_full_button, _("Zoom to Session"));
2589         
2590         zoom_box.pack_start (zoom_out_button, false, false);
2591         zoom_box.pack_start (zoom_in_button, false, false);
2592         zoom_box.pack_start (zoom_range_clock, false, false);   
2593         zoom_box.pack_start (zoom_out_full_button, false, false);
2594         
2595         ARDOUR_UI::instance()->tooltips().set_tip (zoom_range_clock, _("Current Zoom Range\n(Width of visible area)"));
2596
2597         zoom_focus_selector.set_name ("ZoomFocusSelector");
2598         Gtkmm2ext::set_size_request_to_display_given_text (zoom_focus_selector, "Focus Center", 2+FUDGE, 0);
2599         set_popdown_strings (zoom_focus_selector, zoom_focus_strings);
2600         zoom_focus_selector.signal_changed().connect (mem_fun(*this, &Editor::zoom_focus_selection_done));
2601         ARDOUR_UI::instance()->tooltips().set_tip (zoom_focus_selector, _("Zoom focus"));
2602
2603         zoom_box.pack_start (zoom_focus_selector, false, false);
2604
2605
2606         /* Edit Cursor / Snap */
2607
2608         snap_box.set_spacing (1);
2609         snap_box.set_border_width (2);
2610
2611         snap_type_selector.set_name ("SnapTypeSelector");
2612         Gtkmm2ext::set_size_request_to_display_given_text (snap_type_selector, "SMPTE Seconds", 2+FUDGE, 10);
2613         set_popdown_strings (snap_type_selector, snap_type_strings);
2614         snap_type_selector.signal_changed().connect (mem_fun(*this, &Editor::snap_type_selection_done));
2615         ARDOUR_UI::instance()->tooltips().set_tip (snap_type_selector, _("Unit to snap cursors and ranges to"));
2616
2617         snap_mode_selector.set_name ("SnapModeSelector");
2618         Gtkmm2ext::set_size_request_to_display_given_text (snap_mode_selector, "Magnetic Snap", 2+FUDGE, 10);
2619         set_popdown_strings (snap_mode_selector, snap_mode_strings);
2620         snap_mode_selector.signal_changed().connect (mem_fun(*this, &Editor::snap_mode_selection_done));
2621
2622         snap_box.pack_start (edit_cursor_clock, false, false);
2623         snap_box.pack_start (snap_mode_selector, false, false);
2624         snap_box.pack_start (snap_type_selector, false, false);
2625
2626
2627         /* Nudge */
2628
2629         HBox *nudge_box = manage (new HBox);
2630         nudge_box->set_spacing(1);
2631         nudge_box->set_border_width (2);
2632
2633         nudge_forward_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::nudge_forward), false));
2634         nudge_backward_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::nudge_backward), false));
2635
2636         nudge_box->pack_start (nudge_backward_button, false, false);
2637         nudge_box->pack_start (nudge_forward_button, false, false);
2638         nudge_box->pack_start (nudge_clock, false, false);
2639
2640
2641         /* Pack everything in... */
2642
2643         HBox* hbox = new HBox;
2644         hbox->set_spacing(10);
2645
2646         tools_tearoff = new TearOff (*hbox);
2647         tools_tearoff->set_name ("MouseModeBase");
2648
2649         tools_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2650                                              &tools_tearoff->tearoff_window()));
2651         tools_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2652                                              &tools_tearoff->tearoff_window(), 0));
2653         tools_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2654                                              &tools_tearoff->tearoff_window()));
2655         tools_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2656                                               &tools_tearoff->tearoff_window(), 0));
2657
2658         toolbar_hbox.set_spacing (10);
2659         toolbar_hbox.set_border_width (1);
2660
2661         toolbar_hbox.pack_start (*mouse_mode_tearoff, false, false);
2662         toolbar_hbox.pack_start (*tools_tearoff, false, false);
2663
2664         
2665         hbox->pack_start (snap_box, false, false);
2666         hbox->pack_start (zoom_box, false, false); 
2667         hbox->pack_start (*nudge_box, false, false);
2668
2669         hbox->show_all ();
2670         
2671         toolbar_base.set_name ("ToolBarBase");
2672         toolbar_base.add (toolbar_hbox);
2673
2674         toolbar_frame.set_shadow_type (SHADOW_OUT);
2675         toolbar_frame.set_name ("BaseFrame");
2676         toolbar_frame.add (toolbar_base);
2677 }
2678
2679 int
2680 Editor::convert_drop_to_paths (vector<ustring>& paths, 
2681                                const RefPtr<Gdk::DragContext>& context,
2682                                gint                x,
2683                                gint                y,
2684                                const SelectionData& data,
2685                                guint               info,
2686                                guint               time)                               
2687
2688 {       
2689         if (session == 0) {
2690                 return -1;
2691         }
2692
2693         vector<ustring> uris = data.get_uris();
2694
2695         if (uris.empty()) {
2696                 
2697                 /* This is seriously fucked up. Nautilus doesn't say that its URI lists
2698                    are actually URI lists. So do it by hand.
2699                 */
2700
2701                 if (data.get_target() != "text/plain") {
2702                         return -1;
2703                 }
2704   
2705                 /* Parse the "uri-list" format that Nautilus provides, 
2706                    where each pathname is delimited by \r\n
2707                 */
2708         
2709                 const char* p = data.get_text().c_str();
2710                 const char* q;
2711
2712                 while (p)
2713                 {
2714                         if (*p != '#')
2715                         {
2716                                 while (g_ascii_isspace (*p))
2717                                         p++;
2718                                 
2719                                 q = p;
2720                                 while (*q && (*q != '\n') && (*q != '\r'))
2721                                         q++;
2722                                 
2723                                 if (q > p)
2724                                 {
2725                                         q--;
2726                                         while (q > p && g_ascii_isspace (*q))
2727                                                 q--;
2728                                         
2729                                         if (q > p)
2730                                         {
2731                                                 uris.push_back (ustring (p, q - p + 1));
2732                                         }
2733                                 }
2734                         }
2735                         p = strchr (p, '\n');
2736                         if (p)
2737                                 p++;
2738                 }
2739
2740                 if (uris.empty()) {
2741                         return -1;
2742                 }
2743         }
2744         
2745         for (vector<ustring>::iterator i = uris.begin(); i != uris.end(); ++i) {
2746                 if ((*i).substr (0,7) == "file://") {
2747                         string p = *i;
2748                         PBD::url_decode (p);
2749                         paths.push_back (p.substr (7));
2750                 }
2751         }
2752
2753         return 0;
2754 }
2755
2756 void
2757 Editor::new_tempo_section ()
2758
2759 {
2760 }
2761
2762 void
2763 Editor::map_transport_state ()
2764 {
2765         ENSURE_GUI_THREAD (mem_fun(*this, &Editor::map_transport_state));
2766
2767         if (session->transport_stopped()) {
2768                 have_pending_keyboard_selection = false;
2769         }
2770 }
2771
2772 /* UNDO/REDO */
2773
2774 Editor::State::State ()
2775 {
2776         selection = new Selection;
2777 }
2778
2779 Editor::State::~State ()
2780 {
2781         delete selection;
2782 }
2783
2784 UndoAction
2785 Editor::get_memento () const
2786 {
2787         State *state = new State;
2788
2789         store_state (*state);
2790         return bind (mem_fun (*(const_cast<Editor*>(this)), &Editor::restore_state), state);
2791 }
2792
2793 void
2794 Editor::store_state (State& state) const
2795 {
2796         *state.selection = *selection;
2797 }
2798
2799 void
2800 Editor::restore_state (State *state)
2801 {
2802         if (*selection == *state->selection) {
2803                 return;
2804         }
2805
2806         *selection = *state->selection;
2807         time_selection_changed ();
2808         region_selection_changed ();   
2809
2810         /* XXX other selection change handlers? */
2811 }
2812
2813 void
2814 Editor::begin_reversible_command (string name)
2815 {
2816         if (session) {
2817                 before = &get_state();
2818                 session->begin_reversible_command (name);
2819         }
2820 }
2821
2822 void
2823 Editor::commit_reversible_command ()
2824 {
2825         if (session) {
2826                 session->commit_reversible_command (new MementoCommand<Editor>(*this, before, &get_state()));
2827         }
2828 }
2829
2830 bool
2831 Editor::set_selected_track (TimeAxisView& view, Selection::Operation op, bool no_remove)
2832 {
2833         bool commit = false;
2834
2835         switch (op) {
2836         case Selection::Toggle:
2837                 if (selection->selected (&view)) {
2838                         if (!no_remove) {
2839                                 selection->remove (&view);
2840                                 commit = true;
2841                         }
2842                 } else {
2843                         selection->add (&view);
2844                         commit = false;
2845                 }
2846                 break;
2847
2848         case Selection::Set:
2849                 if (selection->selected (&view) && selection->tracks.size() == 1) {
2850                         /* no commit necessary */
2851                 } 
2852
2853                 selection->set (&view);
2854                 break;
2855                 
2856         case Selection::Extend:
2857                 /* not defined yet */
2858                 break;
2859         }
2860
2861         return commit;
2862 }
2863
2864 bool
2865 Editor::set_selected_track_from_click (Selection::Operation op, bool no_remove)
2866 {
2867         if (!clicked_trackview) {
2868                 return false;
2869         }
2870         
2871         return set_selected_track (*clicked_trackview, op, no_remove);
2872 }
2873
2874 bool
2875 Editor::set_selected_control_point_from_click (Selection::Operation op, bool no_remove)
2876 {
2877         if (!clicked_control_point) {
2878                 return false;
2879         }
2880
2881         /* select this point and any others that it represents */
2882
2883         double y1, y2;
2884         nframes_t x1, x2;
2885
2886         x1 = pixel_to_frame (clicked_control_point->get_x() - 10);
2887         x2 = pixel_to_frame (clicked_control_point->get_x() + 10);
2888         y1 = clicked_control_point->get_x() - 10;
2889         y2 = clicked_control_point->get_y() + 10;
2890
2891         return select_all_within (x1, x2, y1, y2, op);
2892 }
2893
2894 void
2895 Editor::get_relevant_audio_tracks (AudioTimeAxisView& base, set<AudioTimeAxisView*>& relevant_tracks)
2896 {
2897         /* step one: get all selected tracks and all tracks in the relevant edit groups */
2898
2899         for (TrackSelection::iterator ti = selection->tracks.begin(); ti != selection->tracks.end(); ++ti) {
2900
2901                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(*ti);
2902
2903                 if (!atv) {
2904                         continue;
2905                 }
2906
2907                 RouteGroup* group = atv->route()->edit_group();
2908
2909                 if (group && group->is_active()) {
2910                         
2911                         /* active group for this track, loop over all tracks and get every member of the group */
2912
2913                         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
2914                                 
2915                                 AudioTimeAxisView* tatv;
2916                                 
2917                                 if ((tatv = dynamic_cast<AudioTimeAxisView*> (*i)) != 0) {
2918                                         
2919                                         if (tatv->route()->edit_group() == group) {
2920                                                 relevant_tracks.insert (tatv);
2921                                         }
2922                                 }
2923                         }
2924
2925                 } else {
2926
2927                         /* no active group, or no group */
2928
2929                         relevant_tracks.insert (&base);
2930                 }
2931
2932         }
2933 }
2934
2935 void
2936 Editor::mapover_audio_tracks (slot<void,AudioTimeAxisView&,uint32_t> sl)
2937 {
2938         set<AudioTimeAxisView*> relevant_tracks;
2939
2940         if (!clicked_audio_trackview) {
2941                 return;
2942         }
2943
2944         get_relevant_audio_tracks (*clicked_audio_trackview, relevant_tracks);
2945
2946         uint32_t sz = relevant_tracks.size();
2947         
2948         for (set<AudioTimeAxisView*>::iterator ati = relevant_tracks.begin(); ati != relevant_tracks.end(); ++ati) {
2949                 sl (**ati, sz);
2950         }
2951 }
2952
2953 void
2954 Editor::mapped_set_selected_regionview_from_click (RouteTimeAxisView& tv, uint32_t ignored, 
2955                                                    RegionView* basis, vector<RegionView*>* all_equivs)
2956 {
2957         Playlist* pl;
2958         vector<boost::shared_ptr<Region> > results;
2959         RegionView* marv;
2960         boost::shared_ptr<Diskstream> ds;
2961
2962         if ((ds = tv.get_diskstream()) == 0) {
2963                 /* bus */
2964                 return;
2965         }
2966
2967         if (&tv == &basis->get_time_axis_view()) {
2968                 /* looking in same track as the original */
2969                 return;
2970         }
2971
2972         
2973         if ((pl = dynamic_cast<Playlist*>(ds->playlist())) != 0) {
2974                 pl->get_equivalent_regions (basis->region(), results);
2975         }
2976         
2977         for (vector<boost::shared_ptr<Region> >::iterator ir = results.begin(); ir != results.end(); ++ir) {
2978                 if ((marv = tv.view()->find_view (*ir)) != 0) {
2979                         all_equivs->push_back (marv);
2980                 }
2981         }
2982 }
2983
2984 bool
2985 Editor::set_selected_regionview_from_click (bool press, Selection::Operation op, bool no_track_remove)
2986 {
2987         vector<RegionView*> all_equivalent_regions;
2988         bool commit = false;
2989
2990         if (!clicked_regionview || !clicked_audio_trackview) {
2991                 return false;
2992         }
2993
2994         if (op == Selection::Toggle || op == Selection::Set) {
2995                 
2996                 mapover_audio_tracks (bind (mem_fun (*this, &Editor::mapped_set_selected_regionview_from_click), 
2997                                             clicked_regionview, &all_equivalent_regions));
2998                 
2999                 
3000                 /* add clicked regionview since we skipped all other regions in the same track as the one it was in */
3001                 
3002                 all_equivalent_regions.push_back (clicked_regionview);
3003                 
3004                 switch (op) {
3005                 case Selection::Toggle:
3006                         
3007                         if (clicked_regionview->get_selected()) {
3008                                 if (press) {
3009
3010                                         /* whatever was clicked was selected already; do nothing here but allow
3011                                            the button release to deselect it
3012                                         */
3013
3014                                         button_release_can_deselect = true;
3015
3016                                 } else {
3017
3018                                         if (button_release_can_deselect) {
3019
3020                                                 /* just remove this one region, but only on a permitted button release */
3021
3022                                                 selection->remove (clicked_regionview);
3023                                                 commit = true;
3024
3025                                                 /* no more deselect action on button release till a new press
3026                                                    finds an already selected object.
3027                                                 */
3028
3029                                                 button_release_can_deselect = false;
3030                                         }
3031                                 } 
3032
3033                         } else {
3034
3035                                 if (press) {
3036                                         /* add all the equivalent regions, but only on button press */
3037                                         
3038                                         if (!all_equivalent_regions.empty()) {
3039                                                 commit = true;
3040                                         }
3041                                         
3042                                         for (vector<RegionView*>::iterator i = all_equivalent_regions.begin(); i != all_equivalent_regions.end(); ++i) {
3043                                                 selection->add (*i);
3044                                         }
3045                                 } 
3046                         }
3047                         break;
3048                         
3049                 case Selection::Set:
3050                         if (!clicked_regionview->get_selected()) {
3051                                 selection->set (all_equivalent_regions);
3052                                 commit = true;
3053                         } else {
3054                                 /* no commit necessary: clicked on an already selected region */
3055                                 goto out;
3056                         }
3057                         break;
3058
3059                 default:
3060                         /* silly compiler */
3061                         break;
3062                 }
3063
3064         } else if (op == Selection::Extend) {
3065
3066                 list<Selectable*> results;
3067                 nframes_t last_frame;
3068                 nframes_t first_frame;
3069
3070                 /* 1. find the last selected regionview in the track that was clicked in */
3071
3072                 last_frame = 0;
3073                 first_frame = max_frames;
3074
3075                 for (RegionSelection::iterator x = selection->regions.begin(); x != selection->regions.end(); ++x) {
3076                         if (&(*x)->get_time_axis_view() == &clicked_regionview->get_time_axis_view()) {
3077
3078                                 if ((*x)->region()->last_frame() > last_frame) {
3079                                         last_frame = (*x)->region()->last_frame();
3080                                 }
3081
3082                                 if ((*x)->region()->first_frame() < first_frame) {
3083                                         first_frame = (*x)->region()->first_frame();
3084                                 }
3085                         }
3086                 }
3087
3088                 /* 2. figure out the boundaries for our search for new objects */
3089
3090                 switch (clicked_regionview->region()->coverage (first_frame, last_frame)) {
3091                 case OverlapNone:
3092                         if (last_frame < clicked_regionview->region()->first_frame()) {
3093                                 first_frame = last_frame;
3094                                 last_frame = clicked_regionview->region()->last_frame();
3095                         } else {
3096                                 last_frame = first_frame;
3097                                 first_frame = clicked_regionview->region()->first_frame();
3098                         }
3099                         break;
3100
3101                 case OverlapExternal:
3102                         if (last_frame < clicked_regionview->region()->first_frame()) {
3103                                 first_frame = last_frame;
3104                                 last_frame = clicked_regionview->region()->last_frame();
3105                         } else {
3106                                 last_frame = first_frame;
3107                                 first_frame = clicked_regionview->region()->first_frame();
3108                         }
3109                         break;
3110
3111                 case OverlapInternal:
3112                         if (last_frame < clicked_regionview->region()->first_frame()) {
3113                                 first_frame = last_frame;
3114                                 last_frame = clicked_regionview->region()->last_frame();
3115                         } else {
3116                                 last_frame = first_frame;
3117                                 first_frame = clicked_regionview->region()->first_frame();
3118                         }
3119                         break;
3120
3121                 case OverlapStart:
3122                 case OverlapEnd:
3123                         /* nothing to do except add clicked region to selection, since it
3124                            overlaps with the existing selection in this track.
3125                         */
3126                         break;
3127                 }
3128
3129                 /* 2. find all selectable objects (regionviews in this case) between that one and the end of the
3130                       one that was clicked.
3131                 */
3132
3133                 set<AudioTimeAxisView*> relevant_tracks;
3134                 
3135                 get_relevant_audio_tracks (*clicked_audio_trackview, relevant_tracks);
3136                 
3137                 for (set<AudioTimeAxisView*>::iterator t = relevant_tracks.begin(); t != relevant_tracks.end(); ++t) {
3138                         (*t)->get_selectables (first_frame, last_frame, -1.0, -1.0, results);
3139                 }
3140                 
3141                 /* 3. convert to a vector of audio regions */
3142
3143                 vector<RegionView*> regions;
3144                 
3145                 for (list<Selectable*>::iterator x = results.begin(); x != results.end(); ++x) {
3146                         RegionView* arv;
3147
3148                         if ((arv = dynamic_cast<RegionView*>(*x)) != 0) {
3149                                 regions.push_back (arv);
3150                         }
3151                 }
3152
3153                 if (!regions.empty()) {
3154                         selection->add (regions);
3155                         commit = true;
3156                 }
3157         }
3158
3159   out:
3160         return commit;
3161 }
3162
3163 void
3164 Editor::set_selected_regionview_from_region_list (boost::shared_ptr<Region> region, Selection::Operation op)
3165 {
3166         vector<RegionView*> all_equivalent_regions;
3167
3168         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
3169                 
3170                 RouteTimeAxisView* tatv;
3171                 
3172                 if ((tatv = dynamic_cast<RouteTimeAxisView*> (*i)) != 0) {
3173                         
3174                         Playlist* pl;
3175                         vector<boost::shared_ptr<Region> > results;
3176                         RegionView* marv;
3177                         boost::shared_ptr<Diskstream> ds;
3178                         
3179                         if ((ds = tatv->get_diskstream()) == 0) {
3180                                 /* bus */
3181                                 continue;
3182                         }
3183
3184                         if ((pl = dynamic_cast<Playlist*>(ds->playlist())) != 0) {
3185                                 pl->get_region_list_equivalent_regions (region, results);
3186                         }
3187                         
3188                         for (vector<boost::shared_ptr<Region> >::iterator ir = results.begin(); ir != results.end(); ++ir) {
3189                                 if ((marv = tatv->view()->find_view (*ir)) != 0) {
3190                                         all_equivalent_regions.push_back (marv);
3191                                 }
3192                         }
3193                         
3194                 }
3195         }
3196         
3197         begin_reversible_command (_("set selected regions"));
3198         
3199         switch (op) {
3200         case Selection::Toggle:
3201                 /* XXX this is not correct */
3202                 selection->toggle (all_equivalent_regions);
3203                 break;
3204         case Selection::Set:
3205                 selection->set (all_equivalent_regions);
3206                 break;
3207         case Selection::Extend:
3208                 selection->add (all_equivalent_regions);
3209                 break;
3210         }
3211
3212         commit_reversible_command () ;
3213 }
3214
3215 bool
3216 Editor::set_selected_regionview_from_map_event (GdkEventAny* ev, StreamView* sv, boost::weak_ptr<Region> weak_r)
3217 {
3218         RegionView* rv;
3219         boost::shared_ptr<Region> r (weak_r.lock());
3220
3221         if (!r) {
3222                 return true;
3223         }
3224
3225         boost::shared_ptr<AudioRegion> ar;
3226
3227         if ((ar = boost::dynamic_pointer_cast<AudioRegion> (r)) == 0) {
3228                 return true;
3229         }
3230
3231         if ((rv = sv->find_view (ar)) == 0) {
3232                 return true;
3233         }
3234
3235         /* don't reset the selection if its something other than 
3236            a single other region.
3237         */
3238
3239         if (selection->regions.size() > 1) {
3240                 return true;
3241         }
3242         
3243         begin_reversible_command (_("set selected regions"));
3244         
3245         selection->set (rv);
3246
3247         commit_reversible_command () ;
3248
3249         return true;
3250 }
3251
3252 void
3253 Editor::set_edit_group_solo (Route& route, bool yn)
3254 {
3255         RouteGroup *edit_group;
3256
3257         if ((edit_group = route.edit_group()) != 0) {
3258                 edit_group->apply (&Route::set_solo, yn, this);
3259         } else {
3260                 route.set_solo (yn, this);
3261         }
3262 }
3263
3264 void
3265 Editor::set_edit_group_mute (Route& route, bool yn)
3266 {
3267         RouteGroup *edit_group = 0;
3268
3269         if ((edit_group == route.edit_group()) != 0) {
3270                 edit_group->apply (&Route::set_mute, yn, this);
3271         } else {
3272                 route.set_mute (yn, this);
3273         }
3274 }
3275                 
3276 void
3277 Editor::set_edit_menu (Menu& menu)
3278 {
3279         edit_menu = &menu;
3280         edit_menu->signal_map_event().connect (mem_fun(*this, &Editor::edit_menu_map_handler));
3281 }
3282
3283 bool
3284 Editor::edit_menu_map_handler (GdkEventAny* ev)
3285 {
3286         using namespace Menu_Helpers;
3287         MenuList& edit_items = edit_menu->items();
3288         string label;
3289
3290         /* Nuke all the old items */
3291                 
3292         edit_items.clear ();
3293
3294         if (session == 0) {
3295                 return false;
3296         }
3297
3298         if (session->undo_depth() == 0) {
3299                 label = _("Undo");
3300         } else {
3301                 label = string_compose(_("Undo (%1)"), session->next_undo());
3302         }
3303         
3304         edit_items.push_back (MenuElem (label, bind (mem_fun(*this, &Editor::undo), 1U)));
3305         
3306         if (session->undo_depth() == 0) {
3307                 edit_items.back().set_sensitive (false);
3308         }
3309         
3310         if (session->redo_depth() == 0) {
3311                 label = _("Redo");
3312         } else {
3313                 label = string_compose(_("Redo (%1)"), session->next_redo());
3314         }
3315         
3316         edit_items.push_back (MenuElem (label, bind (mem_fun(*this, &Editor::redo), 1U)));
3317         if (session->redo_depth() == 0) {
3318                 edit_items.back().set_sensitive (false);
3319         }
3320
3321         vector<MenuItem*> mitems;
3322
3323         edit_items.push_back (SeparatorElem());
3324         edit_items.push_back (MenuElem (_("Cut"), mem_fun(*this, &Editor::cut)));
3325         mitems.push_back (&edit_items.back());
3326         edit_items.push_back (MenuElem (_("Copy"), mem_fun(*this, &Editor::copy)));
3327         mitems.push_back (&edit_items.back());
3328         edit_items.push_back (MenuElem (_("Paste"), bind (mem_fun(*this, &Editor::paste), 1.0f)));
3329         mitems.push_back (&edit_items.back());
3330         edit_items.push_back (SeparatorElem());
3331         edit_items.push_back (MenuElem (_("Align"), bind (mem_fun(*this, &Editor::align), ARDOUR::SyncPoint)));
3332         mitems.push_back (&edit_items.back());
3333         edit_items.push_back (MenuElem (_("Align Relative"), bind (mem_fun(*this, &Editor::align_relative), ARDOUR::SyncPoint)));
3334         mitems.push_back (&edit_items.back());
3335         edit_items.push_back (SeparatorElem());
3336
3337         if (selection->empty()) {
3338                 for (vector<MenuItem*>::iterator i = mitems.begin(); i != mitems.end(); ++i) {
3339                         (*i)->set_sensitive (false);
3340                 }
3341         }
3342
3343         Menu* import_menu = manage (new Menu());
3344         import_menu->set_name ("ArdourContextMenu");
3345         MenuList& import_items = import_menu->items();
3346         
3347         import_items.push_back (MenuElem (_("... as new track"), bind (mem_fun(*this, &Editor::add_external_audio_action), ImportAsTrack)));
3348         import_items.push_back (MenuElem (_("... as new region"), bind (mem_fun(*this, &Editor::add_external_audio_action), ImportAsRegion)));
3349
3350         edit_items.push_back (MenuElem (_("Import audio (copy)"), *import_menu));
3351         edit_items.push_back (SeparatorElem());
3352
3353         edit_items.push_back (MenuElem (_("Remove last capture"), mem_fun(*this, &Editor::remove_last_capture)));
3354
3355         if (!session->have_captured()) {
3356                 edit_items.back().set_sensitive (false);
3357         }
3358
3359         return false;
3360 }
3361
3362 void
3363 Editor::duplicate_dialog (bool dup_region)
3364 {
3365         if (dup_region) {
3366                 if (clicked_regionview == 0) {
3367                         return;
3368                 }
3369         } else {
3370                 if (selection->time.length() == 0) {
3371                         return;
3372                 }
3373         }
3374
3375         ArdourDialog win ("duplicate dialog");
3376         Entry  entry;
3377         Label  label (_("Duplicate how many times?"));
3378
3379         win.get_vbox()->pack_start (label);
3380         win.add_action_widget (entry, RESPONSE_ACCEPT);
3381         win.add_button (Stock::OK, RESPONSE_ACCEPT);
3382         win.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3383
3384         win.set_position (WIN_POS_MOUSE);
3385
3386         entry.set_text ("1");
3387         set_size_request_to_display_given_text (entry, X_("12345678"), 20, 15);
3388         entry.select_region (0, entry.get_text_length());
3389         entry.grab_focus ();
3390
3391
3392         switch (win.run ()) {
3393         case RESPONSE_ACCEPT:
3394                 break;
3395         default:
3396                 return;
3397         }
3398
3399         string text = entry.get_text();
3400         float times;
3401
3402         if (sscanf (text.c_str(), "%f", &times) == 1) {
3403                 if (dup_region) {
3404                         RegionSelection regions;
3405                         regions.add (clicked_regionview);
3406                         duplicate_some_regions (regions, times);
3407                 } else {
3408                         duplicate_selection (times);
3409                 }
3410         }
3411 }
3412
3413 void
3414 Editor::show_verbose_canvas_cursor ()
3415 {
3416         verbose_canvas_cursor->raise_to_top();
3417         verbose_canvas_cursor->show();
3418         verbose_cursor_visible = true;
3419 }
3420
3421 void
3422 Editor::hide_verbose_canvas_cursor ()
3423 {
3424         verbose_canvas_cursor->hide();
3425         verbose_cursor_visible = false;
3426 }
3427
3428 void
3429 Editor::set_verbose_canvas_cursor (const string & txt, double x, double y)
3430 {
3431         /* XXX get origin of canvas relative to root window,
3432            add x and y and check compared to gdk_screen_{width,height}
3433         */
3434         verbose_canvas_cursor->property_text() = txt.c_str();
3435         verbose_canvas_cursor->property_x() = x;
3436         verbose_canvas_cursor->property_y() = y;
3437 }
3438
3439 void
3440 Editor::set_verbose_canvas_cursor_text (const string & txt)
3441 {
3442         verbose_canvas_cursor->property_text() = txt.c_str();
3443 }
3444
3445 void
3446 Editor::edit_mode_selection_done ()
3447 {
3448         if (session == 0) {
3449                 return;
3450         }
3451
3452         string choice = edit_mode_selector.get_active_text();
3453         EditMode mode = Slide;
3454
3455         if (choice == _("Splice Edit")) {
3456                 mode = Splice;
3457         } else if (choice == _("Slide Edit")) {
3458                 mode = Slide;
3459         }
3460
3461         Config->set_edit_mode (mode);
3462 }       
3463
3464 void
3465 Editor::snap_type_selection_done ()
3466 {
3467         string choice = snap_type_selector.get_active_text();
3468         SnapType snaptype = SnapToFrame;
3469
3470         if (choice == _("Beats/3")) {
3471                 snaptype = SnapToAThirdBeat;
3472         } else if (choice == _("Beats/4")) {
3473                 snaptype = SnapToAQuarterBeat;
3474         } else if (choice == _("Beats/8")) {
3475                 snaptype = SnapToAEighthBeat;
3476         } else if (choice == _("Beats/16")) {
3477                 snaptype = SnapToASixteenthBeat;
3478         } else if (choice == _("Beats/32")) {
3479                 snaptype = SnapToAThirtysecondBeat;
3480         } else if (choice == _("Beats")) {
3481                 snaptype = SnapToBeat;
3482         } else if (choice == _("Bars")) {
3483                 snaptype = SnapToBar;
3484         } else if (choice == _("Marks")) {
3485                 snaptype = SnapToMark;
3486         } else if (choice == _("Edit Cursor")) {
3487                 snaptype = SnapToEditCursor;
3488         } else if (choice == _("Region starts")) {
3489                 snaptype = SnapToRegionStart;
3490         } else if (choice == _("Region ends")) {
3491                 snaptype = SnapToRegionEnd;
3492         } else if (choice == _("Region bounds")) {
3493                 snaptype = SnapToRegionBoundary;
3494         } else if (choice == _("Region syncs")) {
3495                 snaptype = SnapToRegionSync;
3496         } else if (choice == _("CD Frames")) {
3497                 snaptype = SnapToCDFrame;
3498         } else if (choice == _("SMPTE Frames")) {
3499                 snaptype = SnapToSMPTEFrame;
3500         } else if (choice == _("SMPTE Seconds")) {
3501                 snaptype = SnapToSMPTESeconds;
3502         } else if (choice == _("SMPTE Minutes")) {
3503                 snaptype = SnapToSMPTEMinutes;
3504         } else if (choice == _("Seconds")) {
3505                 snaptype = SnapToSeconds;
3506         } else if (choice == _("Minutes")) {
3507                 snaptype = SnapToMinutes;
3508         } else if (choice == _("None")) {
3509                 snaptype = SnapToFrame;
3510         }
3511
3512         RefPtr<RadioAction> ract = snap_type_action (snaptype);
3513         if (ract) {
3514                 ract->set_active ();
3515         }
3516 }       
3517
3518 void
3519 Editor::snap_mode_selection_done ()
3520 {
3521         string choice = snap_mode_selector.get_active_text();
3522         SnapMode mode = SnapNormal;
3523
3524         if (choice == _("Normal")) {
3525                 mode = SnapNormal;
3526         } else if (choice == _("Magnetic")) {
3527                 mode = SnapMagnetic;
3528         }
3529
3530         RefPtr<RadioAction> ract = snap_mode_action (mode);
3531
3532         if (ract) {
3533                 ract->set_active (true);
3534         }
3535 }
3536
3537 void
3538 Editor::zoom_focus_selection_done ()
3539 {
3540         string choice = zoom_focus_selector.get_active_text();
3541         ZoomFocus focus_type = ZoomFocusLeft;
3542
3543         if (choice == _("Left")) {
3544                 focus_type = ZoomFocusLeft;
3545         } else if (choice == _("Right")) {
3546                 focus_type = ZoomFocusRight;
3547         } else if (choice == _("Center")) {
3548                 focus_type = ZoomFocusCenter;
3549         } else if (choice == _("Playhead")) {
3550                 focus_type = ZoomFocusPlayhead;
3551         } else if (choice == _("Edit Cursor")) {
3552                 focus_type = ZoomFocusEdit;
3553         } 
3554         
3555         RefPtr<RadioAction> ract = zoom_focus_action (focus_type);
3556
3557         if (ract) {
3558                 ract->set_active ();
3559         }
3560 }       
3561
3562 gint
3563 Editor::edit_controls_button_release (GdkEventButton* ev)
3564 {
3565         if (Keyboard::is_context_menu_event (ev)) {
3566                 ARDOUR_UI::instance()->add_route ();
3567         }
3568         return TRUE;
3569 }
3570
3571 void
3572 Editor::track_selection_changed ()
3573 {
3574         switch (selection->tracks.size()){
3575         case 0:
3576                 break;
3577         default:
3578                 set_selected_mixer_strip (*(selection->tracks.front()));
3579                 break;
3580         }
3581
3582         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
3583                 (*i)->set_selected (false);
3584                 if (mouse_mode == MouseRange) {
3585                         (*i)->hide_selection ();
3586                 }
3587         }
3588
3589         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
3590                 (*i)->set_selected (true);
3591                 if (mouse_mode == MouseRange) {
3592                         (*i)->show_selection (selection->time);
3593                 }
3594         }
3595 }
3596
3597 void
3598 Editor::time_selection_changed ()
3599 {
3600         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
3601                 (*i)->hide_selection ();
3602         }
3603
3604         if (selection->tracks.empty()) {
3605                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
3606                         (*i)->show_selection (selection->time);
3607                 }
3608         } else {
3609                 for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
3610                         (*i)->show_selection (selection->time);
3611                 }
3612         }
3613
3614         if (selection->time.empty()) {
3615                 ActionManager::set_sensitive (ActionManager::time_selection_sensitive_actions, false);
3616         } else {
3617                 ActionManager::set_sensitive (ActionManager::time_selection_sensitive_actions, true);
3618         }
3619 }
3620
3621 void
3622 Editor::region_selection_changed ()
3623 {
3624         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
3625                 (*i)->set_selected_regionviews (selection->regions);
3626         }
3627 }
3628
3629 void
3630 Editor::point_selection_changed ()
3631 {
3632         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
3633                 (*i)->set_selected_points (selection->points);
3634         }
3635 }
3636
3637 gint
3638 Editor::mouse_select_button_release (GdkEventButton* ev)
3639 {
3640         /* this handles just right-clicks */
3641
3642         if (ev->button != 3) {
3643                 return FALSE;
3644         }
3645
3646         return TRUE;
3647 }
3648
3649 Editor::TrackViewList *
3650 Editor::get_valid_views (TimeAxisView* track, RouteGroup* group)
3651 {
3652         TrackViewList *v;
3653         TrackViewList::iterator i;
3654
3655         v = new TrackViewList;
3656
3657         if (track == 0 && group == 0) {
3658
3659                 /* all views */
3660
3661                 for (i = track_views.begin(); i != track_views.end (); ++i) {
3662                         v->push_back (*i);
3663                 }
3664
3665         } else if (track != 0 && group == 0 || (track != 0 && group != 0 && !group->is_active())) {
3666                 
3667                 /* just the view for this track
3668                  */
3669
3670                 v->push_back (track);
3671
3672         } else {
3673                 
3674                 /* views for all tracks in the edit group */
3675                 
3676                 for (i  = track_views.begin(); i != track_views.end (); ++i) {
3677
3678                         if (group == 0 || (*i)->edit_group() == group) {
3679                                 v->push_back (*i);
3680                         }
3681                 }
3682         }
3683         
3684         return v;
3685 }
3686
3687 void
3688 Editor::set_zoom_focus (ZoomFocus f)
3689 {
3690         string str = zoom_focus_strings[(int)f];
3691
3692         if (str != zoom_focus_selector.get_active_text()) {
3693                 zoom_focus_selector.set_active_text (str);
3694         }
3695         
3696         if (zoom_focus != f) {
3697                 zoom_focus = f;
3698
3699                 ZoomFocusChanged (); /* EMIT_SIGNAL */
3700
3701                 instant_save ();
3702         }
3703 }
3704
3705 void
3706 Editor::ensure_float (Window& win)
3707 {
3708         win.set_transient_for (*this);
3709 }
3710
3711 void 
3712 Editor::pane_allocation_handler (Allocation &alloc, Paned* which)
3713 {
3714         /* recover or initialize pane positions. do this here rather than earlier because
3715            we don't want the positions to change the child allocations, which they seem to do.
3716          */
3717
3718         int pos;
3719         XMLProperty* prop;
3720         char buf[32];
3721         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
3722         int width, height;
3723         static int32_t done;
3724         XMLNode* geometry;
3725
3726         if ((geometry = find_named_node (*node, "geometry")) == 0) {
3727                 width = default_width;
3728                 height = default_height;
3729         } else {
3730                 width = atoi(geometry->property("x_size")->value());
3731                 height = atoi(geometry->property("y_size")->value());
3732         }
3733
3734         if (which == static_cast<Paned*> (&edit_pane)) {
3735
3736                 if (done) {
3737                         return;
3738                 }
3739
3740                 if (!geometry || (prop = geometry->property ("edit_pane_pos")) == 0) {
3741                         /* initial allocation is 90% to canvas, 10% to notebook */
3742                         pos = (int) floor (alloc.get_width() * 0.90f);
3743                         snprintf (buf, sizeof(buf), "%d", pos);
3744                 } else {
3745                         pos = atoi (prop->value());
3746                 }
3747                 
3748                 if ((done = GTK_WIDGET(edit_pane.gobj())->allocation.width > pos)) {
3749                         edit_pane.set_position (pos);
3750                         pre_maximal_pane_position = pos;
3751                 }
3752         }
3753 }
3754
3755 void
3756 Editor::detach_tearoff (Box* b, Window* w)
3757 {
3758         if (tools_tearoff->torn_off() && 
3759             mouse_mode_tearoff->torn_off()) {
3760                 top_hbox.remove (toolbar_frame);
3761         }
3762 }
3763
3764 void
3765 Editor::reattach_tearoff (Box* b, Window* w, int32_t n)
3766 {
3767         if (toolbar_frame.get_parent() == 0) {
3768                 top_hbox.pack_end (toolbar_frame);
3769         }
3770 }
3771
3772 void
3773 Editor::set_show_measures (bool yn)
3774 {
3775         if (_show_measures != yn) {
3776                 hide_measures ();
3777
3778                 if ((_show_measures = yn) == true) {
3779                         draw_measures ();
3780                 }
3781                 DisplayControlChanged (ShowMeasures);
3782                 instant_save ();
3783         }
3784 }
3785
3786 void
3787 Editor::toggle_follow_playhead ()
3788 {
3789         RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
3790         if (act) {
3791                 RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
3792                 set_follow_playhead (tact->get_active());
3793         }
3794 }
3795
3796 void
3797 Editor::set_follow_playhead (bool yn)
3798 {
3799         if (_follow_playhead != yn) {
3800                 if ((_follow_playhead = yn) == true) {
3801                         /* catch up */
3802                         update_current_screen ();
3803                 }
3804                 DisplayControlChanged (FollowPlayhead);
3805                 instant_save ();
3806         }
3807 }
3808
3809 void
3810 Editor::toggle_xfade_active (Crossfade* xfade)
3811 {
3812         xfade->set_active (!xfade->active());
3813 }
3814
3815 void
3816 Editor::toggle_xfade_length (Crossfade* xfade)
3817 {
3818         xfade->set_follow_overlap (!xfade->following_overlap());
3819 }
3820
3821 void
3822 Editor::edit_xfade (Crossfade* xfade)
3823 {
3824         CrossfadeEditor cew (*session, *xfade, xfade->fade_in().get_min_y(), 1.0);
3825                 
3826         ensure_float (cew);
3827         
3828         switch (cew.run ()) {
3829         case RESPONSE_ACCEPT:
3830                 break;
3831         default:
3832                 return;
3833         }
3834         
3835         cew.apply ();
3836         xfade->StateChanged (Change (~0));
3837 }
3838
3839 PlaylistSelector&
3840 Editor::playlist_selector () const
3841 {
3842         return *_playlist_selector;
3843 }
3844
3845 nframes_t
3846 Editor::get_nudge_distance (nframes_t pos, nframes_t& next)
3847 {
3848         nframes_t ret;
3849
3850         ret = nudge_clock.current_duration (pos);
3851         next = ret + 1; /* XXXX fix me */
3852
3853         return ret;
3854 }
3855
3856 void
3857 Editor::end_location_changed (Location* location)
3858 {
3859         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::end_location_changed), location));
3860         reset_scrolling_region ();
3861 }
3862
3863 int
3864 Editor::playlist_deletion_dialog (Playlist* pl)
3865 {
3866         ArdourDialog dialog ("playlist deletion dialog");
3867         Label  label (string_compose (_("Playlist %1 is currently unused.\n"
3868                                  "If left alone, no audio files used by it will be cleaned.\n"
3869                                  "If deleted, audio files used by it alone by will cleaned."),
3870                                pl->name()));
3871
3872         dialog.set_position (WIN_POS_CENTER);
3873         dialog.get_vbox()->pack_start (label);
3874
3875         dialog.add_button (_("Delete playlist"), RESPONSE_ACCEPT);
3876         dialog.add_button (_("Keep playlist"), RESPONSE_CANCEL);
3877         dialog.add_button (_("Cancel"), RESPONSE_CANCEL);
3878
3879         switch (dialog.run ()) {
3880         case RESPONSE_ACCEPT:
3881                 /* delete the playlist */
3882                 return 0;
3883                 break;
3884
3885         case RESPONSE_REJECT:
3886                 /* keep the playlist */
3887                 return 1;
3888                 break;
3889
3890         default:
3891                 break;
3892         }
3893
3894         return -1;
3895 }
3896
3897 bool
3898 Editor::audio_region_selection_covers (nframes_t where)
3899 {
3900         for (RegionSelection::iterator a = selection->regions.begin(); a != selection->regions.end(); ++a) {
3901                 if ((*a)->region()->covers (where)) {
3902                         return true;
3903                 }
3904         }
3905
3906         return false;
3907 }
3908
3909 void
3910 Editor::prepare_for_cleanup ()
3911 {
3912         cut_buffer->clear_regions ();
3913         cut_buffer->clear_playlists ();
3914
3915         selection->clear_regions ();
3916         selection->clear_playlists ();
3917 }
3918
3919 Location*
3920 Editor::transport_loop_location()
3921 {
3922         if (session) {
3923                 return session->locations()->auto_loop_location();
3924         } else {
3925                 return 0;
3926         }
3927 }
3928
3929 Location*
3930 Editor::transport_punch_location()
3931 {
3932         if (session) {
3933                 return session->locations()->auto_punch_location();
3934         } else {
3935                 return 0;
3936         }
3937 }
3938
3939 bool
3940 Editor::control_layout_scroll (GdkEventScroll* ev)
3941 {
3942         switch (ev->direction) {
3943         case GDK_SCROLL_UP:
3944                 scroll_tracks_up_line ();
3945                 return true;
3946                 break;
3947
3948         case GDK_SCROLL_DOWN:
3949                 scroll_tracks_down_line ();
3950                 return true;
3951                 
3952         default:
3953                 /* no left/right handling yet */
3954                 break;
3955         }
3956
3957         return false;
3958 }
3959
3960 void
3961 Editor::snapshot_display_selection_changed ()
3962 {
3963         if (snapshot_display.get_selection()->count_selected_rows() > 0) {
3964
3965                 TreeModel::iterator i = snapshot_display.get_selection()->get_selected();
3966                 
3967                 Glib::ustring snap_name = (*i)[snapshot_display_columns.real_name];
3968
3969                 if (snap_name.length() == 0) {
3970                         return;
3971                 }
3972                 
3973                 if (session->snap_name() == snap_name) {
3974                         return;
3975                 }
3976                 
3977                 ARDOUR_UI::instance()->load_session(session->path(), string (snap_name));
3978         }
3979 }
3980
3981 bool
3982 Editor::snapshot_display_button_press (GdkEventButton* ev)
3983 {
3984          return false;
3985 }
3986
3987 void
3988 Editor::redisplay_snapshots ()
3989 {
3990         if (session == 0) {
3991                 return;
3992         }
3993
3994         vector<string*>* states;
3995
3996         if ((states = session->possible_states()) == 0) {
3997                 return;
3998         }
3999
4000         snapshot_display_model->clear ();
4001
4002         for (vector<string*>::iterator i = states->begin(); i != states->end(); ++i) {
4003                 string statename = *(*i);
4004                 TreeModel::Row row = *(snapshot_display_model->append());
4005                 row[snapshot_display_columns.visible_name] = statename;
4006                 row[snapshot_display_columns.real_name] = statename;
4007         }
4008
4009         delete states;
4010 }
4011
4012 void
4013 Editor::session_state_saved (string snap_name)
4014 {
4015         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::session_state_saved), snap_name));
4016         redisplay_snapshots ();
4017 }
4018
4019 void
4020 Editor::maximise_editing_space ()
4021 {
4022         mouse_mode_tearoff->set_visible (false);
4023         tools_tearoff->set_visible (false);
4024
4025         pre_maximal_pane_position = edit_pane.get_position();
4026         edit_pane.set_position (edit_pane.get_width());
4027
4028         fullscreen();
4029 }
4030
4031 void
4032 Editor::restore_editing_space ()
4033 {
4034         mouse_mode_tearoff->set_visible (true);
4035         tools_tearoff->set_visible (true);
4036
4037         edit_pane.set_position (pre_maximal_pane_position);
4038
4039         unfullscreen();
4040 }
4041
4042 void 
4043 Editor::new_playlists ()
4044 {
4045         begin_reversible_command (_("new playlists"));
4046         mapover_audio_tracks (mem_fun (*this, &Editor::mapped_use_new_playlist));
4047         commit_reversible_command ();
4048 }
4049
4050 void
4051 Editor::copy_playlists ()
4052 {
4053         begin_reversible_command (_("copy playlists"));
4054         mapover_audio_tracks (mem_fun (*this, &Editor::mapped_use_copy_playlist));
4055         commit_reversible_command ();
4056 }
4057
4058 void 
4059 Editor::clear_playlists ()
4060 {
4061         begin_reversible_command (_("clear playlists"));
4062         mapover_audio_tracks (mem_fun (*this, &Editor::mapped_clear_playlist));
4063         commit_reversible_command ();
4064 }
4065
4066 void 
4067 Editor::mapped_use_new_playlist (AudioTimeAxisView& atv, uint32_t sz)
4068 {
4069         atv.use_new_playlist (sz > 1 ? false : true);
4070 }
4071
4072 void
4073 Editor::mapped_use_copy_playlist (AudioTimeAxisView& atv, uint32_t sz)
4074 {
4075         atv.use_copy_playlist (sz > 1 ? false : true);
4076 }
4077
4078 void 
4079 Editor::mapped_clear_playlist (AudioTimeAxisView& atv, uint32_t sz)
4080 {
4081         atv.clear_playlist ();
4082 }
4083
4084 bool
4085 Editor::on_key_press_event (GdkEventKey* ev)
4086 {
4087         return key_press_focus_accelerator_handler (*this, ev);
4088 }
4089