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