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