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