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