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