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