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