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