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