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