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