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