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