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