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