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