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