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