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