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