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