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