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