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