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