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