e56acc01148b82cec85f81f7b049363c0c8a5128
[ardour.git] / gtk2_ardour / editor.cc
1 /*
2     Copyright (C) 2000-2007 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/enumwriter.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 ("mixer-width"))) {
2046                 editor_mixer_strip_width = Width (string_2_enum (prop->value(), editor_mixer_strip_width));
2047         }
2048
2049         if ((prop = node.property ("zoom-focus"))) {
2050                 set_zoom_focus ((ZoomFocus) atoi (prop->value()));
2051         }
2052
2053         if ((prop = node.property ("zoom"))) {
2054                 reset_zoom (PBD::atof (prop->value()));
2055         }
2056
2057         if ((prop = node.property ("snap-to"))) {
2058                 set_snap_to ((SnapType) atoi (prop->value()));
2059         }
2060
2061         if ((prop = node.property ("snap-mode"))) {
2062                 set_snap_mode ((SnapMode) atoi (prop->value()));
2063         }
2064
2065         if ((prop = node.property ("mouse-mode"))) {
2066                 MouseMode m = str2mousemode(prop->value());
2067                 mouse_mode = MouseMode ((int) m + 1); /* lie, force mode switch */
2068                 set_mouse_mode (m, true);
2069         } else {
2070                 mouse_mode = MouseGain; /* lie, to force the mode switch */
2071                 set_mouse_mode (MouseObject, true);
2072         }
2073
2074         if ((prop = node.property ("show-waveforms"))) {
2075                 bool yn = (prop->value() == "yes");
2076                 _show_waveforms = !yn;
2077                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleWaveformVisibility"));
2078                 if (act) {
2079                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2080                         /* do it twice to force the change */
2081                         tact->set_active (!yn);
2082                         tact->set_active (yn);
2083                 }
2084         }
2085
2086         if ((prop = node.property ("show-waveforms-recording"))) {
2087                 bool yn = (prop->value() == "yes");
2088                 _show_waveforms_recording = !yn;
2089                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleWaveformsWhileRecording"));
2090                 if (act) {
2091                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2092                         /* do it twice to force the change */
2093                         tact->set_active (!yn);
2094                         tact->set_active (yn);
2095                 }
2096         }
2097         
2098         if ((prop = node.property ("show-measures"))) {
2099                 bool yn = (prop->value() == "yes");
2100                 _show_measures = !yn;
2101                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleMeasureVisibility"));
2102                 if (act) {
2103                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2104                         /* do it twice to force the change */
2105                         tact->set_active (!yn);
2106                         tact->set_active (yn);
2107                 }
2108         }
2109
2110         if ((prop = node.property ("follow-playhead"))) {
2111                 bool yn = (prop->value() == "yes");
2112                 set_follow_playhead (yn);
2113                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
2114                 if (act) {
2115                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2116                         if (tact->get_active() != yn) {
2117                                 tact->set_active (yn);
2118                         }
2119                 }
2120         }
2121
2122         if ((prop = node.property ("region-list-sort-type"))) {
2123                 region_list_sort_type = (Editing::RegionListSortType) -1; // force change 
2124                 reset_region_list_sort_type(str2regionlistsorttype(prop->value()));
2125         }
2126
2127         if ((prop = node.property ("xfades-visible"))) {
2128                 bool yn = (prop->value() == "yes");
2129                 _xfade_visibility = !yn;
2130                 // set_xfade_visibility (yn);
2131         }
2132
2133         if ((prop = node.property ("show-editor-mixer"))) {
2134
2135                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2136                 if (act) {
2137
2138                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2139                         bool yn = (prop->value() == X_("yes"));
2140
2141                         /* do it twice to force the change */
2142                         
2143                         tact->set_active (!yn);
2144                         tact->set_active (yn);
2145                 }
2146         }
2147
2148
2149         return 0;
2150 }
2151
2152 XMLNode&
2153 Editor::get_state ()
2154 {
2155         XMLNode* node = new XMLNode ("Editor");
2156         char buf[32];
2157
2158         _id.print (buf, sizeof (buf));
2159         node->add_property ("id", buf);
2160         
2161         if (is_realized()) {
2162                 Glib::RefPtr<Gdk::Window> win = get_window();
2163                 
2164                 int x, y, xoff, yoff, width, height;
2165                 win->get_root_origin(x, y);
2166                 win->get_position(xoff, yoff);
2167                 win->get_size(width, height);
2168                 
2169                 XMLNode* geometry = new XMLNode ("geometry");
2170
2171                 snprintf(buf, sizeof(buf), "%d", width);
2172                 geometry->add_property("x_size", string(buf));
2173                 snprintf(buf, sizeof(buf), "%d", height);
2174                 geometry->add_property("y_size", string(buf));
2175                 snprintf(buf, sizeof(buf), "%d", x);
2176                 geometry->add_property("x_pos", string(buf));
2177                 snprintf(buf, sizeof(buf), "%d", y);
2178                 geometry->add_property("y_pos", string(buf));
2179                 snprintf(buf, sizeof(buf), "%d", xoff);
2180                 geometry->add_property("x_off", string(buf));
2181                 snprintf(buf, sizeof(buf), "%d", yoff);
2182                 geometry->add_property("y_off", string(buf));
2183                 snprintf(buf,sizeof(buf), "%d",gtk_paned_get_position (static_cast<Paned*>(&edit_pane)->gobj()));
2184                 geometry->add_property("edit_pane_pos", string(buf));
2185
2186                 node->add_child_nocopy (*geometry);
2187         }
2188
2189         maybe_add_mixer_strip_width (*node);
2190         
2191         snprintf (buf, sizeof(buf), "%d", (int) zoom_focus);
2192         node->add_property ("zoom-focus", buf);
2193         snprintf (buf, sizeof(buf), "%f", frames_per_unit);
2194         node->add_property ("zoom", buf);
2195         snprintf (buf, sizeof(buf), "%d", (int) snap_type);
2196         node->add_property ("snap-to", buf);
2197         snprintf (buf, sizeof(buf), "%d", (int) snap_mode);
2198         node->add_property ("snap-mode", buf);
2199
2200         snprintf (buf, sizeof (buf), "%" PRIu32, playhead_cursor->current_frame);
2201         node->add_property ("playhead", buf);
2202         snprintf (buf, sizeof (buf), "%" PRIu32, edit_cursor->current_frame);
2203         node->add_property ("edit-cursor", buf);
2204
2205         node->add_property ("show-waveforms", _show_waveforms ? "yes" : "no");
2206         node->add_property ("show-waveforms-recording", _show_waveforms_recording ? "yes" : "no");
2207         node->add_property ("show-measures", _show_measures ? "yes" : "no");
2208         node->add_property ("follow-playhead", _follow_playhead ? "yes" : "no");
2209         node->add_property ("xfades-visible", _xfade_visibility ? "yes" : "no");
2210         node->add_property ("region-list-sort-type", enum2str(region_list_sort_type));
2211         node->add_property ("mouse-mode", enum2str(mouse_mode));
2212         
2213         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2214         if (act) {
2215                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2216                 node->add_property (X_("show-editor-mixer"), tact->get_active() ? "yes" : "no");
2217         }
2218
2219         return *node;
2220 }
2221
2222
2223
2224 TimeAxisView *
2225 Editor::trackview_by_y_position (double y)
2226 {
2227         for (TrackViewList::iterator iter = track_views.begin(); iter != track_views.end(); ++iter) {
2228
2229                 TimeAxisView *tv;
2230
2231                 if ((tv = (*iter)->covers_y_position (y)) != 0) {
2232                         return tv;
2233                 }
2234         }
2235
2236         return 0;
2237 }
2238
2239 void
2240 Editor::snap_to (nframes_t& start, int32_t direction, bool for_mark)
2241 {
2242         Location* before = 0;
2243         Location* after = 0;
2244
2245         if (!session) {
2246                 return;
2247         }
2248
2249         const nframes_t one_second = session->frame_rate();
2250         const nframes_t one_minute = session->frame_rate() * 60;
2251         const nframes_t one_smpte_second = (nframes_t)(rint(session->smpte_frames_per_second()) * session->frames_per_smpte_frame());
2252         nframes_t one_smpte_minute = (nframes_t)(rint(session->smpte_frames_per_second()) * session->frames_per_smpte_frame() * 60);
2253         nframes_t presnap = start;
2254
2255         switch (snap_type) {
2256         case SnapToFrame:
2257                 break;
2258
2259         case SnapToCDFrame:
2260                 if (direction) {
2261                         start = (nframes_t) ceil ((double) start / (one_second / 75)) * (one_second / 75);
2262                 } else {
2263                         start = (nframes_t) floor ((double) start / (one_second / 75)) * (one_second / 75);
2264                 }
2265                 break;
2266
2267         case SnapToSMPTEFrame:
2268                 if (fmod((double)start, (double)session->frames_per_smpte_frame()) > (session->frames_per_smpte_frame() / 2)) {
2269                         start = (nframes_t) (ceil ((double) start / session->frames_per_smpte_frame()) * session->frames_per_smpte_frame());
2270                 } else {
2271                         start = (nframes_t) (floor ((double) start / session->frames_per_smpte_frame()) *  session->frames_per_smpte_frame());
2272                 }
2273                 break;
2274
2275         case SnapToSMPTESeconds:
2276                 if (session->smpte_offset_negative())
2277                 {
2278                         start += session->smpte_offset ();
2279                 } else {
2280                         start -= session->smpte_offset ();
2281                 }    
2282                 if (start % one_smpte_second > one_smpte_second / 2) {
2283                         start = (nframes_t) ceil ((double) start / one_smpte_second) * one_smpte_second;
2284                 } else {
2285                         start = (nframes_t) floor ((double) start / one_smpte_second) * one_smpte_second;
2286                 }
2287                 
2288                 if (session->smpte_offset_negative())
2289                 {
2290                         start -= session->smpte_offset ();
2291                 } else {
2292                         start += session->smpte_offset ();
2293                 }
2294                 break;
2295                 
2296         case SnapToSMPTEMinutes:
2297                 if (session->smpte_offset_negative())
2298                 {
2299                         start += session->smpte_offset ();
2300                 } else {
2301                         start -= session->smpte_offset ();
2302                 }
2303                 if (start % one_smpte_minute > one_smpte_minute / 2) {
2304                         start = (nframes_t) ceil ((double) start / one_smpte_minute) * one_smpte_minute;
2305                 } else {
2306                         start = (nframes_t) floor ((double) start / one_smpte_minute) * one_smpte_minute;
2307                 }
2308                 if (session->smpte_offset_negative())
2309                 {
2310                         start -= session->smpte_offset ();
2311                 } else {
2312                         start += session->smpte_offset ();
2313                 }
2314                 break;
2315                 
2316         case SnapToSeconds:
2317                 if (start % one_second > one_second / 2) {
2318                         start = (nframes_t) ceil ((double) start / one_second) * one_second;
2319                 } else {
2320                         start = (nframes_t) floor ((double) start / one_second) * one_second;
2321                 }
2322                 break;
2323                 
2324         case SnapToMinutes:
2325                 if (start % one_minute > one_minute / 2) {
2326                         start = (nframes_t) ceil ((double) start / one_minute) * one_minute;
2327                 } else {
2328                         start = (nframes_t) floor ((double) start / one_minute) * one_minute;
2329                 }
2330                 break;
2331
2332         case SnapToBar:
2333                 start = session->tempo_map().round_to_bar (start, direction);
2334                 break;
2335
2336         case SnapToBeat:
2337                 start = session->tempo_map().round_to_beat (start, direction);
2338                 break;
2339
2340         case SnapToAThirtysecondBeat:
2341                 start = session->tempo_map().round_to_beat_subdivision (start, 32);
2342                 break;
2343
2344         case SnapToASixteenthBeat:
2345                 start = session->tempo_map().round_to_beat_subdivision (start, 16);
2346                 break;
2347
2348         case SnapToAEighthBeat:
2349                 start = session->tempo_map().round_to_beat_subdivision (start, 8);
2350                 break;
2351
2352         case SnapToAQuarterBeat:
2353                 start = session->tempo_map().round_to_beat_subdivision (start, 4);
2354                 break;
2355
2356         case SnapToAThirdBeat:
2357                 start = session->tempo_map().round_to_beat_subdivision (start, 3);
2358                 break;
2359
2360         case SnapToEditCursor:
2361                 start = edit_cursor->current_frame;
2362                 break;
2363
2364         case SnapToMark:
2365                 if (for_mark) {
2366                         return;
2367                 }
2368
2369                 before = session->locations()->first_location_before (start);
2370                 after = session->locations()->first_location_after (start);
2371
2372                 if (direction < 0) {
2373                         if (before) {
2374                                 start = before->start();
2375                         } else {
2376                                 start = 0;
2377                         }
2378                 } else if (direction > 0) {
2379                         if (after) {
2380                                 start = after->start();
2381                         } else {
2382                                 start = session->current_end_frame();
2383                         }
2384                 } else {
2385                         if (before) {
2386                                 if (after) {
2387                                         /* find nearest of the two */
2388                                         if ((start - before->start()) < (after->start() - start)) {
2389                                                 start = before->start();
2390                                         } else {
2391                                                 start = after->start();
2392                                         }
2393                                 } else {
2394                                         start = before->start();
2395                                 }
2396                         } else if (after) {
2397                                 start = after->start();
2398                         } else {
2399                                 /* relax */
2400                         }
2401                 }
2402                 break;
2403
2404         case SnapToRegionStart:
2405         case SnapToRegionEnd:
2406         case SnapToRegionSync:
2407         case SnapToRegionBoundary:
2408                 if (!region_boundary_cache.empty()) {
2409                         vector<nframes_t>::iterator i;
2410
2411                         if (direction > 0) {
2412                                 i = std::upper_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2413                         } else {
2414                                 i = std::lower_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2415                         }
2416                         
2417                         if (i != region_boundary_cache.end()) {
2418                                 start = *i;
2419                         } else {
2420                                 start = region_boundary_cache.back();
2421                         }
2422                 }
2423                 break;
2424         }
2425
2426         switch (snap_mode) {
2427         case SnapNormal:
2428                 return;                 
2429                 
2430         case SnapMagnetic:
2431                 
2432                 if (presnap > start) {
2433                         if (presnap > (start + unit_to_frame(snap_threshold))) {
2434                                 start = presnap;
2435                         }
2436                         
2437                 } else if (presnap < start) {
2438                         if (presnap < (start - unit_to_frame(snap_threshold))) {
2439                                 start = presnap;
2440                         }
2441                 }
2442                 
2443         default:
2444                 return;
2445                 
2446         }
2447 }
2448
2449 void
2450 Editor::setup_toolbar ()
2451 {
2452         string pixmap_path;
2453
2454         const guint32 FUDGE = 18; // Combo's are stupid - they steal space from the entry for the button
2455
2456
2457         /* Mode Buttons (tool selection) */
2458
2459         vector<ToggleButton *> mouse_mode_buttons;
2460
2461         mouse_move_button.add (*(manage (new Image (::get_icon("tool_object")))));
2462         mouse_move_button.set_relief(Gtk::RELIEF_NONE);
2463         mouse_mode_buttons.push_back (&mouse_move_button);
2464         mouse_select_button.add (*(manage (new Image (get_xpm("tool_range.xpm")))));
2465         mouse_select_button.set_relief(Gtk::RELIEF_NONE);
2466         mouse_mode_buttons.push_back (&mouse_select_button);
2467         mouse_gain_button.add (*(manage (new Image (::get_icon("tool_gain")))));
2468         mouse_gain_button.set_relief(Gtk::RELIEF_NONE);
2469         mouse_mode_buttons.push_back (&mouse_gain_button);
2470         mouse_zoom_button.add (*(manage (new Image (::get_icon("tool_zoom")))));
2471         mouse_zoom_button.set_relief(Gtk::RELIEF_NONE);
2472         mouse_mode_buttons.push_back (&mouse_zoom_button);
2473         mouse_timefx_button.add (*(manage (new Image (::get_icon("tool_stretch")))));
2474         mouse_timefx_button.set_relief(Gtk::RELIEF_NONE);
2475         mouse_mode_buttons.push_back (&mouse_timefx_button);
2476         mouse_audition_button.add (*(manage (new Image (::get_icon("tool_audition")))));
2477         mouse_audition_button.set_relief(Gtk::RELIEF_NONE);
2478         mouse_mode_buttons.push_back (&mouse_audition_button);
2479         
2480         mouse_mode_button_set = new GroupedButtons (mouse_mode_buttons);
2481
2482         HBox* mode_box = manage(new HBox);
2483         mode_box->set_border_width (2);
2484         mode_box->set_spacing(4);
2485         mouse_mode_button_box.set_spacing(1);
2486         mouse_mode_button_box.pack_start(mouse_move_button, true, true);
2487         mouse_mode_button_box.pack_start(mouse_select_button, true, true);
2488         mouse_mode_button_box.pack_start(mouse_zoom_button, true, true);
2489         mouse_mode_button_box.pack_start(mouse_gain_button, true, true);
2490         mouse_mode_button_box.pack_start(mouse_timefx_button, true, true);
2491         mouse_mode_button_box.pack_start(mouse_audition_button, true, true);
2492         mouse_mode_button_box.set_homogeneous(true);
2493
2494         vector<string> edit_mode_strings;
2495         edit_mode_strings.push_back (edit_mode_to_string (Splice));
2496         edit_mode_strings.push_back (edit_mode_to_string (Slide));
2497
2498         edit_mode_selector.set_name ("EditModeSelector");
2499         Gtkmm2ext::set_size_request_to_display_given_text (edit_mode_selector, longest (edit_mode_strings).c_str(), 2+FUDGE, 10);
2500         set_popdown_strings (edit_mode_selector, edit_mode_strings);
2501         edit_mode_selector.signal_changed().connect (mem_fun(*this, &Editor::edit_mode_selection_done));
2502
2503         mode_box->pack_start(edit_mode_selector);
2504         mode_box->pack_start(mouse_mode_button_box);
2505         
2506         mouse_mode_tearoff = manage (new TearOff (*mode_box));
2507         mouse_mode_tearoff->set_name ("MouseModeBase");
2508
2509         mouse_mode_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2510                                                   &mouse_mode_tearoff->tearoff_window()));
2511         mouse_mode_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2512                                                   &mouse_mode_tearoff->tearoff_window(), 1));
2513         mouse_mode_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2514                                                   &mouse_mode_tearoff->tearoff_window()));
2515         mouse_mode_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2516                                                    &mouse_mode_tearoff->tearoff_window(), 1));
2517
2518         mouse_move_button.set_name ("MouseModeButton");
2519         mouse_select_button.set_name ("MouseModeButton");
2520         mouse_gain_button.set_name ("MouseModeButton");
2521         mouse_zoom_button.set_name ("MouseModeButton");
2522         mouse_timefx_button.set_name ("MouseModeButton");
2523         mouse_audition_button.set_name ("MouseModeButton");
2524
2525         ARDOUR_UI::instance()->tooltips().set_tip (mouse_move_button, _("Select/Move Objects"));
2526         ARDOUR_UI::instance()->tooltips().set_tip (mouse_select_button, _("Select/Move Ranges"));
2527         ARDOUR_UI::instance()->tooltips().set_tip (mouse_gain_button, _("Draw Gain Automation"));
2528         ARDOUR_UI::instance()->tooltips().set_tip (mouse_zoom_button, _("Select Zoom Range"));
2529         ARDOUR_UI::instance()->tooltips().set_tip (mouse_timefx_button, _("Stretch/Shrink Regions"));
2530         ARDOUR_UI::instance()->tooltips().set_tip (mouse_audition_button, _("Listen to Specific Regions"));
2531
2532         mouse_move_button.unset_flags (CAN_FOCUS);
2533         mouse_select_button.unset_flags (CAN_FOCUS);
2534         mouse_gain_button.unset_flags (CAN_FOCUS);
2535         mouse_zoom_button.unset_flags (CAN_FOCUS);
2536         mouse_timefx_button.unset_flags (CAN_FOCUS);
2537         mouse_audition_button.unset_flags (CAN_FOCUS);
2538
2539         mouse_select_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseRange));
2540         mouse_select_button.signal_button_release_event().connect (mem_fun(*this, &Editor::mouse_select_button_release));
2541
2542         mouse_move_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseObject));
2543         mouse_gain_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseGain));
2544         mouse_zoom_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseZoom));
2545         mouse_timefx_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseTimeFX));
2546         mouse_audition_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseAudition));
2547
2548         // mouse_move_button.set_active (true);
2549         
2550
2551         /* Zoom */
2552         
2553         zoom_box.set_spacing (1);
2554         zoom_box.set_border_width (2);
2555
2556         zoom_in_button.set_name ("EditorTimeButton");
2557         zoom_in_button.set_size_request(-1,16);
2558         zoom_in_button.add (*(manage (new Image (::get_icon("zoom_in")))));
2559         zoom_in_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::temporal_zoom_step), false));
2560         ARDOUR_UI::instance()->tooltips().set_tip (zoom_in_button, _("Zoom In"));
2561         
2562         zoom_out_button.set_name ("EditorTimeButton");
2563         zoom_out_button.set_size_request(-1,16);
2564         zoom_out_button.add (*(manage (new Image (::get_icon("zoom_out")))));
2565         zoom_out_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::temporal_zoom_step), true));
2566         ARDOUR_UI::instance()->tooltips().set_tip (zoom_out_button, _("Zoom Out"));
2567
2568         zoom_out_full_button.set_name ("EditorTimeButton");
2569         zoom_out_full_button.set_size_request(-1,16);
2570         zoom_out_full_button.add (*(manage (new Image (::get_icon("zoom_full")))));
2571         zoom_out_full_button.signal_clicked().connect (mem_fun(*this, &Editor::temporal_zoom_session));
2572         ARDOUR_UI::instance()->tooltips().set_tip (zoom_out_full_button, _("Zoom to Session"));
2573
2574         zoom_focus_selector.set_name ("ZoomFocusSelector");
2575         Gtkmm2ext::set_size_request_to_display_given_text (zoom_focus_selector, "Edit Cursor", FUDGE, 0);
2576         set_popdown_strings (zoom_focus_selector, zoom_focus_strings);
2577         zoom_focus_selector.signal_changed().connect (mem_fun(*this, &Editor::zoom_focus_selection_done));
2578         ARDOUR_UI::instance()->tooltips().set_tip (zoom_focus_selector, _("Zoom focus"));
2579
2580         zoom_box.pack_start (zoom_focus_selector, true, true);
2581         zoom_box.pack_start (zoom_out_button, false, false);
2582         zoom_box.pack_start (zoom_in_button, false, false);
2583         zoom_box.pack_start (zoom_out_full_button, false, false);
2584
2585         /* Edit Cursor / Snap */
2586
2587         snap_box.set_spacing (1);
2588         snap_box.set_border_width (2);
2589
2590         snap_type_selector.set_name ("SnapTypeSelector");
2591         Gtkmm2ext::set_size_request_to_display_given_text (snap_type_selector, "SMPTE Seconds", 2+FUDGE, 10);
2592         set_popdown_strings (snap_type_selector, snap_type_strings);
2593         snap_type_selector.signal_changed().connect (mem_fun(*this, &Editor::snap_type_selection_done));
2594         ARDOUR_UI::instance()->tooltips().set_tip (snap_type_selector, _("Unit to snap cursors and ranges to"));
2595
2596         snap_mode_selector.set_name ("SnapModeSelector");
2597         Gtkmm2ext::set_size_request_to_display_given_text (snap_mode_selector, "Magnetic Snap", 2+FUDGE, 10);
2598         set_popdown_strings (snap_mode_selector, snap_mode_strings);
2599         snap_mode_selector.signal_changed().connect (mem_fun(*this, &Editor::snap_mode_selection_done));
2600
2601         snap_box.pack_start (edit_cursor_clock, false, false);
2602         snap_box.pack_start (snap_mode_selector, false, false);
2603         snap_box.pack_start (snap_type_selector, false, false);
2604
2605
2606         /* Nudge */
2607
2608         HBox *nudge_box = manage (new HBox);
2609         nudge_box->set_spacing(1);
2610         nudge_box->set_border_width (2);
2611
2612         nudge_forward_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::nudge_forward), false));
2613         nudge_backward_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::nudge_backward), false));
2614
2615         nudge_box->pack_start (nudge_backward_button, false, false);
2616         nudge_box->pack_start (nudge_forward_button, false, false);
2617         nudge_box->pack_start (nudge_clock, false, false);
2618
2619
2620         /* Pack everything in... */
2621
2622         HBox* hbox = new HBox;
2623         hbox->set_spacing(10);
2624
2625         tools_tearoff = new TearOff (*hbox);
2626         tools_tearoff->set_name ("MouseModeBase");
2627
2628         tools_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2629                                              &tools_tearoff->tearoff_window()));
2630         tools_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2631                                              &tools_tearoff->tearoff_window(), 0));
2632         tools_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2633                                              &tools_tearoff->tearoff_window()));
2634         tools_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2635                                               &tools_tearoff->tearoff_window(), 0));
2636
2637         toolbar_hbox.set_spacing (10);
2638         toolbar_hbox.set_border_width (1);
2639
2640         toolbar_hbox.pack_start (*mouse_mode_tearoff, false, false);
2641         toolbar_hbox.pack_start (*tools_tearoff, false, false);
2642
2643         
2644         hbox->pack_start (snap_box, false, false);
2645         // hbox->pack_start (zoom_box, false, false); 
2646         hbox->pack_start (*nudge_box, false, false);
2647
2648         hbox->show_all ();
2649         
2650         toolbar_base.set_name ("ToolBarBase");
2651         toolbar_base.add (toolbar_hbox);
2652
2653         toolbar_frame.set_shadow_type (SHADOW_OUT);
2654         toolbar_frame.set_name ("BaseFrame");
2655         toolbar_frame.add (toolbar_base);
2656 }
2657
2658 int
2659 Editor::convert_drop_to_paths (vector<ustring>& paths, 
2660                                const RefPtr<Gdk::DragContext>& context,
2661                                gint                x,
2662                                gint                y,
2663                                const SelectionData& data,
2664                                guint               info,
2665                                guint               time)                               
2666
2667 {       
2668         if (session == 0) {
2669                 return -1;
2670         }
2671
2672         vector<ustring> uris = data.get_uris();
2673
2674         if (uris.empty()) {
2675                 
2676                 /* This is seriously fucked up. Nautilus doesn't say that its URI lists
2677                    are actually URI lists. So do it by hand.
2678                 */
2679
2680                 if (data.get_target() != "text/plain") {
2681                         return -1;
2682                 }
2683   
2684                 /* Parse the "uri-list" format that Nautilus provides, 
2685                    where each pathname is delimited by \r\n
2686                 */
2687         
2688                 const char* p = data.get_text().c_str();
2689                 const char* q;
2690
2691                 while (p)
2692                 {
2693                         if (*p != '#')
2694                         {
2695                                 while (g_ascii_isspace (*p))
2696                                         p++;
2697                                 
2698                                 q = p;
2699                                 while (*q && (*q != '\n') && (*q != '\r'))
2700                                         q++;
2701                                 
2702                                 if (q > p)
2703                                 {
2704                                         q--;
2705                                         while (q > p && g_ascii_isspace (*q))
2706                                                 q--;
2707                                         
2708                                         if (q > p)
2709                                         {
2710                                                 uris.push_back (ustring (p, q - p + 1));
2711                                         }
2712                                 }
2713                         }
2714                         p = strchr (p, '\n');
2715                         if (p)
2716                                 p++;
2717                 }
2718
2719                 if (uris.empty()) {
2720                         return -1;
2721                 }
2722         }
2723         
2724         for (vector<ustring>::iterator i = uris.begin(); i != uris.end(); ++i) {
2725                 if ((*i).substr (0,7) == "file://") {
2726                         string p = *i;
2727                         PBD::url_decode (p);
2728                         paths.push_back (p.substr (7));
2729                 }
2730         }
2731
2732         return 0;
2733 }
2734
2735 void
2736 Editor::new_tempo_section ()
2737
2738 {
2739 }
2740
2741 void
2742 Editor::map_transport_state ()
2743 {
2744         ENSURE_GUI_THREAD (mem_fun(*this, &Editor::map_transport_state));
2745
2746         if (session->transport_stopped()) {
2747                 have_pending_keyboard_selection = false;
2748         }
2749
2750         update_loop_range_view (true);
2751 }
2752
2753 /* UNDO/REDO */
2754
2755 Editor::State::State ()
2756 {
2757         selection = new Selection;
2758 }
2759
2760 Editor::State::~State ()
2761 {
2762         delete selection;
2763 }
2764
2765 UndoAction
2766 Editor::get_memento () const
2767 {
2768         State *state = new State;
2769
2770         store_state (*state);
2771         return bind (mem_fun (*(const_cast<Editor*>(this)), &Editor::restore_state), state);
2772 }
2773
2774 void
2775 Editor::store_state (State& state) const
2776 {
2777         *state.selection = *selection;
2778 }
2779
2780 void
2781 Editor::restore_state (State *state)
2782 {
2783         if (*selection == *state->selection) {
2784                 return;
2785         }
2786
2787         *selection = *state->selection;
2788         time_selection_changed ();
2789         region_selection_changed ();   
2790
2791         /* XXX other selection change handlers? */
2792 }
2793
2794 void
2795 Editor::begin_reversible_command (string name)
2796 {
2797         if (session) {
2798                 before = &get_state();
2799                 session->begin_reversible_command (name);
2800         }
2801 }
2802
2803 void
2804 Editor::commit_reversible_command ()
2805 {
2806         if (session) {
2807                 session->commit_reversible_command (new MementoCommand<Editor>(*this, before, &get_state()));
2808         }
2809 }
2810
2811 void
2812 Editor::set_edit_group_solo (Route& route, bool yn)
2813 {
2814         RouteGroup *edit_group;
2815
2816         if ((edit_group = route.edit_group()) != 0) {
2817                 edit_group->apply (&Route::set_solo, yn, this);
2818         } else {
2819                 route.set_solo (yn, this);
2820         }
2821 }
2822
2823 void
2824 Editor::set_edit_group_mute (Route& route, bool yn)
2825 {
2826         RouteGroup *edit_group = 0;
2827
2828         if ((edit_group == route.edit_group()) != 0) {
2829                 edit_group->apply (&Route::set_mute, yn, this);
2830         } else {
2831                 route.set_mute (yn, this);
2832         }
2833 }
2834                 
2835 void
2836 Editor::history_changed ()
2837 {
2838         string label;
2839
2840         if (undo_action && session) {
2841                 if (session->undo_depth() == 0) {
2842                         label = _("Undo");
2843                 } else {
2844                         label = string_compose(_("Undo (%1)"), session->next_undo());
2845                 }
2846                 undo_action->property_label() = label;
2847         }
2848
2849         if (redo_action && session) {
2850                 if (session->redo_depth() == 0) {
2851                         label = _("Redo");
2852                 } else {
2853                         label = string_compose(_("Redo (%1)"), session->next_redo());
2854                 }
2855                 redo_action->property_label() = label;
2856         }
2857 }
2858
2859 void
2860 Editor::duplicate_dialog (bool dup_region)
2861 {
2862         if (selection->regions.empty() && (selection->time.length() == 0)) {
2863                 return;
2864         }
2865
2866         ArdourDialog win ("duplicate dialog");
2867         Label  label (_("Duplicate how many times?"));
2868         Adjustment adjustment (1.0, 1.0, 1000000.0, 1.0, 5.0);
2869         SpinButton spinner (adjustment);
2870
2871         win.get_vbox()->set_spacing (12);
2872         win.get_vbox()->pack_start (label);
2873
2874         /* dialogs have ::add_action_widget() but that puts the spinner in the wrong
2875            place, visually. so do this by hand.
2876         */
2877
2878         win.get_vbox()->pack_start (spinner);
2879         spinner.signal_activate().connect (sigc::bind (mem_fun (win, &ArdourDialog::response), RESPONSE_ACCEPT));
2880
2881         label.show ();
2882         spinner.show ();
2883
2884         win.add_button (Stock::OK, RESPONSE_ACCEPT);
2885         win.add_button (Stock::CANCEL, RESPONSE_CANCEL);
2886
2887         win.set_position (WIN_POS_MOUSE);
2888
2889         spinner.grab_focus ();
2890
2891         switch (win.run ()) {
2892         case RESPONSE_ACCEPT:
2893                 break;
2894         default:
2895                 return;
2896         }
2897
2898         float times = adjustment.get_value();
2899
2900         if (!selection->regions.empty()) {
2901                 duplicate_some_regions (selection->regions, times);
2902         } else {
2903                 duplicate_selection (times);
2904         }
2905 }
2906
2907 void
2908 Editor::show_verbose_canvas_cursor ()
2909 {
2910         verbose_canvas_cursor->raise_to_top();
2911         verbose_canvas_cursor->show();
2912         verbose_cursor_visible = true;
2913 }
2914
2915 void
2916 Editor::hide_verbose_canvas_cursor ()
2917 {
2918         verbose_canvas_cursor->hide();
2919         verbose_cursor_visible = false;
2920 }
2921
2922 void
2923 Editor::set_verbose_canvas_cursor (const string & txt, double x, double y)
2924 {
2925         /* XXX get origin of canvas relative to root window,
2926            add x and y and check compared to gdk_screen_{width,height}
2927         */
2928         verbose_canvas_cursor->property_text() = txt.c_str();
2929         verbose_canvas_cursor->property_x() = x;
2930         verbose_canvas_cursor->property_y() = y;
2931 }
2932
2933 void
2934 Editor::set_verbose_canvas_cursor_text (const string & txt)
2935 {
2936         verbose_canvas_cursor->property_text() = txt.c_str();
2937 }
2938
2939 void
2940 Editor::edit_mode_selection_done ()
2941 {
2942         if (session == 0) {
2943                 return;
2944         }
2945
2946         string choice = edit_mode_selector.get_active_text();
2947         EditMode mode = Slide;
2948
2949         if (choice == _("Splice Edit")) {
2950                 mode = Splice;
2951         } else if (choice == _("Slide Edit")) {
2952                 mode = Slide;
2953         }
2954
2955         Config->set_edit_mode (mode);
2956 }       
2957
2958 void
2959 Editor::snap_type_selection_done ()
2960 {
2961         string choice = snap_type_selector.get_active_text();
2962         SnapType snaptype = SnapToFrame;
2963
2964         if (choice == _("Beats/3")) {
2965                 snaptype = SnapToAThirdBeat;
2966         } else if (choice == _("Beats/4")) {
2967                 snaptype = SnapToAQuarterBeat;
2968         } else if (choice == _("Beats/8")) {
2969                 snaptype = SnapToAEighthBeat;
2970         } else if (choice == _("Beats/16")) {
2971                 snaptype = SnapToASixteenthBeat;
2972         } else if (choice == _("Beats/32")) {
2973                 snaptype = SnapToAThirtysecondBeat;
2974         } else if (choice == _("Beats")) {
2975                 snaptype = SnapToBeat;
2976         } else if (choice == _("Bars")) {
2977                 snaptype = SnapToBar;
2978         } else if (choice == _("Marks")) {
2979                 snaptype = SnapToMark;
2980         } else if (choice == _("Edit Cursor")) {
2981                 snaptype = SnapToEditCursor;
2982         } else if (choice == _("Region starts")) {
2983                 snaptype = SnapToRegionStart;
2984         } else if (choice == _("Region ends")) {
2985                 snaptype = SnapToRegionEnd;
2986         } else if (choice == _("Region bounds")) {
2987                 snaptype = SnapToRegionBoundary;
2988         } else if (choice == _("Region syncs")) {
2989                 snaptype = SnapToRegionSync;
2990         } else if (choice == _("CD Frames")) {
2991                 snaptype = SnapToCDFrame;
2992         } else if (choice == _("SMPTE Frames")) {
2993                 snaptype = SnapToSMPTEFrame;
2994         } else if (choice == _("SMPTE Seconds")) {
2995                 snaptype = SnapToSMPTESeconds;
2996         } else if (choice == _("SMPTE Minutes")) {
2997                 snaptype = SnapToSMPTEMinutes;
2998         } else if (choice == _("Seconds")) {
2999                 snaptype = SnapToSeconds;
3000         } else if (choice == _("Minutes")) {
3001                 snaptype = SnapToMinutes;
3002         } else if (choice == _("None")) {
3003                 snaptype = SnapToFrame;
3004         }
3005
3006         RefPtr<RadioAction> ract = snap_type_action (snaptype);
3007         if (ract) {
3008                 ract->set_active ();
3009         }
3010 }       
3011
3012 void
3013 Editor::snap_mode_selection_done ()
3014 {
3015         string choice = snap_mode_selector.get_active_text();
3016         SnapMode mode = SnapNormal;
3017
3018         if (choice == _("Normal")) {
3019                 mode = SnapNormal;
3020         } else if (choice == _("Magnetic")) {
3021                 mode = SnapMagnetic;
3022         }
3023
3024         RefPtr<RadioAction> ract = snap_mode_action (mode);
3025
3026         if (ract) {
3027                 ract->set_active (true);
3028         }
3029 }
3030
3031 void
3032 Editor::zoom_focus_selection_done ()
3033 {
3034         string choice = zoom_focus_selector.get_active_text();
3035         ZoomFocus focus_type = ZoomFocusLeft;
3036
3037         if (choice == _("Left")) {
3038                 focus_type = ZoomFocusLeft;
3039         } else if (choice == _("Right")) {
3040                 focus_type = ZoomFocusRight;
3041         } else if (choice == _("Center")) {
3042                 focus_type = ZoomFocusCenter;
3043         } else if (choice == _("Playhead")) {
3044                 focus_type = ZoomFocusPlayhead;
3045         } else if (choice == _("Edit Cursor")) {
3046                 focus_type = ZoomFocusEdit;
3047         } 
3048         
3049         RefPtr<RadioAction> ract = zoom_focus_action (focus_type);
3050
3051         if (ract) {
3052                 ract->set_active ();
3053         }
3054 }       
3055
3056 gint
3057 Editor::edit_controls_button_release (GdkEventButton* ev)
3058 {
3059         if (Keyboard::is_context_menu_event (ev)) {
3060                 ARDOUR_UI::instance()->add_route (this);
3061         }
3062         return TRUE;
3063 }
3064
3065 gint
3066 Editor::mouse_select_button_release (GdkEventButton* ev)
3067 {
3068         /* this handles just right-clicks */
3069
3070         if (ev->button != 3) {
3071                 return false;
3072         }
3073
3074         return true;
3075 }
3076
3077 Editor::TrackViewList *
3078 Editor::get_valid_views (TimeAxisView* track, RouteGroup* group)
3079 {
3080         TrackViewList *v;
3081         TrackViewList::iterator i;
3082
3083         v = new TrackViewList;
3084
3085         if (track == 0 && group == 0) {
3086
3087                 /* all views */
3088
3089                 for (i = track_views.begin(); i != track_views.end (); ++i) {
3090                         v->push_back (*i);
3091                 }
3092
3093         } else if (track != 0 && group == 0 || (track != 0 && group != 0 && !group->is_active())) {
3094                 
3095                 /* just the view for this track
3096                  */
3097
3098                 v->push_back (track);
3099
3100         } else {
3101                 
3102                 /* views for all tracks in the edit group */
3103                 
3104                 for (i  = track_views.begin(); i != track_views.end (); ++i) {
3105
3106                         if (group == 0 || (*i)->edit_group() == group) {
3107                                 v->push_back (*i);
3108                         }
3109                 }
3110         }
3111         
3112         return v;
3113 }
3114
3115 void
3116 Editor::set_zoom_focus (ZoomFocus f)
3117 {
3118         string str = zoom_focus_strings[(int)f];
3119
3120         if (str != zoom_focus_selector.get_active_text()) {
3121                 zoom_focus_selector.set_active_text (str);
3122         }
3123         
3124         if (zoom_focus != f) {
3125                 zoom_focus = f;
3126
3127                 ZoomFocusChanged (); /* EMIT_SIGNAL */
3128
3129                 instant_save ();
3130         }
3131 }
3132
3133 void
3134 Editor::ensure_float (Window& win)
3135 {
3136         win.set_transient_for (*this);
3137 }
3138
3139 void 
3140 Editor::pane_allocation_handler (Allocation &alloc, Paned* which)
3141 {
3142         /* recover or initialize pane positions. do this here rather than earlier because
3143            we don't want the positions to change the child allocations, which they seem to do.
3144          */
3145
3146         int pos;
3147         XMLProperty* prop;
3148         char buf[32];
3149         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
3150         int width, height;
3151         static int32_t done;
3152         XMLNode* geometry;
3153
3154         if ((geometry = find_named_node (*node, "geometry")) == 0) {
3155                 width = default_width;
3156                 height = default_height;
3157         } else {
3158                 width = atoi(geometry->property("x_size")->value());
3159                 height = atoi(geometry->property("y_size")->value());
3160         }
3161
3162         if (which == static_cast<Paned*> (&edit_pane)) {
3163
3164                 if (done) {
3165                         return;
3166                 }
3167
3168                 if (!geometry || (prop = geometry->property ("edit_pane_pos")) == 0) {
3169                         /* initial allocation is 90% to canvas, 10% to notebook */
3170                         pos = (int) floor (alloc.get_width() * 0.90f);
3171                         snprintf (buf, sizeof(buf), "%d", pos);
3172                 } else {
3173                         pos = atoi (prop->value());
3174                 }
3175                 
3176                 if ((done = GTK_WIDGET(edit_pane.gobj())->allocation.width > pos)) {
3177                         edit_pane.set_position (pos);
3178                         pre_maximal_pane_position = pos;
3179                 }
3180         }
3181 }
3182
3183 void
3184 Editor::detach_tearoff (Box* b, Window* w)
3185 {
3186         if (tools_tearoff->torn_off() && 
3187             mouse_mode_tearoff->torn_off()) {
3188                 top_hbox.remove (toolbar_frame);
3189         }
3190 }
3191
3192 void
3193 Editor::reattach_tearoff (Box* b, Window* w, int32_t n)
3194 {
3195         if (toolbar_frame.get_parent() == 0) {
3196                 top_hbox.pack_end (toolbar_frame);
3197         }
3198 }
3199
3200 void
3201 Editor::set_show_measures (bool yn)
3202 {
3203         if (_show_measures != yn) {
3204                 hide_measures ();
3205
3206                 if ((_show_measures = yn) == true) {
3207                         draw_measures ();
3208                 }
3209                 instant_save ();
3210         }
3211 }
3212
3213 void
3214 Editor::toggle_follow_playhead ()
3215 {
3216         RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
3217         if (act) {
3218                 RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
3219                 set_follow_playhead (tact->get_active());
3220         }
3221 }
3222
3223 void
3224 Editor::set_follow_playhead (bool yn)
3225 {
3226         if (_follow_playhead != yn) {
3227                 if ((_follow_playhead = yn) == true) {
3228                         /* catch up */
3229                         update_current_screen ();
3230                 }
3231                 instant_save ();
3232         }
3233 }
3234
3235 void
3236 Editor::toggle_xfade_active (boost::weak_ptr<Crossfade> wxfade)
3237 {
3238         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3239         if (xfade) {
3240                 xfade->set_active (!xfade->active());
3241         }
3242 }
3243
3244 void
3245 Editor::toggle_xfade_length (boost::weak_ptr<Crossfade> wxfade)
3246 {
3247         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3248         if (xfade) {
3249                 xfade->set_follow_overlap (!xfade->following_overlap());
3250         }
3251 }
3252
3253 void
3254 Editor::edit_xfade (boost::weak_ptr<Crossfade> wxfade)
3255 {
3256         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3257
3258         if (!xfade) {
3259                 return;
3260         }
3261
3262         CrossfadeEditor cew (*session, xfade, xfade->fade_in().get_min_y(), 1.0);
3263                 
3264         ensure_float (cew);
3265         
3266         switch (cew.run ()) {
3267         case RESPONSE_ACCEPT:
3268                 break;
3269         default:
3270                 return;
3271         }
3272         
3273         cew.apply ();
3274         xfade->StateChanged (Change (~0));
3275 }
3276
3277 PlaylistSelector&
3278 Editor::playlist_selector () const
3279 {
3280         return *_playlist_selector;
3281 }
3282
3283 nframes_t
3284 Editor::get_nudge_distance (nframes_t pos, nframes_t& next)
3285 {
3286         nframes_t ret;
3287
3288         ret = nudge_clock.current_duration (pos);
3289         next = ret + 1; /* XXXX fix me */
3290
3291         return ret;
3292 }
3293
3294 void
3295 Editor::end_location_changed (Location* location)
3296 {
3297         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::end_location_changed), location));
3298         reset_scrolling_region ();
3299 }
3300
3301 int
3302 Editor::playlist_deletion_dialog (boost::shared_ptr<Playlist> pl)
3303 {
3304         ArdourDialog dialog ("playlist deletion dialog");
3305         Label  label (string_compose (_("Playlist %1 is currently unused.\n"
3306                                         "If left alone, no audio files used by it will be cleaned.\n"
3307                                         "If deleted, audio files used by it alone by will cleaned."),
3308                                       pl->name()));
3309         
3310         dialog.set_position (WIN_POS_CENTER);
3311         dialog.get_vbox()->pack_start (label);
3312
3313         label.show ();
3314
3315         dialog.add_button (_("Delete playlist"), RESPONSE_ACCEPT);
3316         dialog.add_button (_("Keep playlist"), RESPONSE_REJECT);
3317         dialog.add_button (_("Cancel"), RESPONSE_CANCEL);
3318
3319         switch (dialog.run ()) {
3320         case RESPONSE_ACCEPT:
3321                 /* delete the playlist */
3322                 return 0;
3323                 break;
3324
3325         case RESPONSE_REJECT:
3326                 /* keep the playlist */
3327                 return 1;
3328                 break;
3329
3330         default:
3331                 break;
3332         }
3333
3334         return -1;
3335 }
3336
3337 bool
3338 Editor::audio_region_selection_covers (nframes_t where)
3339 {
3340         for (RegionSelection::iterator a = selection->regions.begin(); a != selection->regions.end(); ++a) {
3341                 if ((*a)->region()->covers (where)) {
3342                         return true;
3343                 }
3344         }
3345
3346         return false;
3347 }
3348
3349 void
3350 Editor::prepare_for_cleanup ()
3351 {
3352         cut_buffer->clear_regions ();
3353         cut_buffer->clear_playlists ();
3354
3355         selection->clear_regions ();
3356         selection->clear_playlists ();
3357 }
3358
3359 Location*
3360 Editor::transport_loop_location()
3361 {
3362         if (session) {
3363                 return session->locations()->auto_loop_location();
3364         } else {
3365                 return 0;
3366         }
3367 }
3368
3369 Location*
3370 Editor::transport_punch_location()
3371 {
3372         if (session) {
3373                 return session->locations()->auto_punch_location();
3374         } else {
3375                 return 0;
3376         }
3377 }
3378
3379 bool
3380 Editor::control_layout_scroll (GdkEventScroll* ev)
3381 {
3382         switch (ev->direction) {
3383         case GDK_SCROLL_UP:
3384                 scroll_tracks_up_line ();
3385                 return true;
3386                 break;
3387
3388         case GDK_SCROLL_DOWN:
3389                 scroll_tracks_down_line ();
3390                 return true;
3391                 
3392         default:
3393                 /* no left/right handling yet */
3394                 break;
3395         }
3396
3397         return false;
3398 }
3399
3400
3401 /** A new snapshot has been selected.
3402  */
3403 void
3404 Editor::snapshot_display_selection_changed ()
3405 {
3406         if (snapshot_display.get_selection()->count_selected_rows() > 0) {
3407
3408                 TreeModel::iterator i = snapshot_display.get_selection()->get_selected();
3409                 
3410                 Glib::ustring snap_name = (*i)[snapshot_display_columns.real_name];
3411
3412                 if (snap_name.length() == 0) {
3413                         return;
3414                 }
3415                 
3416                 if (session->snap_name() == snap_name) {
3417                         return;
3418                 }
3419                 
3420                 ARDOUR_UI::instance()->load_session(session->path(), string (snap_name));
3421         }
3422 }
3423
3424 bool
3425 Editor::snapshot_display_button_press (GdkEventButton* ev)
3426 {
3427         if (ev->button == 3) {
3428                 /* Right-click on the snapshot list. Work out which snapshot it
3429                    was over. */
3430                 Gtk::TreeModel::Path path;
3431                 Gtk::TreeViewColumn* col;
3432                 int cx;
3433                 int cy;
3434                 snapshot_display.get_path_at_pos ((int) ev->x, (int) ev->y, path, col, cx, cy);
3435                 Gtk::TreeModel::iterator iter = snapshot_display_model->get_iter (path);
3436                 if (iter) {
3437                         Gtk::TreeModel::Row row = *iter;
3438                         popup_snapshot_context_menu (ev->button, ev->time, row[snapshot_display_columns.real_name]);
3439                 }
3440                 return true;
3441         }
3442
3443         return false;
3444 }
3445
3446
3447 /** Pop up the snapshot display context menu.
3448  * @param button Button used to open the menu.
3449  * @param time Menu open time.
3450  * @snapshot_name Name of the snapshot that the menu click was over.
3451  */
3452
3453 void
3454 Editor::popup_snapshot_context_menu (int button, int32_t time, Glib::ustring snapshot_name)
3455 {
3456         using namespace Menu_Helpers;
3457
3458         MenuList& items (snapshot_context_menu.items());
3459         items.clear ();
3460
3461         const bool modification_allowed = (session->snap_name() != snapshot_name && session->name() != snapshot_name);
3462
3463         items.push_back (MenuElem (_("Remove"), bind (mem_fun (*this, &Editor::remove_snapshot), snapshot_name)));
3464         if (!modification_allowed) {
3465                 items.back().set_sensitive (false);
3466         }
3467
3468         items.push_back (MenuElem (_("Rename"), bind (mem_fun (*this, &Editor::rename_snapshot), snapshot_name)));
3469         if (!modification_allowed) {
3470                 items.back().set_sensitive (false);
3471         }
3472
3473         snapshot_context_menu.popup (button, time);
3474 }
3475
3476 void
3477 Editor::rename_snapshot (Glib::ustring old_name)
3478 {
3479         ArdourPrompter prompter(true);
3480
3481         string new_name;
3482
3483         prompter.set_name ("Prompter");
3484         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
3485         prompter.set_prompt (_("New name of snapshot"));
3486         prompter.set_initial_text (old_name);
3487         
3488         if (prompter.run() == RESPONSE_ACCEPT) {
3489                 prompter.get_result (new_name);
3490                 if (new_name.length()) {
3491                         session->rename_state (old_name, new_name);
3492                         redisplay_snapshots ();
3493                 }
3494         }
3495 }
3496
3497
3498 void
3499 Editor::remove_snapshot (Glib::ustring name)
3500 {
3501         vector<string> choices;
3502
3503         std::string prompt  = string_compose (_("Do you really want to remove snapshot \"%1\" ?\n(cannot be undone)"), name);
3504
3505         choices.push_back (_("No, do nothing."));
3506         choices.push_back (_("Yes, remove it."));
3507
3508         Gtkmm2ext::Choice prompter (prompt, choices);
3509
3510         if (prompter.run () == 1) {
3511                 session->remove_state (name);
3512                 redisplay_snapshots ();
3513         }
3514 }
3515
3516 void
3517 Editor::redisplay_snapshots ()
3518 {
3519         if (session == 0) {
3520                 return;
3521         }
3522
3523         vector<string*>* states;
3524
3525         if ((states = session->possible_states()) == 0) {
3526                 return;
3527         }
3528
3529         snapshot_display_model->clear ();
3530
3531         for (vector<string*>::iterator i = states->begin(); i != states->end(); ++i) {
3532                 string statename = *(*i);
3533                 TreeModel::Row row = *(snapshot_display_model->append());
3534                 
3535                 /* this lingers on in case we ever want to change the visible
3536                    name of the snapshot.
3537                 */
3538                 
3539                 string display_name;
3540                 display_name = statename;
3541
3542                 if (statename == session->snap_name()) {
3543                         snapshot_display.get_selection()->select(row);
3544                 } 
3545                 
3546                 row[snapshot_display_columns.visible_name] = display_name;
3547                 row[snapshot_display_columns.real_name] = statename;
3548         }
3549
3550         delete states;
3551 }
3552
3553 void
3554 Editor::session_state_saved (string snap_name)
3555 {
3556         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::session_state_saved), snap_name));
3557         redisplay_snapshots ();
3558 }
3559
3560 void
3561 Editor::maximise_editing_space ()
3562 {
3563         initial_ruler_update_required = true;
3564
3565         mouse_mode_tearoff->set_visible (false);
3566         tools_tearoff->set_visible (false);
3567
3568         pre_maximal_pane_position = edit_pane.get_position();
3569         pre_maximal_editor_width = this->get_width();
3570
3571         if(post_maximal_pane_position == 0) {
3572                 post_maximal_pane_position = edit_pane.get_width();
3573         }
3574
3575
3576         fullscreen();
3577         if(post_maximal_editor_width) {
3578                 edit_pane.set_position (post_maximal_pane_position - 
3579                         abs(post_maximal_editor_width - pre_maximal_editor_width));
3580         } else {
3581                 edit_pane.set_position (post_maximal_pane_position);
3582         }
3583 }
3584
3585 void
3586 Editor::restore_editing_space ()
3587 {
3588         initial_ruler_update_required = true;
3589
3590         // user changed width of pane during fullscreen
3591         if(post_maximal_pane_position != edit_pane.get_position()) {
3592                 post_maximal_pane_position = edit_pane.get_position();
3593         }
3594
3595         unfullscreen();
3596
3597         mouse_mode_tearoff->set_visible (true);
3598         tools_tearoff->set_visible (true);
3599         post_maximal_editor_width = this->get_width();
3600
3601
3602         edit_pane.set_position (
3603                 pre_maximal_pane_position + abs(this->get_width() - pre_maximal_editor_width)
3604         );
3605 }
3606
3607 void 
3608 Editor::new_playlists ()
3609 {
3610         begin_reversible_command (_("new playlists"));
3611         mapover_tracks (mem_fun (*this, &Editor::mapped_use_new_playlist));
3612         commit_reversible_command ();
3613 }
3614
3615 void
3616 Editor::copy_playlists ()
3617 {
3618         begin_reversible_command (_("copy playlists"));
3619         mapover_tracks (mem_fun (*this, &Editor::mapped_use_copy_playlist));
3620         commit_reversible_command ();
3621 }
3622
3623 void 
3624 Editor::clear_playlists ()
3625 {
3626         begin_reversible_command (_("clear playlists"));
3627         mapover_tracks (mem_fun (*this, &Editor::mapped_clear_playlist));
3628         commit_reversible_command ();
3629 }
3630
3631 void 
3632 Editor::mapped_use_new_playlist (RouteTimeAxisView& atv, uint32_t sz)
3633 {
3634         atv.use_new_playlist (sz > 1 ? false : true);
3635 }
3636
3637 void
3638 Editor::mapped_use_copy_playlist (RouteTimeAxisView& atv, uint32_t sz)
3639 {
3640         atv.use_copy_playlist (sz > 1 ? false : true);
3641 }
3642
3643 void 
3644 Editor::mapped_clear_playlist (RouteTimeAxisView& atv, uint32_t sz)
3645 {
3646         atv.clear_playlist ();
3647 }
3648
3649 bool
3650 Editor::on_key_press_event (GdkEventKey* ev)
3651 {
3652         return key_press_focus_accelerator_handler (*this, ev);
3653 }
3654
3655 void
3656 Editor::reset_x_origin (nframes_t frame)
3657 {
3658         queue_visual_change (frame);
3659 }
3660
3661 void
3662 Editor::reset_zoom (double fpu)
3663 {
3664         queue_visual_change (fpu);
3665 }
3666
3667 void
3668 Editor::reposition_and_zoom (nframes_t frame, double fpu)
3669 {
3670         reset_x_origin (frame);
3671         reset_zoom (fpu);
3672 }
3673
3674 void
3675 Editor::set_frames_per_unit (double fpu)
3676 {
3677         nframes_t frames;
3678
3679         /* this is the core function that controls the zoom level of the canvas. it is called
3680            whenever one or more calls are made to reset_zoom(). it executes in an idle handler.
3681         */
3682
3683         if (fpu == frames_per_unit) {
3684                 return;
3685         }
3686
3687         if (fpu < 2.0) {
3688                 fpu = 2.0;
3689         }
3690
3691         // convert fpu to frame count
3692
3693         frames = (nframes_t) floor (fpu * canvas_width);
3694         
3695         /* don't allow zooms that fit more than the maximum number
3696            of frames into an 800 pixel wide space.
3697         */
3698
3699         if (max_frames / fpu < 800.0) {
3700                 return;
3701         }
3702
3703         if (fpu == frames_per_unit) {
3704                 return;
3705         }
3706
3707         frames_per_unit = fpu;
3708
3709         if (frames != zoom_range_clock.current_duration()) {
3710                 zoom_range_clock.set (frames);
3711         }
3712
3713         if (mouse_mode == MouseRange && selection->time.start () != selection->time.end_frame ()) {
3714                 if (!selection->tracks.empty()) {
3715                         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
3716                                 (*i)->reshow_selection (selection->time);
3717                         }
3718                 } else {
3719                         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
3720                                 (*i)->reshow_selection (selection->time);
3721                         }
3722                 }
3723         }
3724
3725         ZoomChanged (); /* EMIT_SIGNAL */
3726
3727         reset_hscrollbar_stepping ();
3728         reset_scrolling_region ();
3729         
3730         if (edit_cursor) edit_cursor->set_position (edit_cursor->current_frame);
3731         if (playhead_cursor) playhead_cursor->set_position (playhead_cursor->current_frame);
3732
3733         instant_save ();
3734 }
3735
3736 void
3737 Editor::queue_visual_change (nframes_t where)
3738 {
3739         pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::TimeOrigin);
3740         pending_visual_change.time_origin = where;
3741
3742         if (pending_visual_change.idle_handler_id < 0) {
3743                 pending_visual_change.idle_handler_id = g_idle_add (_idle_visual_changer, this);
3744         }
3745 }
3746
3747 void
3748 Editor::queue_visual_change (double fpu)
3749 {
3750         pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::ZoomLevel);
3751         pending_visual_change.frames_per_unit = fpu;
3752
3753         if (pending_visual_change.idle_handler_id < 0) {
3754                 pending_visual_change.idle_handler_id = g_idle_add_full (G_PRIORITY_HIGH_IDLE, _idle_visual_changer, this, 0);
3755         }
3756 }
3757
3758 int
3759 Editor::_idle_visual_changer (void* arg)
3760 {
3761         return static_cast<Editor*>(arg)->idle_visual_changer ();
3762 }
3763
3764 int
3765 Editor::idle_visual_changer ()
3766 {
3767         VisualChange::Type p = pending_visual_change.pending;
3768
3769         pending_visual_change.pending = (VisualChange::Type) 0;
3770         pending_visual_change.idle_handler_id = -1;
3771         
3772         if (p & VisualChange::ZoomLevel) {
3773                 set_frames_per_unit (pending_visual_change.frames_per_unit);
3774         }
3775
3776         if (p & VisualChange::TimeOrigin) {
3777                 if (pending_visual_change.time_origin != leftmost_frame) {
3778                         horizontal_adjustment.set_value (pending_visual_change.time_origin/frames_per_unit);
3779                         /* the signal handler will do the rest */
3780                 } else {
3781                         update_fixed_rulers();
3782                         redisplay_tempo (true);
3783                 }
3784         }
3785
3786         return 0; /* this is always a one-shot call */
3787 }
3788
3789 struct EditorOrderTimeAxisSorter {
3790     bool operator() (const TimeAxisView* a, const TimeAxisView* b) const {
3791             return a->order < b->order;
3792     }
3793 };
3794         
3795 void
3796 Editor::sort_track_selection ()
3797 {
3798         EditorOrderTimeAxisSorter cmp;
3799         selection->tracks.sort (cmp);
3800 }
3801
3802 nframes_t
3803 Editor::edit_cursor_position(bool sync)
3804 {
3805         if (sync && edit_cursor->current_frame != edit_cursor_clock.current_time()) {
3806                 edit_cursor_clock.set(edit_cursor->current_frame, true);
3807         }
3808
3809         return edit_cursor->current_frame;
3810 }