Make visible track automation views appear correctly newly loaded sessions.
[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         cout<< "OSC: Recieved: "<< action_item << endl;
1051
1052         RefPtr<Action> act;
1053         act = ActionManager::get_action( action_group.c_str(), action_item.c_str() );
1054
1055         if (act) {
1056                 act->activate();
1057         }
1058                 
1059
1060 }
1061
1062 void
1063 Editor::on_realize ()
1064 {
1065         Window::on_realize ();
1066         Realized ();
1067 }
1068
1069 void
1070 Editor::start_scrolling ()
1071 {
1072         scroll_connection = ARDOUR_UI::instance()->SuperRapidScreenUpdate.connect 
1073                 (mem_fun(*this, &Editor::update_current_screen));
1074
1075 }
1076
1077 void
1078 Editor::stop_scrolling ()
1079 {
1080         scroll_connection.disconnect ();
1081 }
1082
1083 void
1084 Editor::map_position_change (nframes64_t frame)
1085 {
1086         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::map_position_change), frame));
1087
1088         if (session == 0 || !_follow_playhead) {
1089                 return;
1090         }
1091
1092         center_screen (frame);
1093         playhead_cursor->set_position (frame);
1094 }       
1095
1096 void
1097 Editor::center_screen (nframes64_t frame)
1098 {
1099         double page = canvas_width * frames_per_unit;
1100
1101         /* if we're off the page, then scroll.
1102          */
1103         
1104         if (frame < leftmost_frame || frame >= leftmost_frame + page) {
1105                 center_screen_internal (frame, page);
1106         }
1107 }
1108
1109 void
1110 Editor::center_screen_internal (nframes64_t frame, float page)
1111 {
1112         page /= 2;
1113                 
1114         if (frame > page) {
1115                 frame -= (nframes64_t) page;
1116         } else {
1117                 frame = 0;
1118         }
1119
1120         reset_x_origin (frame);
1121 }
1122
1123 void
1124 Editor::handle_new_duration ()
1125 {
1126         if (!session) {
1127                 return;
1128         }
1129
1130         ENSURE_GUI_THREAD (mem_fun (*this, &Editor::handle_new_duration));
1131
1132         nframes64_t new_end = session->current_end_frame() + (nframes64_t) floorf (current_page_frames() * 0.10f);
1133
1134         horizontal_adjustment.set_upper (new_end / frames_per_unit);
1135         horizontal_adjustment.set_page_size (current_page_frames()/frames_per_unit);
1136         
1137         if (horizontal_adjustment.get_value() + canvas_width > horizontal_adjustment.get_upper()) {
1138                 horizontal_adjustment.set_value (horizontal_adjustment.get_upper() - canvas_width);
1139         }
1140         //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
1141 }
1142
1143 void
1144 Editor::update_title_s (const string & snap_name)
1145 {
1146         ENSURE_GUI_THREAD(bind (mem_fun(*this, &Editor::update_title_s), snap_name));
1147         
1148         update_title ();
1149 }
1150
1151 void
1152 Editor::update_title ()
1153 {
1154         ENSURE_GUI_THREAD (mem_fun(*this, &Editor::update_title));
1155
1156         if (session) {
1157                 bool dirty = session->dirty();
1158
1159                 string session_name;
1160
1161                 if (session->snap_name() != session->name()) {
1162                         session_name = session->snap_name();
1163                 } else {
1164                         session_name = session->name();
1165                 }
1166
1167                 if (dirty) {
1168                         session_name = "*" + session_name;
1169                 }
1170
1171                 WindowTitle title(session_name);
1172                 title += Glib::get_application_name();
1173                 set_title (title.get_string());
1174         }
1175 }
1176
1177 void
1178 Editor::connect_to_session (Session *t)
1179 {
1180         session = t;
1181
1182         /* there are never any selected regions at startup */
1183
1184         sensitize_the_right_region_actions (false);
1185
1186         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
1187         set_state (*node);
1188
1189         /* catch up with the playhead */
1190
1191         session->request_locate (playhead_cursor->current_frame);
1192
1193         if (first_action_message) {
1194                 first_action_message->hide();
1195         }
1196
1197         update_title ();
1198
1199         session->GoingAway.connect (mem_fun(*this, &Editor::session_going_away));
1200         session->history().Changed.connect (mem_fun (*this, &Editor::history_changed));
1201
1202         /* These signals can all be emitted by a non-GUI thread. Therefore the
1203            handlers for them must not attempt to directly interact with the GUI,
1204            but use Gtkmm2ext::UI::instance()->call_slot();
1205         */
1206
1207         session_connections.push_back (session->TransportStateChange.connect (mem_fun(*this, &Editor::map_transport_state)));
1208         session_connections.push_back (session->PositionChanged.connect (mem_fun(*this, &Editor::map_position_change)));
1209         session_connections.push_back (session->RouteAdded.connect (mem_fun(*this, &Editor::handle_new_route)));
1210         session_connections.push_back (session->AudioRegionsAdded.connect (mem_fun(*this, &Editor::handle_new_audio_regions)));
1211         session_connections.push_back (session->AudioRegionRemoved.connect (mem_fun(*this, &Editor::handle_audio_region_removed)));
1212         session_connections.push_back (session->DurationChanged.connect (mem_fun(*this, &Editor::handle_new_duration)));
1213         session_connections.push_back (session->edit_group_added.connect (mem_fun(*this, &Editor::add_edit_group)));
1214         session_connections.push_back (session->edit_group_removed.connect (mem_fun(*this, &Editor::edit_groups_changed)));
1215         session_connections.push_back (session->NamedSelectionAdded.connect (mem_fun(*this, &Editor::handle_new_named_selection)));
1216         session_connections.push_back (session->NamedSelectionRemoved.connect (mem_fun(*this, &Editor::handle_new_named_selection)));
1217         session_connections.push_back (session->DirtyChanged.connect (mem_fun(*this, &Editor::update_title)));
1218         session_connections.push_back (session->StateSaved.connect (mem_fun(*this, &Editor::update_title_s)));
1219         session_connections.push_back (session->AskAboutPlaylistDeletion.connect (mem_fun(*this, &Editor::playlist_deletion_dialog)));
1220         session_connections.push_back (session->RegionHiddenChange.connect (mem_fun(*this, &Editor::region_hidden)));
1221
1222         session_connections.push_back (session->SMPTEOffsetChanged.connect (mem_fun(*this, &Editor::update_just_smpte)));
1223
1224         session_connections.push_back (session->tempo_map().StateChanged.connect (mem_fun(*this, &Editor::tempo_map_changed)));
1225
1226         edit_groups_changed ();
1227
1228         edit_point_clock.set_session (session);
1229         zoom_range_clock.set_session (session);
1230         _playlist_selector->set_session (session);
1231         nudge_clock.set_session (session);
1232         nudge_clock.set (session->frame_rate() * 5); // default of 5 seconds
1233
1234         playhead_cursor->canvas_item.show ();
1235
1236         if (rhythm_ferret) {
1237                 rhythm_ferret->set_session (session);
1238         }
1239
1240 #ifdef FFT_ANALYSIS
1241         if (analysis_window != 0)
1242                 analysis_window->set_session (session);
1243 #endif
1244
1245         Location* loc = session->locations()->auto_loop_location();
1246         if (loc == 0) {
1247                 loc = new Location (0, session->current_end_frame(), _("Loop"),(Location::Flags) (Location::IsAutoLoop | Location::IsHidden));
1248                 if (loc->start() == loc->end()) {
1249                         loc->set_end (loc->start() + 1);
1250                 }
1251                 session->locations()->add (loc, false);
1252                 session->set_auto_loop_location (loc);
1253         } else {
1254                 // force name
1255                 loc->set_name (_("Loop"));
1256         }
1257         
1258         loc = session->locations()->auto_punch_location();
1259         if (loc == 0) {
1260                 loc = new Location (0, session->current_end_frame(), _("Punch"), (Location::Flags) (Location::IsAutoPunch | Location::IsHidden));
1261                 if (loc->start() == loc->end()) {
1262                         loc->set_end (loc->start() + 1);
1263                 }
1264                 session->locations()->add (loc, false);
1265                 session->set_auto_punch_location (loc);
1266         } else {
1267                 // force name
1268                 loc->set_name (_("Punch"));
1269         }
1270
1271         Config->map_parameters (mem_fun (*this, &Editor::parameter_changed));
1272         
1273         session->StateSaved.connect (mem_fun(*this, &Editor::session_state_saved));
1274         
1275         refresh_location_display ();
1276         session->locations()->added.connect (mem_fun(*this, &Editor::add_new_location));
1277         session->locations()->removed.connect (mem_fun(*this, &Editor::location_gone));
1278         session->locations()->changed.connect (mem_fun(*this, &Editor::refresh_location_display));
1279         session->locations()->StateChanged.connect (mem_fun(*this, &Editor::refresh_location_display_s));
1280         session->locations()->end_location()->changed.connect (mem_fun(*this, &Editor::end_location_changed));
1281
1282         if (sfbrowser) {
1283                 sfbrowser->set_session (session);
1284         }
1285
1286         handle_new_duration ();
1287
1288         redisplay_regions ();
1289         redisplay_named_selections ();
1290         redisplay_snapshots ();
1291
1292         initial_route_list_display ();
1293
1294         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
1295                 (static_cast<TimeAxisView*>(*i))->set_samples_per_unit (frames_per_unit);
1296         }
1297
1298         restore_ruler_visibility ();
1299         //tempo_map_changed (Change (0));
1300         session->tempo_map().apply_with_metrics (*this, &Editor::draw_metric_marks);
1301
1302         start_scrolling ();
1303
1304         /* don't show master bus in a new session */
1305
1306         if (ARDOUR_UI::instance()->session_is_new ()) {
1307
1308                 TreeModel::Children rows = route_display_model->children();
1309                 TreeModel::Children::iterator i;
1310         
1311                 no_route_list_redisplay = true;
1312                 
1313                 for (i = rows.begin(); i != rows.end(); ++i) {
1314                         TimeAxisView *tv =  (*i)[route_display_columns.tv];
1315                         AudioTimeAxisView *atv;
1316                         
1317                         if ((atv = dynamic_cast<AudioTimeAxisView*>(tv)) != 0) {
1318                                 if (atv->route()->master()) {
1319                                         route_list_display.get_selection()->unselect (i);
1320                                 }
1321                         }
1322                 }
1323                 
1324                 no_route_list_redisplay = false;
1325                 redisplay_route_list ();
1326         }
1327
1328         switch (snap_type) {
1329         case SnapToRegionStart:
1330         case SnapToRegionEnd:
1331         case SnapToRegionSync:
1332         case SnapToRegionBoundary:
1333                 build_region_boundary_cache ();
1334                 break;
1335
1336         default:
1337                 break;
1338         }
1339
1340         /* register for undo history */
1341
1342         session->register_with_memento_command_factory(_id, this);
1343
1344         start_updating ();
1345 }
1346
1347 void
1348 Editor::build_cursors ()
1349 {
1350         using namespace Gdk;
1351         
1352         Gdk::Color mbg ("#000000" ); /* Black */
1353         Gdk::Color mfg ("#0000ff" ); /* Blue. */
1354
1355         {
1356                 RefPtr<Bitmap> source, mask;
1357                 source = Bitmap::create (mag_bits, mag_width, mag_height);
1358                 mask = Bitmap::create (magmask_bits, mag_width, mag_height);
1359                 zoom_cursor = new Gdk::Cursor (source, mask, mfg, mbg, mag_x_hot, mag_y_hot);
1360         }
1361
1362         Gdk::Color fbg ("#ffffff" );
1363         Gdk::Color ffg  ("#000000" );
1364         
1365         {
1366                 RefPtr<Bitmap> source, mask;
1367                 
1368                 source = Bitmap::create (fader_cursor_bits, fader_cursor_width, fader_cursor_height);
1369                 mask = Bitmap::create (fader_cursor_mask_bits, fader_cursor_width, fader_cursor_height);
1370                 fader_cursor = new Gdk::Cursor (source, mask, ffg, fbg, fader_cursor_x_hot, fader_cursor_y_hot);
1371         }
1372         
1373         { 
1374                 RefPtr<Bitmap> source, mask;
1375                 source = Bitmap::create (speaker_cursor_bits, speaker_cursor_width, speaker_cursor_height);
1376                 mask = Bitmap::create (speaker_cursor_mask_bits, speaker_cursor_width, speaker_cursor_height);
1377                 speaker_cursor = new Gdk::Cursor (source, mask, ffg, fbg, speaker_cursor_x_hot, speaker_cursor_y_hot);
1378         }
1379
1380         { 
1381                 RefPtr<Bitmap> bits;
1382                 char pix[4] = { 0, 0, 0, 0 };
1383                 bits = Bitmap::create (pix, 2, 2);
1384                 Gdk::Color c;
1385                 transparent_cursor = new Gdk::Cursor (bits, bits, c, c, 0, 0);
1386         }
1387         
1388
1389         grabber_cursor = new Gdk::Cursor (HAND2);
1390         
1391         {
1392                 Glib::RefPtr<Gdk::Pixbuf> grabber_edit_point_pixbuf (::get_icon ("grabber_edit_point"));
1393                 grabber_edit_point_cursor = new Gdk::Cursor (Gdk::Display::get_default(), grabber_edit_point_pixbuf, 5, 17);
1394         }
1395
1396         cross_hair_cursor = new Gdk::Cursor (CROSSHAIR);
1397         trimmer_cursor =  new Gdk::Cursor (SB_H_DOUBLE_ARROW);
1398         selector_cursor = new Gdk::Cursor (XTERM);
1399         time_fx_cursor = new Gdk::Cursor (SIZING);
1400         wait_cursor = new Gdk::Cursor  (WATCH);
1401         timebar_cursor = new Gdk::Cursor(LEFT_PTR);
1402 }
1403
1404 void
1405 Editor::popup_fade_context_menu (int button, int32_t time, ArdourCanvas::Item* item, ItemType item_type)
1406 {
1407         using namespace Menu_Helpers;
1408         AudioRegionView* arv = static_cast<AudioRegionView*> (item->get_data ("regionview"));
1409
1410         if (arv == 0) {
1411                 fatal << _("programming error: fade in canvas item has no regionview data pointer!") << endmsg;
1412                 /*NOTREACHED*/
1413         }
1414
1415         MenuList& items (fade_context_menu.items());
1416
1417         items.clear ();
1418
1419         switch (item_type) {
1420         case FadeInItem:
1421         case FadeInHandleItem:
1422                 if (arv->audio_region()->fade_in_active()) {
1423                         items.push_back (MenuElem (_("Deactivate"), bind (mem_fun (*this, &Editor::set_fade_in_active), false)));
1424                 } else {
1425                         items.push_back (MenuElem (_("Activate"), bind (mem_fun (*this, &Editor::set_fade_in_active), true)));
1426                 }
1427                 
1428                 items.push_back (SeparatorElem());
1429
1430                 if (Profile->get_sae()) {
1431                         items.push_back (MenuElem (_("Linear"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Linear)));
1432                         items.push_back (MenuElem (_("Slowest"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Fast)));
1433                 } else {
1434                         items.push_back (MenuElem (_("Linear"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Linear)));
1435                         items.push_back (MenuElem (_("Slowest"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Fast)));
1436                         items.push_back (MenuElem (_("Slow"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::LogB)));
1437                         items.push_back (MenuElem (_("Fast"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::LogA)));
1438                         items.push_back (MenuElem (_("Fastest"), bind (mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Slow)));
1439                 }
1440                 break;
1441
1442         case FadeOutItem:
1443         case FadeOutHandleItem:
1444                 if (arv->audio_region()->fade_out_active()) {
1445                         items.push_back (MenuElem (_("Deactivate"), bind (mem_fun (*this, &Editor::set_fade_out_active), false)));
1446                 } else {
1447                         items.push_back (MenuElem (_("Activate"), bind (mem_fun (*this, &Editor::set_fade_out_active), true)));
1448                 }
1449                 
1450                 items.push_back (SeparatorElem());
1451
1452                 if (Profile->get_sae()) {
1453                         items.push_back (MenuElem (_("Linear"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Linear)));
1454                         items.push_back (MenuElem (_("Slowest"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Slow)));
1455                 } else {
1456                         items.push_back (MenuElem (_("Linear"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Linear)));
1457                         items.push_back (MenuElem (_("Slowest"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Slow)));
1458                         items.push_back (MenuElem (_("Slow"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::LogA)));
1459                         items.push_back (MenuElem (_("Fast"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::LogB)));
1460                         items.push_back (MenuElem (_("Fastest"), bind (mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Fast)));
1461                 }
1462                 break;
1463
1464         default:
1465                 fatal << _("programming error: ")
1466                       << X_("non-fade canvas item passed to popup_fade_context_menu()")
1467                       << endmsg;
1468                 /*NOTREACHED*/
1469         }
1470
1471         fade_context_menu.popup (button, time);
1472 }
1473
1474 void
1475 Editor::popup_track_context_menu (int button, int32_t time, ItemType item_type, bool with_selection, nframes64_t frame)
1476 {
1477         using namespace Menu_Helpers;
1478         Menu* (Editor::*build_menu_function)(nframes64_t);
1479         Menu *menu;
1480
1481         switch (item_type) {
1482         case RegionItem:
1483         case RegionViewName:
1484         case RegionViewNameHighlight:
1485                 if (with_selection) {
1486                         build_menu_function = &Editor::build_track_selection_context_menu;
1487                 } else {
1488                         build_menu_function = &Editor::build_track_region_context_menu;
1489                 }
1490                 break;
1491
1492         case SelectionItem:
1493                 if (with_selection) {
1494                         build_menu_function = &Editor::build_track_selection_context_menu;
1495                 } else {
1496                         build_menu_function = &Editor::build_track_context_menu;
1497                 }
1498                 break;
1499
1500         case CrossfadeViewItem:
1501                 build_menu_function = &Editor::build_track_crossfade_context_menu;
1502                 break;
1503
1504         case StreamItem:
1505                 if (clicked_audio_trackview->get_diskstream()) {
1506                         build_menu_function = &Editor::build_track_context_menu;
1507                 } else {
1508                         build_menu_function = &Editor::build_track_bus_context_menu;
1509                 }
1510                 break;
1511
1512         default:
1513                 /* probably shouldn't happen but if it does, we don't care */
1514                 return;
1515         }
1516
1517         menu = (this->*build_menu_function)(frame);
1518         menu->set_name ("ArdourContextMenu");
1519         
1520         /* now handle specific situations */
1521
1522         switch (item_type) {
1523         case RegionItem:
1524         case RegionViewName:
1525         case RegionViewNameHighlight:
1526                 if (!with_selection) {
1527                         if (region_edit_menu_split_item) {
1528                                 if (clicked_regionview && clicked_regionview->region()->covers (get_preferred_edit_position())) {
1529                                         ActionManager::set_sensitive (ActionManager::edit_point_in_region_sensitive_actions, true);
1530                                 } else {
1531                                         ActionManager::set_sensitive (ActionManager::edit_point_in_region_sensitive_actions, false);
1532                                 }
1533                         }
1534                         /*
1535                         if (region_edit_menu_split_multichannel_item) {
1536                                 if (clicked_regionview && clicked_regionview->region().n_channels() > 1) {
1537                                         // GTK2FIX find the action, change its sensitivity
1538                                         // region_edit_menu_split_multichannel_item->set_sensitive (true);
1539                                 } else {
1540                                         // GTK2FIX see above
1541                                         // region_edit_menu_split_multichannel_item->set_sensitive (false);
1542                                 }
1543                         }*/
1544                 }
1545                 break;
1546
1547         case SelectionItem:
1548                 break;
1549
1550         case CrossfadeViewItem:
1551                 break;
1552
1553         case StreamItem:
1554                 break;
1555
1556         default:
1557                 /* probably shouldn't happen but if it does, we don't care */
1558                 return;
1559         }
1560
1561         if (item_type != SelectionItem && clicked_audio_trackview && clicked_audio_trackview->audio_track()) {
1562
1563                 /* Bounce to disk */
1564                 
1565                 using namespace Menu_Helpers;
1566                 MenuList& edit_items  = menu->items();
1567                 
1568                 edit_items.push_back (SeparatorElem());
1569
1570                 switch (clicked_audio_trackview->audio_track()->freeze_state()) {
1571                 case AudioTrack::NoFreeze:
1572                         edit_items.push_back (MenuElem (_("Freeze"), mem_fun(*this, &Editor::freeze_route)));
1573                         break;
1574
1575                 case AudioTrack::Frozen:
1576                         edit_items.push_back (MenuElem (_("Unfreeze"), mem_fun(*this, &Editor::unfreeze_route)));
1577                         break;
1578                         
1579                 case AudioTrack::UnFrozen:
1580                         edit_items.push_back (MenuElem (_("Freeze"), mem_fun(*this, &Editor::freeze_route)));
1581                         break;
1582                 }
1583
1584         }
1585
1586         menu->popup (button, time);
1587 }
1588
1589 Menu*
1590 Editor::build_track_context_menu (nframes64_t ignored)
1591 {
1592         using namespace Menu_Helpers;
1593
1594         MenuList& edit_items = track_context_menu.items();
1595         edit_items.clear();
1596
1597         add_dstream_context_items (edit_items);
1598         return &track_context_menu;
1599 }
1600
1601 Menu*
1602 Editor::build_track_bus_context_menu (nframes64_t ignored)
1603 {
1604         using namespace Menu_Helpers;
1605
1606         MenuList& edit_items = track_context_menu.items();
1607         edit_items.clear();
1608
1609         add_bus_context_items (edit_items);
1610         return &track_context_menu;
1611 }
1612
1613 Menu*
1614 Editor::build_track_region_context_menu (nframes64_t frame)
1615 {
1616         using namespace Menu_Helpers;
1617         MenuList& edit_items  = track_region_context_menu.items();
1618         edit_items.clear();
1619
1620         AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*> (clicked_trackview);
1621
1622         if (atv) {
1623                 boost::shared_ptr<Diskstream> ds;
1624                 boost::shared_ptr<Playlist> pl;
1625                 
1626                 if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()))) {
1627                         Playlist::RegionList* regions = pl->regions_at ((nframes64_t) floor ( (double)frame * ds->speed()));
1628
1629                         if (selection->regions.size() > 1) {
1630                                 // there's already a multiple selection: just add a 
1631                                 // single region context menu that will act on all 
1632                                 // selected regions
1633                                 boost::shared_ptr<Region> dummy_region; // = NULL               
1634                                 add_region_context_items (atv->audio_view(), dummy_region, edit_items);                 
1635                         } else {
1636                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
1637                                         add_region_context_items (atv->audio_view(), (*i), edit_items);
1638                                 }
1639                         }
1640
1641                         delete regions;
1642                 }
1643         }
1644
1645         add_dstream_context_items (edit_items);
1646
1647         return &track_region_context_menu;
1648 }
1649
1650 Menu*
1651 Editor::build_track_crossfade_context_menu (nframes64_t frame)
1652 {
1653         using namespace Menu_Helpers;
1654         MenuList& edit_items  = track_crossfade_context_menu.items();
1655         edit_items.clear ();
1656
1657         AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*> (clicked_trackview);
1658
1659         if (atv) {
1660                 boost::shared_ptr<Diskstream> ds;
1661                 boost::shared_ptr<Playlist> pl;
1662                 boost::shared_ptr<AudioPlaylist> apl;
1663
1664                 if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()) != 0) && ((apl = boost::dynamic_pointer_cast<AudioPlaylist> (pl)) != 0)) {
1665
1666                         Playlist::RegionList* regions = pl->regions_at (frame);
1667                         AudioPlaylist::Crossfades xfades;
1668
1669                         apl->crossfades_at (frame, xfades);
1670
1671                         bool many = xfades.size() > 1;
1672
1673                         for (AudioPlaylist::Crossfades::iterator i = xfades.begin(); i != xfades.end(); ++i) {
1674                                 add_crossfade_context_items (atv->audio_view(), (*i), edit_items, many);
1675                         }
1676
1677                         if (selection->regions.size() > 1) {
1678                                 // there's already a multiple selection: just add a 
1679                                 // single region context menu that will act on all 
1680                                 // selected regions
1681                                 boost::shared_ptr<Region> dummy_region; // = NULL               
1682                                 add_region_context_items (atv->audio_view(), dummy_region, edit_items);                 
1683                         } else {
1684                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
1685                                         add_region_context_items (atv->audio_view(), (*i), edit_items);
1686                                 }
1687                         }
1688                         delete regions;
1689                 }
1690         }
1691
1692         add_dstream_context_items (edit_items);
1693
1694         return &track_crossfade_context_menu;
1695 }
1696
1697 #ifdef FFT_ANALYSIS
1698 void
1699 Editor::analyze_region_selection()
1700 {
1701         if (analysis_window == 0) {
1702                 analysis_window = new AnalysisWindow();
1703
1704                 if (session != 0)
1705                         analysis_window->set_session(session);
1706
1707                 analysis_window->show_all();
1708         }
1709
1710         analysis_window->set_regionmode();
1711         analysis_window->analyze();
1712         
1713         analysis_window->present();
1714 }
1715
1716 void
1717 Editor::analyze_range_selection()
1718 {
1719         if (analysis_window == 0) {
1720                 analysis_window = new AnalysisWindow();
1721
1722                 if (session != 0)
1723                         analysis_window->set_session(session);
1724
1725                 analysis_window->show_all();
1726         }
1727
1728         analysis_window->set_rangemode();
1729         analysis_window->analyze();
1730         
1731         analysis_window->present();
1732 }
1733 #endif /* FFT_ANALYSIS */
1734
1735
1736
1737 Menu*
1738 Editor::build_track_selection_context_menu (nframes64_t ignored)
1739 {
1740         using namespace Menu_Helpers;
1741         MenuList& edit_items  = track_selection_context_menu.items();
1742         edit_items.clear ();
1743
1744         add_selection_context_items (edit_items);
1745         // edit_items.push_back (SeparatorElem());
1746         // add_dstream_context_items (edit_items);
1747
1748         return &track_selection_context_menu;
1749 }
1750
1751 void
1752 Editor::add_crossfade_context_items (AudioStreamView* view, boost::shared_ptr<Crossfade> xfade, Menu_Helpers::MenuList& edit_items, bool many)
1753 {
1754         using namespace Menu_Helpers;
1755         Menu     *xfade_menu = manage (new Menu);
1756         MenuList& items       = xfade_menu->items();
1757         xfade_menu->set_name ("ArdourContextMenu");
1758         string str;
1759
1760         if (xfade->active()) {
1761                 str = _("Mute");
1762         } else { 
1763                 str = _("Unmute");
1764         }
1765
1766         items.push_back (MenuElem (str, bind (mem_fun(*this, &Editor::toggle_xfade_active), boost::weak_ptr<Crossfade> (xfade))));
1767         items.push_back (MenuElem (_("Edit"), bind (mem_fun(*this, &Editor::edit_xfade), boost::weak_ptr<Crossfade> (xfade))));
1768
1769         if (xfade->can_follow_overlap()) {
1770
1771                 if (xfade->following_overlap()) {
1772                         str = _("Convert to short");
1773                 } else {
1774                         str = _("Convert to full");
1775                 }
1776
1777                 items.push_back (MenuElem (str, bind (mem_fun(*this, &Editor::toggle_xfade_length), xfade)));
1778         }
1779
1780         if (many) {
1781                 str = xfade->out()->name();
1782                 str += "->";
1783                 str += xfade->in()->name();
1784         } else {
1785                 str = _("Crossfade");
1786         }
1787
1788         edit_items.push_back (MenuElem (str, *xfade_menu));
1789         edit_items.push_back (SeparatorElem());
1790 }
1791
1792 void
1793 Editor::xfade_edit_left_region ()
1794 {
1795         if (clicked_crossfadeview) {
1796                 clicked_crossfadeview->left_view.show_region_editor ();
1797         }
1798 }
1799
1800 void
1801 Editor::xfade_edit_right_region ()
1802 {
1803         if (clicked_crossfadeview) {
1804                 clicked_crossfadeview->right_view.show_region_editor ();
1805         }
1806 }
1807
1808 void
1809 Editor::add_region_context_items (AudioStreamView* sv, boost::shared_ptr<Region> region, Menu_Helpers::MenuList& edit_items)
1810 {
1811         using namespace Menu_Helpers;
1812         Menu     *region_menu = manage (new Menu);
1813         MenuList& items       = region_menu->items();
1814         region_menu->set_name ("ArdourContextMenu");
1815         
1816         boost::shared_ptr<AudioRegion> ar;
1817
1818         if (region) {
1819                 ar = boost::dynamic_pointer_cast<AudioRegion> (region);
1820
1821                 /* when this particular menu pops up, make the relevant region 
1822                    become selected.
1823                 */
1824
1825                 region_menu->signal_map_event().connect (
1826                         bind (
1827                                 mem_fun(*this, &Editor::set_selected_regionview_from_map_event), 
1828                                 sv, 
1829                                 boost::weak_ptr<Region>(region)
1830                         )
1831                 );
1832
1833                 items.push_back (MenuElem (_("Rename"), mem_fun(*this, &Editor::rename_region)));
1834                 items.push_back (MenuElem (_("Popup region editor"), mem_fun(*this, &Editor::edit_region)));
1835         }
1836
1837         items.push_back (MenuElem (_("Raise to top layer"), mem_fun(*this, &Editor::raise_region_to_top)));
1838         items.push_back (MenuElem (_("Lower to bottom layer"), mem_fun  (*this, &Editor::lower_region_to_bottom)));
1839         items.push_back (SeparatorElem());
1840         items.push_back (MenuElem (_("Define sync point"), mem_fun(*this, &Editor::set_region_sync_from_edit_point)));
1841         items.push_back (MenuElem (_("Remove sync point"), mem_fun(*this, &Editor::remove_region_sync)));
1842         items.push_back (SeparatorElem());
1843
1844         items.push_back (MenuElem (_("Audition"), mem_fun(*this, &Editor::play_selected_region)));
1845         items.push_back (MenuElem (_("Export"), mem_fun(*this, &Editor::export_region)));
1846         items.push_back (MenuElem (_("Bounce"), mem_fun(*this, &Editor::bounce_region_selection)));
1847
1848 #ifdef FFT_ANALYSIS
1849         items.push_back (MenuElem (_("Spectral Analysis"), mem_fun(*this, &Editor::analyze_region_selection)));
1850 #endif
1851
1852         items.push_back (SeparatorElem());
1853
1854         sigc::connection fooc;
1855         boost::shared_ptr<Region> region_to_check;
1856
1857         if (region) {
1858                 region_to_check = region;
1859         } else {
1860                 region_to_check = selection->regions.front()->region();
1861         }
1862
1863         items.push_back (CheckMenuElem (_("Lock")));
1864         CheckMenuItem* region_lock_item = static_cast<CheckMenuItem*>(&items.back());
1865         if (region_to_check->locked()) {
1866                 region_lock_item->set_active();
1867         }
1868         region_lock_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_region_lock));
1869         
1870         items.push_back (CheckMenuElem (_("Glue to Bars&Beats")));
1871         CheckMenuItem* bbt_glue_item = static_cast<CheckMenuItem*>(&items.back());
1872         
1873         switch (region_to_check->positional_lock_style()) {
1874         case Region::MusicTime:
1875                 bbt_glue_item->set_active (true);
1876                 break;
1877         default:
1878                 bbt_glue_item->set_active (false);
1879                 break;
1880         }
1881         
1882         bbt_glue_item->signal_activate().connect (bind (mem_fun (*this, &Editor::set_region_lock_style), Region::MusicTime));
1883         
1884         items.push_back (CheckMenuElem (_("Mute")));
1885         CheckMenuItem* region_mute_item = static_cast<CheckMenuItem*>(&items.back());
1886         fooc = region_mute_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_region_mute));
1887         if (region_to_check->muted()) {
1888                 fooc.block (true);
1889                 region_mute_item->set_active();
1890                 fooc.block (false);
1891         }
1892         
1893         if (!Profile->get_sae()) {
1894                 items.push_back (CheckMenuElem (_("Opaque")));
1895                 CheckMenuItem* region_opaque_item = static_cast<CheckMenuItem*>(&items.back());
1896                 fooc = region_opaque_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_region_opaque));
1897                 if (region_to_check->opaque()) {
1898                         fooc.block (true);
1899                         region_opaque_item->set_active();
1900                         fooc.block (false);
1901                 }
1902         }
1903         
1904         items.push_back (CheckMenuElem (_("Original position"), mem_fun(*this, &Editor::naturalize)));
1905         if (region_to_check->at_natural_position()) {
1906                 items.back().set_sensitive (false);
1907         }
1908         
1909         items.push_back (SeparatorElem());
1910         
1911         if (ar) {
1912                 
1913                 RegionView* rv = sv->find_view (ar);
1914                 AudioRegionView* arv = dynamic_cast<AudioRegionView*>(rv);
1915                 
1916                 if (!Profile->get_sae()) {
1917                         items.push_back (MenuElem (_("Reset Envelope"), mem_fun(*this, &Editor::reset_region_gain_envelopes)));
1918
1919                         items.push_back (CheckMenuElem (_("Envelope Visible")));
1920                         CheckMenuItem* region_envelope_visible_item = static_cast<CheckMenuItem*> (&items.back());
1921                         fooc = region_envelope_visible_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_gain_envelope_visibility));
1922                         if (arv->envelope_visible()) {
1923                                 fooc.block (true);
1924                                 region_envelope_visible_item->set_active (true);
1925                                 fooc.block (false);
1926                         }
1927                 
1928                         items.push_back (CheckMenuElem (_("Envelope Active")));
1929                         CheckMenuItem* region_envelope_active_item = static_cast<CheckMenuItem*> (&items.back());
1930                         fooc = region_envelope_active_item->signal_activate().connect (mem_fun(*this, &Editor::toggle_gain_envelope_active));
1931                         
1932                         if (ar->envelope_active()) {
1933                                 fooc.block (true);
1934                                 region_envelope_active_item->set_active (true);
1935                                 fooc.block (false);
1936                         }
1937
1938                         items.push_back (SeparatorElem());
1939                 }
1940
1941                 if (ar->scale_amplitude() != 1.0f) {
1942                         items.push_back (MenuElem (_("DeNormalize"), mem_fun(*this, &Editor::denormalize_region)));
1943                 } else {
1944                         items.push_back (MenuElem (_("Normalize"), mem_fun(*this, &Editor::normalize_region)));
1945                 }
1946         }
1947
1948         items.push_back (MenuElem (_("Reverse"), mem_fun(*this, &Editor::reverse_region)));
1949         items.push_back (SeparatorElem());
1950
1951         /* range related stuff */
1952
1953         items.push_back (MenuElem (_("Add Range Markers"), mem_fun (*this, &Editor::add_location_from_audio_region)));
1954         items.push_back (MenuElem (_("Set Range Selection"), mem_fun (*this, &Editor::set_selection_from_audio_region)));
1955         items.push_back (SeparatorElem());
1956                          
1957         /* Nudge region */
1958
1959         Menu *nudge_menu = manage (new Menu());
1960         MenuList& nudge_items = nudge_menu->items();
1961         nudge_menu->set_name ("ArdourContextMenu");
1962         
1963         nudge_items.push_back (MenuElem (_("Nudge fwd"), (bind (mem_fun(*this, &Editor::nudge_forward), false, false))));
1964         nudge_items.push_back (MenuElem (_("Nudge bwd"), (bind (mem_fun(*this, &Editor::nudge_backward), false, false))));
1965         nudge_items.push_back (MenuElem (_("Nudge fwd by capture offset"), (mem_fun(*this, &Editor::nudge_forward_capture_offset))));
1966         nudge_items.push_back (MenuElem (_("Nudge bwd by capture offset"), (mem_fun(*this, &Editor::nudge_backward_capture_offset))));
1967
1968         items.push_back (MenuElem (_("Nudge"), *nudge_menu));
1969         items.push_back (SeparatorElem());
1970
1971         Menu *trim_menu = manage (new Menu);
1972         MenuList& trim_items = trim_menu->items();
1973         trim_menu->set_name ("ArdourContextMenu");
1974         
1975         trim_items.push_back (MenuElem (_("Start to edit point"), mem_fun(*this, &Editor::trim_region_from_edit_point)));
1976         trim_items.push_back (MenuElem (_("Edit point to end"), mem_fun(*this, &Editor::trim_region_to_edit_point)));
1977         trim_items.push_back (MenuElem (_("Trim To Loop"), mem_fun(*this, &Editor::trim_region_to_loop)));
1978         trim_items.push_back (MenuElem (_("Trim To Punch"), mem_fun(*this, &Editor::trim_region_to_punch)));
1979                              
1980         items.push_back (MenuElem (_("Trim"), *trim_menu));
1981         items.push_back (SeparatorElem());
1982
1983         items.push_back (MenuElem (_("Split"), (mem_fun(*this, &Editor::split_region))));
1984         region_edit_menu_split_item = &items.back();
1985
1986         items.push_back (MenuElem (_("Make mono regions"), (mem_fun(*this, &Editor::split_multichannel_region))));
1987         region_edit_menu_split_multichannel_item = &items.back();
1988
1989         items.push_back (MenuElem (_("Duplicate"), (bind (mem_fun(*this, &Editor::duplicate_dialog), false))));
1990         items.push_back (MenuElem (_("Multi-Duplicate"), (bind (mem_fun(*this, &Editor::duplicate_dialog), true))));
1991         items.push_back (MenuElem (_("Fill Track"), (mem_fun(*this, &Editor::region_fill_track))));
1992         items.push_back (SeparatorElem());
1993         items.push_back (MenuElem (_("Remove"), mem_fun(*this, &Editor::remove_region)));
1994
1995         /* OK, stick the region submenu at the top of the list, and then add
1996            the standard items.
1997         */
1998
1999         /* we have to hack up the region name because "_" has a special
2000            meaning for menu titles.
2001         */
2002
2003         string::size_type pos = 0;
2004         string menu_item_name = (region) ? region->name() : _("Selected regions");
2005
2006         while ((pos = menu_item_name.find ("_", pos)) != string::npos) {
2007                 menu_item_name.replace (pos, 1, "__");
2008                 pos += 2;
2009         }
2010         
2011         edit_items.push_back (MenuElem (menu_item_name, *region_menu));
2012         edit_items.push_back (SeparatorElem());
2013 }
2014
2015 void
2016 Editor::add_selection_context_items (Menu_Helpers::MenuList& items)
2017 {
2018         using namespace Menu_Helpers;
2019
2020         items.push_back (MenuElem (_("Play range"), mem_fun(*this, &Editor::play_selection)));
2021         items.push_back (MenuElem (_("Loop range"), bind (mem_fun(*this, &Editor::set_loop_from_selection), true)));
2022
2023 #ifdef FFT_ANALYSIS
2024         items.push_back (SeparatorElem());
2025         items.push_back (MenuElem (_("Spectral Analysis"), mem_fun(*this, &Editor::analyze_range_selection)));
2026 #endif
2027         
2028         items.push_back (SeparatorElem());
2029         items.push_back (MenuElem (_("Extend Range to End of Region"), bind (mem_fun(*this, &Editor::extend_selection_to_end_of_region), false)));
2030         items.push_back (MenuElem (_("Extend Range to Start of Region"), bind (mem_fun(*this, &Editor::extend_selection_to_start_of_region), false)));
2031
2032         items.push_back (SeparatorElem());
2033         items.push_back (MenuElem (_("Convert to region in-place"), mem_fun(*this, &Editor::separate_region_from_selection)));
2034         items.push_back (MenuElem (_("Convert to region in region list"), mem_fun(*this, &Editor::new_region_from_selection)));
2035         
2036         items.push_back (SeparatorElem());
2037         items.push_back (MenuElem (_("Select all in range"), mem_fun(*this, &Editor::select_all_selectables_using_time_selection)));
2038
2039         items.push_back (SeparatorElem());
2040         items.push_back (MenuElem (_("Set loop from selection"), bind (mem_fun(*this, &Editor::set_loop_from_selection), false)));
2041         items.push_back (MenuElem (_("Set punch from selection"), mem_fun(*this, &Editor::set_punch_from_selection)));
2042         
2043         items.push_back (SeparatorElem());
2044         items.push_back (MenuElem (_("Add Range Markers"), mem_fun (*this, &Editor::add_location_from_selection)));
2045         items.push_back (SeparatorElem());
2046         items.push_back (MenuElem (_("Crop region to range"), mem_fun(*this, &Editor::crop_region_to_selection)));
2047         items.push_back (MenuElem (_("Fill range with region"), mem_fun(*this, &Editor::region_fill_selection)));
2048         items.push_back (MenuElem (_("Duplicate range"), bind (mem_fun(*this, &Editor::duplicate_dialog), false)));
2049         items.push_back (MenuElem (_("Create chunk from range"), mem_fun(*this, &Editor::create_named_selection)));
2050         items.push_back (SeparatorElem());
2051         items.push_back (MenuElem (_("Consolidate range"), bind (mem_fun(*this, &Editor::bounce_range_selection), true)));
2052         items.push_back (MenuElem (_("Bounce range to region list"), bind (mem_fun(*this, &Editor::bounce_range_selection), false)));
2053         items.push_back (MenuElem (_("Export range"), mem_fun(*this, &Editor::export_selection)));
2054 }
2055
2056 void
2057 Editor::add_dstream_context_items (Menu_Helpers::MenuList& edit_items)
2058 {
2059         using namespace Menu_Helpers;
2060
2061         /* Playback */
2062
2063         Menu *play_menu = manage (new Menu);
2064         MenuList& play_items = play_menu->items();
2065         play_menu->set_name ("ArdourContextMenu");
2066         
2067         play_items.push_back (MenuElem (_("Play from edit point"), mem_fun(*this, &Editor::play_from_edit_point)));
2068         play_items.push_back (MenuElem (_("Play from start"), mem_fun(*this, &Editor::play_from_start)));
2069         play_items.push_back (MenuElem (_("Play region"), mem_fun(*this, &Editor::play_selected_region)));
2070         play_items.push_back (SeparatorElem());
2071         play_items.push_back (MenuElem (_("Loop Region"), mem_fun(*this, &Editor::loop_selected_region)));
2072         
2073         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2074
2075         /* Selection */
2076
2077         Menu *select_menu = manage (new Menu);
2078         MenuList& select_items = select_menu->items();
2079         select_menu->set_name ("ArdourContextMenu");
2080         
2081         select_items.push_back (MenuElem (_("Select All in track"), bind (mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2082         select_items.push_back (MenuElem (_("Select All"), bind (mem_fun(*this, &Editor::select_all), Selection::Set)));
2083         select_items.push_back (MenuElem (_("Invert selection in track"), mem_fun(*this, &Editor::invert_selection_in_track)));
2084         select_items.push_back (MenuElem (_("Invert selection"), mem_fun(*this, &Editor::invert_selection)));
2085         select_items.push_back (SeparatorElem());
2086         select_items.push_back (MenuElem (_("Set range to loop range"), mem_fun(*this, &Editor::set_selection_from_loop)));
2087         select_items.push_back (MenuElem (_("Set range to punch range"), mem_fun(*this, &Editor::set_selection_from_punch)));
2088         select_items.push_back (SeparatorElem());
2089         select_items.push_back (MenuElem (_("Select All After Edit Point"), bind (mem_fun(*this, &Editor::select_all_selectables_using_edit), true)));
2090         select_items.push_back (MenuElem (_("Select All Before Edit Point"), bind (mem_fun(*this, &Editor::select_all_selectables_using_edit), false)));
2091         select_items.push_back (MenuElem (_("Select All After Playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2092         select_items.push_back (MenuElem (_("Select All Before Playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2093         select_items.push_back (MenuElem (_("Select All Between Playhead & Edit Point"), bind (mem_fun(*this, &Editor::select_all_selectables_between), false)));
2094         select_items.push_back (MenuElem (_("Select All Within Playhead & Edit Point"), bind (mem_fun(*this, &Editor::select_all_selectables_between), true)));
2095         select_items.push_back (MenuElem (_("Select Range Between Playhead & Edit Point"), mem_fun(*this, &Editor::select_range_between)));
2096
2097         select_items.push_back (SeparatorElem());
2098
2099         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2100
2101         /* Cut-n-Paste */
2102
2103         Menu *cutnpaste_menu = manage (new Menu);
2104         MenuList& cutnpaste_items = cutnpaste_menu->items();
2105         cutnpaste_menu->set_name ("ArdourContextMenu");
2106         
2107         cutnpaste_items.push_back (MenuElem (_("Cut"), mem_fun(*this, &Editor::cut)));
2108         cutnpaste_items.push_back (MenuElem (_("Copy"), mem_fun(*this, &Editor::copy)));
2109         cutnpaste_items.push_back (MenuElem (_("Paste"), bind (mem_fun(*this, &Editor::paste), 1.0f)));
2110
2111         cutnpaste_items.push_back (SeparatorElem());
2112
2113         cutnpaste_items.push_back (MenuElem (_("Align"), bind (mem_fun(*this, &Editor::align), ARDOUR::SyncPoint)));
2114         cutnpaste_items.push_back (MenuElem (_("Align Relative"), bind (mem_fun(*this, &Editor::align_relative), ARDOUR::SyncPoint)));
2115
2116         cutnpaste_items.push_back (SeparatorElem());
2117
2118         cutnpaste_items.push_back (MenuElem (_("Insert chunk"), bind (mem_fun(*this, &Editor::paste_named_selection), 1.0f)));
2119
2120         edit_items.push_back (MenuElem (_("Edit"), *cutnpaste_menu));
2121
2122         /* Adding new material */
2123         
2124         edit_items.push_back (SeparatorElem());
2125         edit_items.push_back (MenuElem (_("Insert Selected Region"), bind (mem_fun(*this, &Editor::insert_region_list_selection), 1.0f)));
2126         edit_items.push_back (MenuElem (_("Insert Existing Audio"), bind (mem_fun(*this, &Editor::add_external_audio_action), ImportToTrack)));
2127
2128         /* Nudge track */
2129
2130         Menu *nudge_menu = manage (new Menu());
2131         MenuList& nudge_items = nudge_menu->items();
2132         nudge_menu->set_name ("ArdourContextMenu");
2133         
2134         edit_items.push_back (SeparatorElem());
2135         nudge_items.push_back (MenuElem (_("Nudge entire track fwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, true))));
2136         nudge_items.push_back (MenuElem (_("Nudge track after edit point fwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, true))));
2137         nudge_items.push_back (MenuElem (_("Nudge entire track bwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, false))));
2138         nudge_items.push_back (MenuElem (_("Nudge track after edit point bwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, false))));
2139
2140         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2141 }
2142
2143 void
2144 Editor::add_bus_context_items (Menu_Helpers::MenuList& edit_items)
2145 {
2146         using namespace Menu_Helpers;
2147
2148         /* Playback */
2149
2150         Menu *play_menu = manage (new Menu);
2151         MenuList& play_items = play_menu->items();
2152         play_menu->set_name ("ArdourContextMenu");
2153         
2154         play_items.push_back (MenuElem (_("Play from edit point"), mem_fun(*this, &Editor::play_from_edit_point)));
2155         play_items.push_back (MenuElem (_("Play from start"), mem_fun(*this, &Editor::play_from_start)));
2156         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2157
2158         /* Selection */
2159
2160         Menu *select_menu = manage (new Menu);
2161         MenuList& select_items = select_menu->items();
2162         select_menu->set_name ("ArdourContextMenu");
2163         
2164         select_items.push_back (MenuElem (_("Select All in track"), bind (mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2165         select_items.push_back (MenuElem (_("Select All"), bind (mem_fun(*this, &Editor::select_all), Selection::Set)));
2166         select_items.push_back (MenuElem (_("Invert selection in track"), mem_fun(*this, &Editor::invert_selection_in_track)));
2167         select_items.push_back (MenuElem (_("Invert selection"), mem_fun(*this, &Editor::invert_selection)));
2168         select_items.push_back (SeparatorElem());
2169         select_items.push_back (MenuElem (_("Select all after edit point"), bind (mem_fun(*this, &Editor::select_all_selectables_using_edit), true)));
2170         select_items.push_back (MenuElem (_("Select all before edit point"), bind (mem_fun(*this, &Editor::select_all_selectables_using_edit), false)));
2171         select_items.push_back (MenuElem (_("Select all after playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2172         select_items.push_back (MenuElem (_("Select all before playhead"), bind (mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2173
2174         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2175
2176         /* Cut-n-Paste */
2177
2178         Menu *cutnpaste_menu = manage (new Menu);
2179         MenuList& cutnpaste_items = cutnpaste_menu->items();
2180         cutnpaste_menu->set_name ("ArdourContextMenu");
2181         
2182         cutnpaste_items.push_back (MenuElem (_("Cut"), mem_fun(*this, &Editor::cut)));
2183         cutnpaste_items.push_back (MenuElem (_("Copy"), mem_fun(*this, &Editor::copy)));
2184         cutnpaste_items.push_back (MenuElem (_("Paste"), bind (mem_fun(*this, &Editor::paste), 1.0f)));
2185
2186         Menu *nudge_menu = manage (new Menu());
2187         MenuList& nudge_items = nudge_menu->items();
2188         nudge_menu->set_name ("ArdourContextMenu");
2189         
2190         edit_items.push_back (SeparatorElem());
2191         nudge_items.push_back (MenuElem (_("Nudge entire track fwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, true))));
2192         nudge_items.push_back (MenuElem (_("Nudge track after edit point fwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, true))));
2193         nudge_items.push_back (MenuElem (_("Nudge entire track bwd"), (bind (mem_fun(*this, &Editor::nudge_track), false, false))));
2194         nudge_items.push_back (MenuElem (_("Nudge track after edit point bwd"), (bind (mem_fun(*this, &Editor::nudge_track), true, false))));
2195
2196         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2197 }
2198
2199 void
2200 Editor::set_snap_to (SnapType st)
2201 {
2202         unsigned int snap_ind = (unsigned int)st;
2203         snap_type = st;
2204         
2205         if (snap_ind > snap_type_strings.size() - 1) {
2206                 snap_ind = 0;
2207                 snap_type = (SnapType)snap_ind;
2208         }
2209         
2210         string str = snap_type_strings[snap_ind];
2211
2212         if (str != snap_type_selector.get_active_text()) {
2213                 snap_type_selector.set_active_text (str);
2214         }
2215
2216         instant_save ();
2217
2218         switch (snap_type) {
2219         case SnapToAThirtysecondBeat:
2220         case SnapToASixteenthBeat:
2221         case SnapToAEighthBeat:
2222         case SnapToAQuarterBeat:
2223         case SnapToAThirdBeat:
2224                 update_tempo_based_rulers ();
2225                 break;
2226
2227         case SnapToRegionStart:
2228         case SnapToRegionEnd:
2229         case SnapToRegionSync:
2230         case SnapToRegionBoundary:
2231                 build_region_boundary_cache ();
2232                 break;
2233
2234         default:
2235                 /* relax */
2236                 break;
2237     }
2238 }
2239
2240 void
2241 Editor::set_snap_mode (SnapMode mode)
2242 {
2243         snap_mode = mode;
2244         string str = snap_mode_strings[(int)mode];
2245
2246         if (str != snap_mode_selector.get_active_text ()) {
2247                 snap_mode_selector.set_active_text (str);
2248         }
2249
2250         instant_save ();
2251 }
2252 void
2253 Editor::set_edit_point_preference (EditPoint ep, bool force)
2254 {
2255         bool changed = (_edit_point != ep);
2256
2257         _edit_point = ep;
2258         string str = edit_point_strings[(int)ep];
2259
2260         if (str != edit_point_selector.get_active_text ()) {
2261                 edit_point_selector.set_active_text (str);
2262         }
2263
2264         set_canvas_cursor ();
2265
2266         if (!force && !changed) {
2267                 return;
2268         }
2269
2270         switch (zoom_focus) {
2271         case ZoomFocusMouse:
2272         case ZoomFocusPlayhead:
2273         case ZoomFocusEdit:
2274                 switch (_edit_point) {
2275                 case EditAtMouse:
2276                         set_zoom_focus (ZoomFocusMouse);
2277                         break;
2278                 case EditAtPlayhead:
2279                         set_zoom_focus (ZoomFocusPlayhead);
2280                         break;
2281                 case EditAtSelectedMarker:
2282                         set_zoom_focus (ZoomFocusEdit);
2283                         break;
2284                 }
2285                 break;
2286         default:
2287                 break;
2288         }
2289
2290         const char* action=NULL;
2291
2292         switch (_edit_point) {
2293         case EditAtPlayhead:
2294                 action = "edit-at-playhead";
2295                 break;
2296         case EditAtSelectedMarker:
2297                 action = "edit-at-marker";
2298                 break;
2299         case EditAtMouse:
2300                 action = "edit-at-mouse";
2301                 break;
2302         }
2303
2304         Glib::RefPtr<Action> act = ActionManager::get_action ("Editor", action);
2305         if (act) {
2306                 Glib::RefPtr<RadioAction>::cast_dynamic(act)->set_active (true);
2307         }
2308
2309         nframes64_t foo;
2310         bool in_track_canvas;
2311
2312         if (!mouse_frame (foo, in_track_canvas)) {
2313                 in_track_canvas = false;
2314         }
2315
2316         reset_canvas_action_sensitivity (in_track_canvas);
2317
2318         instant_save ();
2319 }
2320
2321 int
2322 Editor::set_state (const XMLNode& node)
2323 {
2324         const XMLProperty* prop;
2325         XMLNode* geometry;
2326         int x, y, xoff, yoff;
2327         Gdk::Geometry g;
2328
2329         if ((prop = node.property ("id")) != 0) {
2330                 _id = prop->value ();
2331         }
2332
2333         if ((geometry = find_named_node (node, "geometry")) == 0) {
2334
2335                 g.base_width = default_width;
2336                 g.base_height = default_height;
2337                 x = 1;
2338                 y = 1;
2339                 xoff = 0;
2340                 yoff = 21;
2341
2342         } else {
2343
2344                 g.base_width = atoi(geometry->property("x_size")->value());
2345                 g.base_height = atoi(geometry->property("y_size")->value());
2346                 x = atoi(geometry->property("x_pos")->value());
2347                 y = atoi(geometry->property("y_pos")->value());
2348                 xoff = atoi(geometry->property("x_off")->value());
2349                 yoff = atoi(geometry->property("y_off")->value());
2350         }
2351
2352         set_default_size (g.base_width, g.base_height);
2353         move (x, y);
2354
2355         if (session && (prop = node.property ("playhead"))) {
2356                 nframes64_t pos = atol (prop->value().c_str());
2357                 playhead_cursor->set_position (pos);
2358         } else {
2359                 playhead_cursor->set_position (0);
2360
2361                 /* reset_x_origin() doesn't work right here, since the old
2362                    position may be zero already, and it does nothing in such
2363                    circumstances.
2364                 */
2365                 
2366                 leftmost_frame = 0;
2367                 horizontal_adjustment.set_value (0);
2368         }
2369
2370         if ((prop = node.property ("mixer-width"))) {
2371                 editor_mixer_strip_width = Width (string_2_enum (prop->value(), editor_mixer_strip_width));
2372         }
2373
2374         if ((prop = node.property ("zoom-focus"))) {
2375                 set_zoom_focus ((ZoomFocus) atoi (prop->value()));
2376         }
2377
2378         if ((prop = node.property ("zoom"))) {
2379                 reset_zoom (PBD::atof (prop->value()));
2380         }
2381
2382         if ((prop = node.property ("snap-to"))) {
2383                 set_snap_to ((SnapType) atoi (prop->value()));
2384         }
2385
2386         if ((prop = node.property ("snap-mode"))) {
2387                 set_snap_mode ((SnapMode) atoi (prop->value()));
2388         }
2389
2390         if ((prop = node.property ("edit-point"))) {
2391                 set_edit_point_preference ((EditPoint) string_2_enum (prop->value(), _edit_point), true);
2392         }
2393
2394         if ((prop = node.property ("mouse-mode"))) {
2395                 MouseMode m = str2mousemode(prop->value());
2396                 mouse_mode = MouseMode ((int) m + 1); /* lie, force mode switch */
2397                 set_mouse_mode (m, true);
2398         } else {
2399                 mouse_mode = MouseGain; /* lie, to force the mode switch */
2400                 set_mouse_mode (MouseObject, true);
2401         }
2402
2403         if ((prop = node.property ("show-waveforms"))) {
2404                 bool yn = (prop->value() == "yes");
2405                 _show_waveforms = !yn;
2406                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-waveform-visible"));
2407                 if (act) {
2408                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2409                         /* do it twice to force the change */
2410                         tact->set_active (!yn);
2411                         tact->set_active (yn);
2412                 }
2413         }
2414
2415         if ((prop = node.property ("show-waveforms-recording"))) {
2416                 bool yn = (prop->value() == "yes");
2417                 _show_waveforms_recording = !yn;
2418                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleWaveformsWhileRecording"));
2419                 if (act) {
2420                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2421                         /* do it twice to force the change */
2422                         tact->set_active (!yn);
2423                         tact->set_active (yn);
2424                 }
2425         }
2426         
2427         if ((prop = node.property ("show-measures"))) {
2428                 bool yn = (prop->value() == "yes");
2429                 _show_measures = !yn;
2430                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleMeasureVisibility"));
2431                 if (act) {
2432                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2433                         /* do it twice to force the change */
2434                         tact->set_active (!yn);
2435                         tact->set_active (yn);
2436                 }
2437         }
2438
2439         if ((prop = node.property ("follow-playhead"))) {
2440                 bool yn = (prop->value() == "yes");
2441                 set_follow_playhead (yn);
2442                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
2443                 if (act) {
2444                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2445                         if (tact->get_active() != yn) {
2446                                 tact->set_active (yn);
2447                         }
2448                 }
2449         }
2450
2451         if ((prop = node.property ("region-list-sort-type"))) {
2452                 region_list_sort_type = (Editing::RegionListSortType) -1; // force change 
2453                 reset_region_list_sort_type(str2regionlistsorttype(prop->value()));
2454         }
2455
2456         if ((prop = node.property ("xfades-visible"))) {
2457                 bool yn = (prop->value() == "yes");
2458                 _xfade_visibility = !yn;
2459                 // set_xfade_visibility (yn);
2460         }
2461
2462         if ((prop = node.property ("show-editor-mixer"))) {
2463
2464                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2465                 if (act) {
2466
2467                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2468                         bool yn = (prop->value() == X_("yes"));
2469
2470                         /* do it twice to force the change */
2471                         
2472                         tact->set_active (!yn);
2473                         tact->set_active (yn);
2474                 }
2475         }
2476
2477
2478         return 0;
2479 }
2480
2481 XMLNode&
2482 Editor::get_state ()
2483 {
2484         XMLNode* node = new XMLNode ("Editor");
2485         char buf[32];
2486
2487         _id.print (buf, sizeof (buf));
2488         node->add_property ("id", buf);
2489         
2490         if (is_realized()) {
2491                 Glib::RefPtr<Gdk::Window> win = get_window();
2492                 
2493                 int x, y, xoff, yoff, width, height;
2494                 win->get_root_origin(x, y);
2495                 win->get_position(xoff, yoff);
2496                 win->get_size(width, height);
2497                 
2498                 XMLNode* geometry = new XMLNode ("geometry");
2499
2500                 snprintf(buf, sizeof(buf), "%d", width);
2501                 geometry->add_property("x_size", string(buf));
2502                 snprintf(buf, sizeof(buf), "%d", height);
2503                 geometry->add_property("y_size", string(buf));
2504                 snprintf(buf, sizeof(buf), "%d", x);
2505                 geometry->add_property("x_pos", string(buf));
2506                 snprintf(buf, sizeof(buf), "%d", y);
2507                 geometry->add_property("y_pos", string(buf));
2508                 snprintf(buf, sizeof(buf), "%d", xoff);
2509                 geometry->add_property("x_off", string(buf));
2510                 snprintf(buf, sizeof(buf), "%d", yoff);
2511                 geometry->add_property("y_off", string(buf));
2512                 snprintf(buf,sizeof(buf), "%d",gtk_paned_get_position (static_cast<Paned*>(&edit_pane)->gobj()));
2513                 geometry->add_property("edit_pane_pos", string(buf));
2514
2515                 node->add_child_nocopy (*geometry);
2516         }
2517
2518         maybe_add_mixer_strip_width (*node);
2519         
2520         snprintf (buf, sizeof(buf), "%d", (int) zoom_focus);
2521         node->add_property ("zoom-focus", buf);
2522         snprintf (buf, sizeof(buf), "%f", frames_per_unit);
2523         node->add_property ("zoom", buf);
2524         snprintf (buf, sizeof(buf), "%d", (int) snap_type);
2525         node->add_property ("snap-to", buf);
2526         snprintf (buf, sizeof(buf), "%d", (int) snap_mode);
2527         node->add_property ("snap-mode", buf);
2528
2529         node->add_property ("edit-point", enum_2_string (_edit_point));
2530
2531         snprintf (buf, sizeof (buf), "%" PRIi64, playhead_cursor->current_frame);
2532         node->add_property ("playhead", buf);
2533
2534         node->add_property ("show-waveforms", _show_waveforms ? "yes" : "no");
2535         node->add_property ("show-waveforms-recording", _show_waveforms_recording ? "yes" : "no");
2536         node->add_property ("show-measures", _show_measures ? "yes" : "no");
2537         node->add_property ("follow-playhead", _follow_playhead ? "yes" : "no");
2538         node->add_property ("xfades-visible", _xfade_visibility ? "yes" : "no");
2539         node->add_property ("region-list-sort-type", enum2str(region_list_sort_type));
2540         node->add_property ("mouse-mode", enum2str(mouse_mode));
2541         
2542         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2543         if (act) {
2544                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2545                 node->add_property (X_("show-editor-mixer"), tact->get_active() ? "yes" : "no");
2546         }
2547
2548         return *node;
2549 }
2550
2551
2552
2553 TimeAxisView *
2554 Editor::trackview_by_y_position (double y)
2555 {
2556         for (TrackViewList::iterator iter = track_views.begin(); iter != track_views.end(); ++iter) {
2557
2558                 TimeAxisView *tv;
2559
2560                 if ((tv = (*iter)->covers_y_position (y)) != 0) {
2561                         return tv;
2562                 }
2563         }
2564
2565         return 0;
2566 }
2567
2568 void
2569 Editor::snap_to (nframes64_t& start, int32_t direction, bool for_mark)
2570 {
2571         if (!session || snap_mode == SnapOff) {
2572                 return;
2573         }
2574
2575         snap_to_internal (start, direction, for_mark);
2576 }
2577
2578 void
2579 Editor::snap_to_internal (nframes64_t& start, int32_t direction, bool for_mark)
2580 {
2581         Location* before = 0;
2582         Location* after = 0;
2583
2584         const nframes64_t one_second = session->frame_rate();
2585         const nframes64_t one_minute = session->frame_rate() * 60;
2586         const nframes64_t one_smpte_second = (nframes64_t)(rint(session->smpte_frames_per_second()) * session->frames_per_smpte_frame());
2587         nframes64_t one_smpte_minute = (nframes64_t)(rint(session->smpte_frames_per_second()) * session->frames_per_smpte_frame() * 60);
2588         nframes64_t presnap = start;
2589
2590         switch (snap_type) {
2591         case SnapToCDFrame:
2592                 if (((direction == 0) && (start % (one_second/75) > (one_second/75) / 2)) || (direction > 0)) {
2593                         start = (nframes64_t) ceil ((double) start / (one_second / 75)) * (one_second / 75);
2594                 } else {
2595                         start = (nframes64_t) floor ((double) start / (one_second / 75)) * (one_second / 75);
2596                 }
2597                 break;
2598
2599         case SnapToSMPTEFrame:
2600                 if (((direction == 0) && (fmod((double)start, (double)session->frames_per_smpte_frame()) > (session->frames_per_smpte_frame() / 2))) || (direction > 0)) {
2601                         start = (nframes64_t) (ceil ((double) start / session->frames_per_smpte_frame()) * session->frames_per_smpte_frame());
2602                 } else {
2603                         start = (nframes64_t) (floor ((double) start / session->frames_per_smpte_frame()) *  session->frames_per_smpte_frame());
2604                 }
2605                 break;
2606
2607         case SnapToSMPTESeconds:
2608                 if (session->smpte_offset_negative())
2609                 {
2610                         start += session->smpte_offset ();
2611                 } else {
2612                         start -= session->smpte_offset ();
2613                 }    
2614                 if (((direction == 0) && (start % one_smpte_second > one_smpte_second / 2)) || direction > 0) {
2615                         start = (nframes64_t) ceil ((double) start / one_smpte_second) * one_smpte_second;
2616                 } else {
2617                         start = (nframes64_t) floor ((double) start / one_smpte_second) * one_smpte_second;
2618                 }
2619                 
2620                 if (session->smpte_offset_negative())
2621                 {
2622                         start -= session->smpte_offset ();
2623                 } else {
2624                         start += session->smpte_offset ();
2625                 }
2626                 break;
2627                 
2628         case SnapToSMPTEMinutes:
2629                 if (session->smpte_offset_negative())
2630                 {
2631                         start += session->smpte_offset ();
2632                 } else {
2633                         start -= session->smpte_offset ();
2634                 }
2635                 if (((direction == 0) && (start % one_smpte_minute > one_smpte_minute / 2)) || direction > 0) {
2636                         start = (nframes64_t) ceil ((double) start / one_smpte_minute) * one_smpte_minute;
2637                 } else {
2638                         start = (nframes64_t) floor ((double) start / one_smpte_minute) * one_smpte_minute;
2639                 }
2640                 if (session->smpte_offset_negative())
2641                 {
2642                         start -= session->smpte_offset ();
2643                 } else {
2644                         start += session->smpte_offset ();
2645                 }
2646                 break;
2647                 
2648         case SnapToSeconds:
2649                 if (((direction == 0) && (start % one_second > one_second / 2)) || (direction > 0)) {
2650                         start = (nframes64_t) ceil ((double) start / one_second) * one_second;
2651                 } else {
2652                         start = (nframes64_t) floor ((double) start / one_second) * one_second;
2653                 }
2654                 break;
2655                 
2656         case SnapToMinutes:
2657                 if (((direction == 0) && (start % one_minute > one_minute / 2)) || (direction > 0)) {
2658                         start = (nframes64_t) ceil ((double) start / one_minute) * one_minute;
2659                 } else {
2660                         start = (nframes64_t) floor ((double) start / one_minute) * one_minute;
2661                 }
2662                 break;
2663
2664         case SnapToBar:
2665                 start = session->tempo_map().round_to_bar (start, direction);
2666                 break;
2667
2668         case SnapToBeat:
2669                 start = session->tempo_map().round_to_beat (start, direction);
2670                 break;
2671
2672         case SnapToAThirtysecondBeat:
2673                 start = session->tempo_map().round_to_beat_subdivision (start, 32);
2674                 break;
2675
2676         case SnapToASixteenthBeat:
2677                 start = session->tempo_map().round_to_beat_subdivision (start, 16);
2678                 break;
2679
2680         case SnapToAEighthBeat:
2681                 start = session->tempo_map().round_to_beat_subdivision (start, 8);
2682                 break;
2683
2684         case SnapToAQuarterBeat:
2685                 start = session->tempo_map().round_to_beat_subdivision (start, 4);
2686                 break;
2687
2688         case SnapToAThirdBeat:
2689                 start = session->tempo_map().round_to_beat_subdivision (start, 3);
2690                 break;
2691
2692         case SnapToMark:
2693                 if (for_mark) {
2694                         return;
2695                 }
2696
2697                 before = session->locations()->first_location_before (start);
2698                 after = session->locations()->first_location_after (start);
2699
2700                 if (direction < 0) {
2701                         if (before) {
2702                                 start = before->start();
2703                         } else {
2704                                 start = 0;
2705                         }
2706                 } else if (direction > 0) {
2707                         if (after) {
2708                                 start = after->start();
2709                         } else {
2710                                 start = session->current_end_frame();
2711                         }
2712                 } else {
2713                         if (before) {
2714                                 if (after) {
2715                                         /* find nearest of the two */
2716                                         if ((start - before->start()) < (after->start() - start)) {
2717                                                 start = before->start();
2718                                         } else {
2719                                                 start = after->start();
2720                                         }
2721                                 } else {
2722                                         start = before->start();
2723                                 }
2724                         } else if (after) {
2725                                 start = after->start();
2726                         } else {
2727                                 /* relax */
2728                         }
2729                 }
2730                 break;
2731
2732         case SnapToRegionStart:
2733         case SnapToRegionEnd:
2734         case SnapToRegionSync:
2735         case SnapToRegionBoundary:
2736                 if (!region_boundary_cache.empty()) {
2737                         vector<nframes64_t>::iterator i;
2738
2739                         if (direction > 0) {
2740                                 i = std::upper_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2741                         } else {
2742                                 i = std::lower_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2743                         }
2744                         
2745                         if (i != region_boundary_cache.end()) {
2746
2747                                 /* lower bound doesn't quite to the right thing for our purposes */
2748
2749                                 if (direction < 0 && i != region_boundary_cache.begin()) {
2750                                         --i;
2751                                 }
2752
2753                                 start = *i;
2754
2755                         } else {
2756                                 start = region_boundary_cache.back();
2757                         }
2758                 } 
2759                 break;
2760         }
2761
2762         switch (snap_mode) {
2763         case SnapNormal:
2764                 return;                 
2765                 
2766         case SnapMagnetic:
2767                 
2768                 if (presnap > start) {
2769                         if (presnap > (start + unit_to_frame(snap_threshold))) {
2770                                 start = presnap;
2771                         }
2772                         
2773                 } else if (presnap < start) {
2774                         if (presnap < (start - unit_to_frame(snap_threshold))) {
2775                                 start = presnap;
2776                         }
2777                 }
2778                 
2779         default:
2780                 /* handled at entry */
2781                 return;
2782                 
2783         }
2784 }
2785
2786 void
2787 Editor::setup_toolbar ()
2788 {
2789         string pixmap_path;
2790
2791 #ifdef GTKOSX
2792         const guint32 FUDGE = 38; // Combo's are stupid - they steal space from the entry for the button
2793 #else
2794         const guint32 FUDGE = 18; // Combo's are stupid - they steal space from the entry for the button
2795 #endif
2796
2797         /* Mode Buttons (tool selection) */
2798
2799         vector<ToggleButton *> mouse_mode_buttons;
2800
2801         mouse_move_button.add (*(manage (new Image (::get_icon("tool_object")))));
2802         mouse_move_button.set_relief(Gtk::RELIEF_NONE);
2803         mouse_mode_buttons.push_back (&mouse_move_button);
2804
2805         if (!Profile->get_sae()) {
2806                 mouse_select_button.add (*(manage (new Image (get_xpm("tool_range.xpm")))));
2807                 mouse_select_button.set_relief(Gtk::RELIEF_NONE);
2808                 mouse_mode_buttons.push_back (&mouse_select_button);
2809
2810                 mouse_gain_button.add (*(manage (new Image (::get_icon("tool_gain")))));
2811                 mouse_gain_button.set_relief(Gtk::RELIEF_NONE);
2812                 mouse_mode_buttons.push_back (&mouse_gain_button);
2813         }
2814
2815         mouse_zoom_button.add (*(manage (new Image (::get_icon("tool_zoom")))));
2816         mouse_zoom_button.set_relief(Gtk::RELIEF_NONE);
2817         mouse_mode_buttons.push_back (&mouse_zoom_button);
2818         mouse_timefx_button.add (*(manage (new Image (::get_icon("tool_stretch")))));
2819         mouse_timefx_button.set_relief(Gtk::RELIEF_NONE);
2820         mouse_mode_buttons.push_back (&mouse_timefx_button);
2821         mouse_audition_button.add (*(manage (new Image (::get_icon("tool_audition")))));
2822         mouse_audition_button.set_relief(Gtk::RELIEF_NONE);
2823         mouse_mode_buttons.push_back (&mouse_audition_button);
2824         
2825         mouse_mode_button_set = new GroupedButtons (mouse_mode_buttons);
2826
2827         HBox* mode_box = manage(new HBox);
2828         mode_box->set_border_width (2);
2829         mode_box->set_spacing(4);
2830         mouse_mode_button_box.set_spacing(1);
2831         mouse_mode_button_box.pack_start(mouse_move_button, true, true);
2832         if (!Profile->get_sae()) {
2833                 mouse_mode_button_box.pack_start(mouse_select_button, true, true);
2834         }
2835         mouse_mode_button_box.pack_start(mouse_zoom_button, true, true);
2836         if (!Profile->get_sae()) {
2837                 mouse_mode_button_box.pack_start(mouse_gain_button, true, true);
2838         }
2839         mouse_mode_button_box.pack_start(mouse_timefx_button, true, true);
2840         mouse_mode_button_box.pack_start(mouse_audition_button, true, true);
2841         mouse_mode_button_box.set_homogeneous(true);
2842
2843         vector<string> edit_mode_strings;
2844         edit_mode_strings.push_back (edit_mode_to_string (Slide));
2845         edit_mode_strings.push_back (edit_mode_to_string (Splice));
2846         edit_mode_strings.push_back (edit_mode_to_string (Lock));
2847
2848         edit_mode_selector.set_name ("EditModeSelector");
2849         Gtkmm2ext::set_size_request_to_display_given_text (edit_mode_selector, longest (edit_mode_strings).c_str(), 2+FUDGE, 10);
2850         set_popdown_strings (edit_mode_selector, edit_mode_strings);
2851         edit_mode_selector.signal_changed().connect (mem_fun(*this, &Editor::edit_mode_selection_done));
2852
2853         mode_box->pack_start(edit_mode_selector);
2854         mode_box->pack_start(mouse_mode_button_box);
2855         
2856         mouse_mode_tearoff = manage (new TearOff (*mode_box));
2857         mouse_mode_tearoff->set_name ("MouseModeBase");
2858
2859         mouse_mode_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2860                                                   &mouse_mode_tearoff->tearoff_window()));
2861         mouse_mode_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2862                                                   &mouse_mode_tearoff->tearoff_window(), 1));
2863         mouse_mode_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2864                                                   &mouse_mode_tearoff->tearoff_window()));
2865         mouse_mode_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2866                                                    &mouse_mode_tearoff->tearoff_window(), 1));
2867
2868         mouse_move_button.set_name ("MouseModeButton");
2869         mouse_select_button.set_name ("MouseModeButton");
2870         mouse_gain_button.set_name ("MouseModeButton");
2871         mouse_zoom_button.set_name ("MouseModeButton");
2872         mouse_timefx_button.set_name ("MouseModeButton");
2873         mouse_audition_button.set_name ("MouseModeButton");
2874
2875         ARDOUR_UI::instance()->tooltips().set_tip (mouse_move_button, _("Select/Move Objects"));
2876         ARDOUR_UI::instance()->tooltips().set_tip (mouse_select_button, _("Select/Move Ranges"));
2877         ARDOUR_UI::instance()->tooltips().set_tip (mouse_gain_button, _("Draw Gain Automation"));
2878         ARDOUR_UI::instance()->tooltips().set_tip (mouse_zoom_button, _("Select Zoom Range"));
2879         ARDOUR_UI::instance()->tooltips().set_tip (mouse_timefx_button, _("Stretch/Shrink Regions"));
2880         ARDOUR_UI::instance()->tooltips().set_tip (mouse_audition_button, _("Listen to Specific Regions"));
2881
2882         mouse_move_button.unset_flags (CAN_FOCUS);
2883         mouse_select_button.unset_flags (CAN_FOCUS);
2884         mouse_gain_button.unset_flags (CAN_FOCUS);
2885         mouse_zoom_button.unset_flags (CAN_FOCUS);
2886         mouse_timefx_button.unset_flags (CAN_FOCUS);
2887         mouse_audition_button.unset_flags (CAN_FOCUS);
2888
2889         mouse_select_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseRange));
2890         mouse_select_button.signal_button_release_event().connect (mem_fun(*this, &Editor::mouse_select_button_release));
2891
2892         mouse_move_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseObject));
2893         mouse_gain_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseGain));
2894         mouse_zoom_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseZoom));
2895         mouse_timefx_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseTimeFX));
2896         mouse_audition_button.signal_toggled().connect (bind (mem_fun(*this, &Editor::mouse_mode_toggled), Editing::MouseAudition));
2897
2898         // mouse_move_button.set_active (true);
2899         
2900
2901         /* Zoom */
2902         
2903         zoom_box.set_spacing (1);
2904         zoom_box.set_border_width (0);
2905
2906         zoom_in_button.set_name ("EditorTimeButton");
2907         zoom_in_button.set_size_request(-1,16);
2908         zoom_in_button.add (*(manage (new Image (::get_icon("zoom_in")))));
2909         zoom_in_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::temporal_zoom_step), false));
2910         ARDOUR_UI::instance()->tooltips().set_tip (zoom_in_button, _("Zoom In"));
2911         
2912         zoom_out_button.set_name ("EditorTimeButton");
2913         zoom_out_button.set_size_request(-1,16);
2914         zoom_out_button.add (*(manage (new Image (::get_icon("zoom_out")))));
2915         zoom_out_button.signal_clicked().connect (bind (mem_fun(*this, &Editor::temporal_zoom_step), true));
2916         ARDOUR_UI::instance()->tooltips().set_tip (zoom_out_button, _("Zoom Out"));
2917
2918         zoom_out_full_button.set_name ("EditorTimeButton");
2919         zoom_out_full_button.set_size_request(-1,16);
2920         zoom_out_full_button.add (*(manage (new Image (::get_icon("zoom_full")))));
2921         zoom_out_full_button.signal_clicked().connect (mem_fun(*this, &Editor::temporal_zoom_session));
2922         ARDOUR_UI::instance()->tooltips().set_tip (zoom_out_full_button, _("Zoom to Session"));
2923
2924         zoom_focus_selector.set_name ("ZoomFocusSelector");
2925         Gtkmm2ext::set_size_request_to_display_given_text (zoom_focus_selector, _("Playhead"), FUDGE, 0);
2926         set_popdown_strings (zoom_focus_selector, zoom_focus_strings);
2927         zoom_focus_selector.signal_changed().connect (mem_fun(*this, &Editor::zoom_focus_selection_done));
2928         ARDOUR_UI::instance()->tooltips().set_tip (zoom_focus_selector, _("Zoom focus"));
2929
2930         zoom_box.pack_start (zoom_focus_selector, true, true);
2931         zoom_box.pack_start (zoom_out_button, false, false);
2932         zoom_box.pack_start (zoom_in_button, false, false);
2933         zoom_box.pack_start (zoom_out_full_button, false, false);
2934
2935         snap_box.set_spacing (1);
2936         snap_box.set_border_width (2);
2937
2938         snap_type_selector.set_name ("SnapTypeSelector");
2939         Gtkmm2ext::set_size_request_to_display_given_text (snap_type_selector, _("SMPTE Seconds"), 2+FUDGE, 10);
2940         set_popdown_strings (snap_type_selector, snap_type_strings);
2941         snap_type_selector.signal_changed().connect (mem_fun(*this, &Editor::snap_type_selection_done));
2942         ARDOUR_UI::instance()->tooltips().set_tip (snap_type_selector, _("Snap/Grid Units"));
2943
2944         snap_mode_selector.set_name ("SnapModeSelector");
2945         Gtkmm2ext::set_size_request_to_display_given_text (snap_mode_selector, _("Magnetic Snap"), 2+FUDGE, 10);
2946         set_popdown_strings (snap_mode_selector, snap_mode_strings);
2947         snap_mode_selector.signal_changed().connect (mem_fun(*this, &Editor::snap_mode_selection_done));
2948         ARDOUR_UI::instance()->tooltips().set_tip (snap_mode_selector, _("Snap/Grid Mode"));
2949
2950         edit_point_selector.set_name ("SnapModeSelector");
2951         Gtkmm2ext::set_size_request_to_display_given_text (edit_point_selector, _("Playhead"), 2+FUDGE, 10);
2952         set_popdown_strings (edit_point_selector, edit_point_strings);
2953         edit_point_selector.signal_changed().connect (mem_fun(*this, &Editor::edit_point_selection_done));
2954         ARDOUR_UI::instance()->tooltips().set_tip (edit_point_selector, _("Edit point"));
2955
2956         snap_box.pack_start (edit_point_clock, false, false);
2957         snap_box.pack_start (snap_mode_selector, false, false);
2958         snap_box.pack_start (snap_type_selector, false, false);
2959         snap_box.pack_start (edit_point_selector, false, false);
2960
2961         /* Nudge */
2962
2963         HBox *nudge_box = manage (new HBox);
2964         nudge_box->set_spacing(1);
2965         nudge_box->set_border_width (2);
2966
2967         nudge_forward_button.signal_button_release_event().connect (mem_fun(*this, &Editor::nudge_forward_release), false);
2968         nudge_backward_button.signal_button_release_event().connect (mem_fun(*this, &Editor::nudge_backward_release), false);
2969
2970         nudge_box->pack_start (nudge_backward_button, false, false);
2971         nudge_box->pack_start (nudge_forward_button, false, false);
2972         nudge_box->pack_start (nudge_clock, false, false);
2973
2974
2975         /* Pack everything in... */
2976
2977         HBox* hbox = new HBox;
2978         hbox->set_spacing(10);
2979
2980         tools_tearoff = new TearOff (*hbox);
2981         tools_tearoff->set_name ("MouseModeBase");
2982
2983         tools_tearoff->Detach.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2984                                              &tools_tearoff->tearoff_window()));
2985         tools_tearoff->Attach.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2986                                              &tools_tearoff->tearoff_window(), 0));
2987         tools_tearoff->Hidden.connect (bind (mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox), 
2988                                              &tools_tearoff->tearoff_window()));
2989         tools_tearoff->Visible.connect (bind (mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox), 
2990                                               &tools_tearoff->tearoff_window(), 0));
2991
2992         toolbar_hbox.set_spacing (10);
2993         toolbar_hbox.set_border_width (1);
2994
2995         toolbar_hbox.pack_start (*mouse_mode_tearoff, false, false);
2996         toolbar_hbox.pack_start (*tools_tearoff, false, false);
2997
2998         
2999         hbox->pack_start (snap_box, false, false);
3000         // hbox->pack_start (zoom_box, false, false); 
3001         hbox->pack_start (*nudge_box, false, false);
3002
3003         hbox->show_all ();
3004         
3005         toolbar_base.set_name ("ToolBarBase");
3006         toolbar_base.add (toolbar_hbox);
3007
3008         toolbar_frame.set_shadow_type (SHADOW_OUT);
3009         toolbar_frame.set_name ("BaseFrame");
3010         toolbar_frame.add (toolbar_base);
3011 }
3012
3013 int
3014 Editor::convert_drop_to_paths (vector<ustring>& paths, 
3015                                const RefPtr<Gdk::DragContext>& context,
3016                                gint                x,
3017                                gint                y,
3018                                const SelectionData& data,
3019                                guint               info,
3020                                guint               time)                               
3021
3022 {       
3023         if (session == 0) {
3024                 return -1;
3025         }
3026
3027         vector<ustring> uris = data.get_uris();
3028
3029         if (uris.empty()) {
3030
3031                 /* This is seriously fucked up. Nautilus doesn't say that its URI lists
3032                    are actually URI lists. So do it by hand.
3033                 */
3034
3035                 if (data.get_target() != "text/plain") {
3036                         return -1;
3037                 }
3038   
3039                 /* Parse the "uri-list" format that Nautilus provides, 
3040                    where each pathname is delimited by \r\n
3041                 */
3042         
3043                 const char* p = data.get_text().c_str();
3044                 const char* q;
3045
3046                 while (p)
3047                 {
3048                         if (*p != '#')
3049                         {
3050                                 while (g_ascii_isspace (*p))
3051                                         p++;
3052                                 
3053                                 q = p;
3054                                 while (*q && (*q != '\n') && (*q != '\r'))
3055                                         q++;
3056                                 
3057                                 if (q > p)
3058                                 {
3059                                         q--;
3060                                         while (q > p && g_ascii_isspace (*q))
3061                                                 q--;
3062                                         
3063                                         if (q > p)
3064                                         {
3065                                                 uris.push_back (ustring (p, q - p + 1));
3066                                         }
3067                                 }
3068                         }
3069                         p = strchr (p, '\n');
3070                         if (p)
3071                                 p++;
3072                 }
3073
3074                 if (uris.empty()) {
3075                         return -1;
3076                 }
3077         }
3078         
3079         for (vector<ustring>::iterator i = uris.begin(); i != uris.end(); ++i) {
3080
3081                 if ((*i).substr (0,7) == "file://") {
3082
3083                         
3084                         ustring p = *i;
3085                         PBD::url_decode (p);
3086
3087                         // scan forward past three slashes
3088                         
3089                         ustring::size_type slashcnt = 0;
3090                         ustring::size_type n = 0;
3091                         ustring::iterator x = p.begin();
3092
3093                         while (slashcnt < 3 && x != p.end()) {
3094                                 if ((*x) == '/') {
3095                                         slashcnt++;
3096                                 } else if (slashcnt == 3) {
3097                                         break;
3098                                 }
3099                                 ++n;
3100                                 ++x;
3101                         }
3102
3103                         if (slashcnt != 3 || x == p.end()) {
3104                                 error << _("malformed URL passed to drag-n-drop code") << endmsg;
3105                                 continue;
3106                         }
3107
3108                         paths.push_back (p.substr (n - 1));
3109                 }
3110         }
3111
3112         return 0;
3113 }
3114
3115 void
3116 Editor::new_tempo_section ()
3117
3118 {
3119 }
3120
3121 void
3122 Editor::map_transport_state ()
3123 {
3124         ENSURE_GUI_THREAD (mem_fun(*this, &Editor::map_transport_state));
3125
3126         if (session->transport_stopped()) {
3127                 have_pending_keyboard_selection = false;
3128         }
3129
3130         update_loop_range_view (true);
3131 }
3132
3133 /* UNDO/REDO */
3134
3135 Editor::State::State ()
3136 {
3137         selection = new Selection;
3138 }
3139
3140 Editor::State::~State ()
3141 {
3142         delete selection;
3143 }
3144
3145 UndoAction
3146 Editor::get_memento () const
3147 {
3148         State *state = new State;
3149
3150         store_state (*state);
3151         return bind (mem_fun (*(const_cast<Editor*>(this)), &Editor::restore_state), state);
3152 }
3153
3154 void
3155 Editor::store_state (State& state) const
3156 {
3157         *state.selection = *selection;
3158 }
3159
3160 void
3161 Editor::restore_state (State *state)
3162 {
3163         if (*selection == *state->selection) {
3164                 return;
3165         }
3166
3167         *selection = *state->selection;
3168         time_selection_changed ();
3169         region_selection_changed ();   
3170
3171         /* XXX other selection change handlers? */
3172 }
3173
3174 void
3175 Editor::begin_reversible_command (string name)
3176 {
3177         if (session) {
3178                 // before = &get_state();
3179                 session->begin_reversible_command (name);
3180         }
3181 }
3182
3183 void
3184 Editor::commit_reversible_command ()
3185 {
3186         if (session) {
3187                 // session->commit_reversible_command (new MementoCommand<Editor>(*this, before, &get_state()));
3188                 session->commit_reversible_command ();
3189         }
3190 }
3191
3192 void
3193 Editor::set_edit_group_solo (Route& route, bool yn)
3194 {
3195         RouteGroup *edit_group;
3196
3197         if ((edit_group = route.edit_group()) != 0) {
3198                 edit_group->apply (&Route::set_solo, yn, this);
3199         } else {
3200                 route.set_solo (yn, this);
3201         }
3202 }
3203
3204 void
3205 Editor::set_edit_group_mute (Route& route, bool yn)
3206 {
3207         RouteGroup *edit_group = 0;
3208
3209         if ((edit_group == route.edit_group()) != 0) {
3210                 edit_group->apply (&Route::set_mute, yn, this);
3211         } else {
3212                 route.set_mute (yn, this);
3213         }
3214 }
3215                 
3216 void
3217 Editor::history_changed ()
3218 {
3219         string label;
3220
3221         if (undo_action && session) {
3222                 if (session->undo_depth() == 0) {
3223                         label = _("Undo");
3224                 } else {
3225                         label = string_compose(_("Undo (%1)"), session->next_undo());
3226                 }
3227                 undo_action->property_label() = label;
3228         }
3229
3230         if (redo_action && session) {
3231                 if (session->redo_depth() == 0) {
3232                         label = _("Redo");
3233                 } else {
3234                         label = string_compose(_("Redo (%1)"), session->next_redo());
3235                 }
3236                 redo_action->property_label() = label;
3237         }
3238 }
3239
3240 void
3241 Editor::duplicate_dialog (bool with_dialog)
3242 {
3243         float times = 1.0f;
3244
3245         if (mouse_mode == MouseRange) {
3246                 if (selection->time.length() == 0) {
3247                         return;
3248                 }
3249         }
3250
3251         RegionSelection rs;
3252         get_regions_for_action (rs);
3253         
3254         if (mouse_mode != MouseRange) {
3255
3256                 if (rs.empty()) {
3257                         return;
3258                 }
3259         }
3260
3261         if (with_dialog) {
3262
3263                 ArdourDialog win ("Duplication Dialog");
3264                 Label  label (_("Number of Duplications:"));
3265                 Adjustment adjustment (1.0, 1.0, 1000000.0, 1.0, 5.0);
3266                 SpinButton spinner (adjustment, 0.0, 1);
3267                 HBox hbox;
3268                 
3269                 win.get_vbox()->set_spacing (12);
3270                 win.get_vbox()->pack_start (hbox);
3271                 hbox.set_border_width (6);
3272                 hbox.pack_start (label, PACK_EXPAND_PADDING, 12);
3273                 
3274                 /* dialogs have ::add_action_widget() but that puts the spinner in the wrong
3275                    place, visually. so do this by hand.
3276                 */
3277                 
3278                 hbox.pack_start (spinner, PACK_EXPAND_PADDING, 12);
3279                 spinner.signal_activate().connect (sigc::bind (mem_fun (win, &ArdourDialog::response), RESPONSE_ACCEPT));
3280                 spinner.grab_focus();
3281
3282                 hbox.show ();
3283                 label.show ();
3284                 spinner.show ();
3285                 
3286                 win.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3287                 win.add_button (_("Duplicate"), RESPONSE_ACCEPT);
3288                 win.set_default_response (RESPONSE_ACCEPT);
3289                 
3290                 win.set_position (WIN_POS_MOUSE);
3291                 
3292                 spinner.grab_focus ();
3293                 
3294                 switch (win.run ()) {
3295                 case RESPONSE_ACCEPT:
3296                         break;
3297                 default:
3298                         return;
3299                 }
3300                 
3301                 times = adjustment.get_value();
3302         }
3303
3304         if (mouse_mode == MouseRange) {
3305                 duplicate_selection (times);
3306         } else {
3307                 duplicate_some_regions (rs, times);
3308         }
3309 }
3310
3311 void
3312 Editor::show_verbose_canvas_cursor ()
3313 {
3314         verbose_canvas_cursor->raise_to_top();
3315         verbose_canvas_cursor->show();
3316         verbose_cursor_visible = true;
3317 }
3318
3319 void
3320 Editor::hide_verbose_canvas_cursor ()
3321 {
3322         verbose_canvas_cursor->hide();
3323         verbose_cursor_visible = false;
3324 }
3325
3326 double
3327 Editor::clamp_verbose_cursor_x (double x)
3328 {
3329         if (x < 0) {
3330                 x = 0;
3331         } else {
3332                 x = min (canvas_width - 200.0, x);
3333         }
3334         return x;
3335 }
3336
3337 double
3338 Editor::clamp_verbose_cursor_y (double y)
3339 {
3340         if (y < canvas_timebars_vsize) {
3341                 y = canvas_timebars_vsize;
3342         } else {
3343                 y = min (canvas_height - 50, y);
3344         }
3345         return y;
3346 }
3347
3348 void
3349 Editor::set_verbose_canvas_cursor (const string & txt, double x, double y)
3350 {
3351         verbose_canvas_cursor->property_text() = txt.c_str();
3352         /* don't get too close to the edge */
3353         verbose_canvas_cursor->property_x() = clamp_verbose_cursor_x (x);
3354         verbose_canvas_cursor->property_y() = clamp_verbose_cursor_y (y);
3355 }
3356
3357 void
3358 Editor::set_verbose_canvas_cursor_text (const string & txt)
3359 {
3360         verbose_canvas_cursor->property_text() = txt.c_str();
3361 }
3362
3363 void
3364 Editor::set_edit_mode (EditMode m)
3365 {
3366         Config->set_edit_mode (m);
3367 }
3368
3369 void
3370 Editor::cycle_edit_mode ()
3371 {
3372         switch (Config->get_edit_mode()) {
3373         case Slide:
3374                 Config->set_edit_mode (Splice);
3375                 break;
3376         case Splice:
3377                 Config->set_edit_mode (Lock);
3378                 break;
3379         case Lock:
3380                 Config->set_edit_mode (Slide);
3381                 break;
3382         }
3383 }
3384
3385 void
3386 Editor::edit_mode_selection_done ()
3387 {
3388         if (session == 0) {
3389                 return;
3390         }
3391
3392         string choice = edit_mode_selector.get_active_text();
3393         EditMode mode = Slide;
3394
3395         if (choice == _("Splice Edit")) {
3396                 mode = Splice;
3397         } else if (choice == _("Slide Edit")) {
3398                 mode = Slide;
3399         } else if (choice == _("Lock Edit")) {
3400                 mode = Lock;
3401         }
3402
3403         Config->set_edit_mode (mode);
3404 }       
3405
3406 void
3407 Editor::snap_type_selection_done ()
3408 {
3409         string choice = snap_type_selector.get_active_text();
3410         SnapType snaptype = SnapToBeat;
3411
3412         if (choice == _("Beats/3")) {
3413                 snaptype = SnapToAThirdBeat;
3414         } else if (choice == _("Beats/4")) {
3415                 snaptype = SnapToAQuarterBeat;
3416         } else if (choice == _("Beats/8")) {
3417                 snaptype = SnapToAEighthBeat;
3418         } else if (choice == _("Beats/16")) {
3419                 snaptype = SnapToASixteenthBeat;
3420         } else if (choice == _("Beats/32")) {
3421                 snaptype = SnapToAThirtysecondBeat;
3422         } else if (choice == _("Beats")) {
3423                 snaptype = SnapToBeat;
3424         } else if (choice == _("Bars")) {
3425                 snaptype = SnapToBar;
3426         } else if (choice == _("Marks")) {
3427                 snaptype = SnapToMark;
3428         } else if (choice == _("Region starts")) {
3429                 snaptype = SnapToRegionStart;
3430         } else if (choice == _("Region ends")) {
3431                 snaptype = SnapToRegionEnd;
3432         } else if (choice == _("Region bounds")) {
3433                 snaptype = SnapToRegionBoundary;
3434         } else if (choice == _("Region syncs")) {
3435                 snaptype = SnapToRegionSync;
3436         } else if (choice == _("CD Frames")) {
3437                 snaptype = SnapToCDFrame;
3438         } else if (choice == _("SMPTE Frames")) {
3439                 snaptype = SnapToSMPTEFrame;
3440         } else if (choice == _("SMPTE Seconds")) {
3441                 snaptype = SnapToSMPTESeconds;
3442         } else if (choice == _("SMPTE Minutes")) {
3443                 snaptype = SnapToSMPTEMinutes;
3444         } else if (choice == _("Seconds")) {
3445                 snaptype = SnapToSeconds;
3446         } else if (choice == _("Minutes")) {
3447                 snaptype = SnapToMinutes;
3448         }
3449
3450         RefPtr<RadioAction> ract = snap_type_action (snaptype);
3451         if (ract) {
3452                 ract->set_active ();
3453         }
3454 }       
3455
3456 void
3457 Editor::snap_mode_selection_done ()
3458 {
3459         string choice = snap_mode_selector.get_active_text();
3460         SnapMode mode = SnapNormal;
3461
3462         if (choice == _("No Grid")) {
3463                 mode = SnapOff;
3464         } else if (choice == _("Grid")) {
3465                 mode = SnapNormal;
3466         } else if (choice == _("Magnetic")) {
3467                 mode = SnapMagnetic;
3468         }
3469
3470         RefPtr<RadioAction> ract = snap_mode_action (mode);
3471
3472         if (ract) {
3473                 ract->set_active (true);
3474         }
3475 }
3476
3477 void
3478 Editor::cycle_edit_point (bool with_marker)
3479 {
3480         switch (_edit_point) {
3481         case EditAtMouse:
3482                 set_edit_point_preference (EditAtPlayhead);
3483                 break;
3484         case EditAtPlayhead:
3485                 if (with_marker) {
3486                         set_edit_point_preference (EditAtSelectedMarker);
3487                 } else {
3488                         set_edit_point_preference (EditAtMouse);
3489                 }
3490                 break;
3491         case EditAtSelectedMarker:
3492                 set_edit_point_preference (EditAtMouse);
3493                 break;
3494         }
3495 }
3496
3497 void
3498 Editor::edit_point_selection_done ()
3499 {
3500         string choice = edit_point_selector.get_active_text();
3501         EditPoint ep = EditAtSelectedMarker;
3502
3503         if (choice == _("Marker")) {
3504                 set_edit_point_preference (EditAtSelectedMarker);
3505         } else if (choice == _("Playhead")) {
3506                 set_edit_point_preference (EditAtPlayhead);
3507         } else {
3508                 set_edit_point_preference (EditAtMouse);
3509         }
3510
3511         RefPtr<RadioAction> ract = edit_point_action (ep);
3512
3513         if (ract) {
3514                 ract->set_active (true);
3515         }
3516 }
3517
3518 void
3519 Editor::zoom_focus_selection_done ()
3520 {
3521         string choice = zoom_focus_selector.get_active_text();
3522         ZoomFocus focus_type = ZoomFocusLeft;
3523
3524         if (choice == _("Left")) {
3525                 focus_type = ZoomFocusLeft;
3526         } else if (choice == _("Right")) {
3527                 focus_type = ZoomFocusRight;
3528         } else if (choice == _("Center")) {
3529                 focus_type = ZoomFocusCenter;
3530         } else if (choice == _("Playhead")) {
3531                 focus_type = ZoomFocusPlayhead;
3532         } else if (choice == _("Mouse")) {
3533                 focus_type = ZoomFocusMouse;
3534         } else if (choice == _("Active Mark")) {
3535                 focus_type = ZoomFocusEdit;
3536         } 
3537         
3538         RefPtr<RadioAction> ract = zoom_focus_action (focus_type);
3539
3540         if (ract) {
3541                 ract->set_active ();
3542         }
3543 }       
3544
3545 gint
3546 Editor::edit_controls_button_release (GdkEventButton* ev)
3547 {
3548         if (Keyboard::is_context_menu_event (ev)) {
3549                 ARDOUR_UI::instance()->add_route (this);
3550         }
3551         return TRUE;
3552 }
3553
3554 gint
3555 Editor::mouse_select_button_release (GdkEventButton* ev)
3556 {
3557         /* this handles just right-clicks */
3558
3559         if (ev->button != 3) {
3560                 return false;
3561         }
3562
3563         return true;
3564 }
3565
3566 Editor::TrackViewList *
3567 Editor::get_valid_views (TimeAxisView* track, RouteGroup* group)
3568 {
3569         TrackViewList *v;
3570         TrackViewList::iterator i;
3571
3572         v = new TrackViewList;
3573
3574         if (track == 0 && group == 0) {
3575
3576                 /* all views */
3577
3578                 for (i = track_views.begin(); i != track_views.end (); ++i) {
3579                         v->push_back (*i);
3580                 }
3581
3582         } else if ((track != 0 && group == 0) || (track != 0 && group != 0 && !group->is_active())) {
3583                 
3584                 /* just the view for this track
3585                  */
3586
3587                 v->push_back (track);
3588
3589         } else {
3590                 
3591                 /* views for all tracks in the edit group */
3592                 
3593                 for (i  = track_views.begin(); i != track_views.end (); ++i) {
3594
3595                         if (group == 0 || (*i)->edit_group() == group) {
3596                                 v->push_back (*i);
3597                         }
3598                 }
3599         }
3600         
3601         return v;
3602 }
3603
3604 void
3605 Editor::set_zoom_focus (ZoomFocus f)
3606 {
3607         string str = zoom_focus_strings[(int)f];
3608
3609         if (str != zoom_focus_selector.get_active_text()) {
3610                 zoom_focus_selector.set_active_text (str);
3611         }
3612         
3613         if (zoom_focus != f) {
3614                 zoom_focus = f;
3615
3616                 ZoomFocusChanged (); /* EMIT_SIGNAL */
3617
3618                 instant_save ();
3619         }
3620 }
3621
3622 void
3623 Editor::ensure_float (Window& win)
3624 {
3625         win.set_transient_for (*this);
3626 }
3627
3628 void 
3629 Editor::pane_allocation_handler (Allocation &alloc, Paned* which)
3630 {
3631         /* recover or initialize pane positions. do this here rather than earlier because
3632            we don't want the positions to change the child allocations, which they seem to do.
3633          */
3634
3635         int pos;
3636         XMLProperty* prop;
3637         char buf[32];
3638         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
3639         int width, height;
3640         static int32_t done;
3641         XMLNode* geometry;
3642
3643         if ((geometry = find_named_node (*node, "geometry")) == 0) {
3644                 width = default_width;
3645                 height = default_height;
3646         } else {
3647                 width = atoi(geometry->property("x_size")->value());
3648                 height = atoi(geometry->property("y_size")->value());
3649         }
3650
3651         if (which == static_cast<Paned*> (&edit_pane)) {
3652
3653                 if (done) {
3654                         return;
3655                 }
3656
3657                 if (!geometry || (prop = geometry->property ("edit_pane_pos")) == 0) {
3658                         /* initial allocation is 90% to canvas, 10% to notebook */
3659                         pos = (int) floor (alloc.get_width() * 0.90f);
3660                         snprintf (buf, sizeof(buf), "%d", pos);
3661                 } else {
3662                         pos = atoi (prop->value());
3663                 }
3664                 
3665                 if ((done = GTK_WIDGET(edit_pane.gobj())->allocation.width > pos)) {
3666                         edit_pane.set_position (pos);
3667                         pre_maximal_pane_position = pos;
3668                 }
3669         }
3670 }
3671
3672 void
3673 Editor::detach_tearoff (Box* b, Window* w)
3674 {
3675         if (tools_tearoff->torn_off() && 
3676             mouse_mode_tearoff->torn_off()) {
3677                 top_hbox.remove (toolbar_frame);
3678         }
3679 }
3680
3681 void
3682 Editor::reattach_tearoff (Box* b, Window* w, int32_t n)
3683 {
3684         if (toolbar_frame.get_parent() == 0) {
3685                 top_hbox.pack_end (toolbar_frame);
3686         }
3687 }
3688
3689 void
3690 Editor::set_show_measures (bool yn)
3691 {
3692         if (_show_measures != yn) {
3693                 hide_measures ();
3694
3695                 if ((_show_measures = yn) == true) {
3696                         if (tempo_lines) {
3697                                 tempo_lines->show();
3698                         }
3699                         draw_measures ();
3700                 }
3701                 instant_save ();
3702         }
3703 }
3704
3705 void
3706 Editor::toggle_follow_playhead ()
3707 {
3708         RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
3709         if (act) {
3710                 RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
3711                 set_follow_playhead (tact->get_active());
3712         }
3713 }
3714
3715 void
3716 Editor::set_follow_playhead (bool yn)
3717 {
3718         if (_follow_playhead != yn) {
3719                 if ((_follow_playhead = yn) == true) {
3720                         /* catch up */
3721                         update_current_screen ();
3722                 }
3723                 instant_save ();
3724         }
3725 }
3726
3727 void
3728 Editor::toggle_xfade_active (boost::weak_ptr<Crossfade> wxfade)
3729 {
3730         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3731         if (xfade) {
3732                 xfade->set_active (!xfade->active());
3733         }
3734 }
3735
3736 void
3737 Editor::toggle_xfade_length (boost::weak_ptr<Crossfade> wxfade)
3738 {
3739         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3740         if (xfade) {
3741                 xfade->set_follow_overlap (!xfade->following_overlap());
3742         }
3743 }
3744
3745 void
3746 Editor::edit_xfade (boost::weak_ptr<Crossfade> wxfade)
3747 {
3748         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3749
3750         if (!xfade) {
3751                 return;
3752         }
3753
3754         CrossfadeEditor cew (*session, xfade, xfade->fade_in().get_min_y(), 1.0);
3755                 
3756         ensure_float (cew);
3757         
3758         switch (cew.run ()) {
3759         case RESPONSE_ACCEPT:
3760                 break;
3761         default:
3762                 return;
3763         }
3764         
3765         cew.apply ();
3766         xfade->StateChanged (Change (~0));
3767 }
3768
3769 PlaylistSelector&
3770 Editor::playlist_selector () const
3771 {
3772         return *_playlist_selector;
3773 }
3774
3775 nframes64_t
3776 Editor::get_nudge_distance (nframes64_t pos, nframes64_t& next)
3777 {
3778         nframes64_t ret;
3779
3780         ret = nudge_clock.current_duration (pos);
3781         next = ret + 1; /* XXXX fix me */
3782
3783         return ret;
3784 }
3785
3786 void
3787 Editor::end_location_changed (Location* location)
3788 {
3789         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::end_location_changed), location));
3790         //reset_scrolling_region ();
3791         nframes64_t session_span = location->start() + (nframes64_t) floorf (current_page_frames() * 0.10f);
3792         horizontal_adjustment.set_upper (session_span / frames_per_unit);
3793 }
3794
3795 int
3796 Editor::playlist_deletion_dialog (boost::shared_ptr<Playlist> pl)
3797 {
3798         ArdourDialog dialog ("playlist deletion dialog");
3799         Label  label (string_compose (_("Playlist %1 is currently unused.\n"
3800                                         "If left alone, no audio files used by it will be cleaned.\n"
3801                                         "If deleted, audio files used by it alone by will cleaned."),
3802                                       pl->name()));
3803         
3804         dialog.set_position (WIN_POS_CENTER);
3805         dialog.get_vbox()->pack_start (label);
3806
3807         label.show ();
3808
3809         dialog.add_button (_("Delete playlist"), RESPONSE_ACCEPT);
3810         dialog.add_button (_("Keep playlist"), RESPONSE_REJECT);
3811         dialog.add_button (_("Cancel"), RESPONSE_CANCEL);
3812
3813         switch (dialog.run ()) {
3814         case RESPONSE_ACCEPT:
3815                 /* delete the playlist */
3816                 return 0;
3817                 break;
3818
3819         case RESPONSE_REJECT:
3820                 /* keep the playlist */
3821                 return 1;
3822                 break;
3823
3824         default:
3825                 break;
3826         }
3827
3828         return -1;
3829 }
3830
3831 bool
3832 Editor::audio_region_selection_covers (nframes64_t where)
3833 {
3834         for (RegionSelection::iterator a = selection->regions.begin(); a != selection->regions.end(); ++a) {
3835                 if ((*a)->region()->covers (where)) {
3836                         return true;
3837                 }
3838         }
3839
3840         return false;
3841 }
3842
3843 void
3844 Editor::prepare_for_cleanup ()
3845 {
3846         cut_buffer->clear_regions ();
3847         cut_buffer->clear_playlists ();
3848
3849         selection->clear_regions ();
3850         selection->clear_playlists ();
3851
3852         no_region_list_redisplay = true;
3853 }
3854
3855 void
3856 Editor::finish_cleanup ()
3857 {
3858         no_region_list_redisplay = false;
3859         redisplay_regions ();
3860 }
3861
3862 Location*
3863 Editor::transport_loop_location()
3864 {
3865         if (session) {
3866                 return session->locations()->auto_loop_location();
3867         } else {
3868                 return 0;
3869         }
3870 }
3871
3872 Location*
3873 Editor::transport_punch_location()
3874 {
3875         if (session) {
3876                 return session->locations()->auto_punch_location();
3877         } else {
3878                 return 0;
3879         }
3880 }
3881
3882 bool
3883 Editor::control_layout_scroll (GdkEventScroll* ev)
3884 {
3885         switch (ev->direction) {
3886         case GDK_SCROLL_UP:
3887                 scroll_tracks_up_line ();
3888                 return true;
3889                 break;
3890
3891         case GDK_SCROLL_DOWN:
3892                 scroll_tracks_down_line ();
3893                 return true;
3894                 
3895         default:
3896                 /* no left/right handling yet */
3897                 break;
3898         }
3899
3900         return false;
3901 }
3902
3903
3904 /** A new snapshot has been selected.
3905  */
3906 void
3907 Editor::snapshot_display_selection_changed ()
3908 {
3909         if (snapshot_display.get_selection()->count_selected_rows() > 0) {
3910
3911                 TreeModel::iterator i = snapshot_display.get_selection()->get_selected();
3912                 
3913                 Glib::ustring snap_name = (*i)[snapshot_display_columns.real_name];
3914
3915                 if (snap_name.length() == 0) {
3916                         return;
3917                 }
3918                 
3919                 if (session->snap_name() == snap_name) {
3920                         return;
3921                 }
3922                 
3923                 ARDOUR_UI::instance()->load_session(session->path(), string (snap_name));
3924         }
3925 }
3926
3927 bool
3928 Editor::snapshot_display_button_press (GdkEventButton* ev)
3929 {
3930         if (ev->button == 3) {
3931                 /* Right-click on the snapshot list. Work out which snapshot it
3932                    was over. */
3933                 Gtk::TreeModel::Path path;
3934                 Gtk::TreeViewColumn* col;
3935                 int cx;
3936                 int cy;
3937                 snapshot_display.get_path_at_pos ((int) ev->x, (int) ev->y, path, col, cx, cy);
3938                 Gtk::TreeModel::iterator iter = snapshot_display_model->get_iter (path);
3939                 if (iter) {
3940                         Gtk::TreeModel::Row row = *iter;
3941                         popup_snapshot_context_menu (ev->button, ev->time, row[snapshot_display_columns.real_name]);
3942                 }
3943                 return true;
3944         }
3945
3946         return false;
3947 }
3948
3949
3950 /** Pop up the snapshot display context menu.
3951  * @param button Button used to open the menu.
3952  * @param time Menu open time.
3953  * @snapshot_name Name of the snapshot that the menu click was over.
3954  */
3955
3956 void
3957 Editor::popup_snapshot_context_menu (int button, int32_t time, Glib::ustring snapshot_name)
3958 {
3959         using namespace Menu_Helpers;
3960
3961         MenuList& items (snapshot_context_menu.items());
3962         items.clear ();
3963
3964         const bool modification_allowed = (session->snap_name() != snapshot_name && session->name() != snapshot_name);
3965
3966         items.push_back (MenuElem (_("Remove"), bind (mem_fun (*this, &Editor::remove_snapshot), snapshot_name)));
3967         if (!modification_allowed) {
3968                 items.back().set_sensitive (false);
3969         }
3970
3971         items.push_back (MenuElem (_("Rename"), bind (mem_fun (*this, &Editor::rename_snapshot), snapshot_name)));
3972         if (!modification_allowed) {
3973                 items.back().set_sensitive (false);
3974         }
3975
3976         snapshot_context_menu.popup (button, time);
3977 }
3978
3979 void
3980 Editor::rename_snapshot (Glib::ustring old_name)
3981 {
3982         ArdourPrompter prompter(true);
3983
3984         string new_name;
3985
3986         prompter.set_name ("Prompter");
3987         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
3988         prompter.set_prompt (_("New name of snapshot"));
3989         prompter.set_initial_text (old_name);
3990         
3991         if (prompter.run() == RESPONSE_ACCEPT) {
3992                 prompter.get_result (new_name);
3993                 if (new_name.length()) {
3994                         session->rename_state (old_name, new_name);
3995                         redisplay_snapshots ();
3996                 }
3997         }
3998 }
3999
4000
4001 void
4002 Editor::remove_snapshot (Glib::ustring name)
4003 {
4004         vector<string> choices;
4005
4006         std::string prompt  = string_compose (_("Do you really want to remove snapshot \"%1\" ?\n(cannot be undone)"), name);
4007
4008         choices.push_back (_("No, do nothing."));
4009         choices.push_back (_("Yes, remove it."));
4010
4011         Gtkmm2ext::Choice prompter (prompt, choices);
4012
4013         if (prompter.run () == 1) {
4014                 session->remove_state (name);
4015                 redisplay_snapshots ();
4016         }
4017 }
4018
4019 void
4020 Editor::redisplay_snapshots ()
4021 {
4022         if (session == 0) {
4023                 return;
4024         }
4025
4026         vector<string*>* states;
4027
4028         if ((states = session->possible_states()) == 0) {
4029                 return;
4030         }
4031
4032         snapshot_display_model->clear ();
4033
4034         for (vector<string*>::iterator i = states->begin(); i != states->end(); ++i) {
4035                 string statename = *(*i);
4036                 TreeModel::Row row = *(snapshot_display_model->append());
4037                 
4038                 /* this lingers on in case we ever want to change the visible
4039                    name of the snapshot.
4040                 */
4041                 
4042                 string display_name;
4043                 display_name = statename;
4044
4045                 if (statename == session->snap_name()) {
4046                         snapshot_display.get_selection()->select(row);
4047                 } 
4048                 
4049                 row[snapshot_display_columns.visible_name] = display_name;
4050                 row[snapshot_display_columns.real_name] = statename;
4051         }
4052
4053         delete states;
4054 }
4055
4056 void
4057 Editor::session_state_saved (string snap_name)
4058 {
4059         ENSURE_GUI_THREAD (bind (mem_fun(*this, &Editor::session_state_saved), snap_name));
4060         redisplay_snapshots ();
4061 }
4062
4063 void
4064 Editor::maximise_editing_space ()
4065 {
4066         mouse_mode_tearoff->set_visible (false);
4067         tools_tearoff->set_visible (false);
4068
4069         pre_maximal_pane_position = edit_pane.get_position();
4070         pre_maximal_editor_width = this->get_width();
4071
4072         if(post_maximal_pane_position == 0) {
4073                 post_maximal_pane_position = edit_pane.get_width();
4074         }
4075
4076         fullscreen();
4077
4078         if(post_maximal_editor_width) {
4079                 edit_pane.set_position (post_maximal_pane_position - 
4080                         abs(post_maximal_editor_width - pre_maximal_editor_width));
4081         } else {
4082                 edit_pane.set_position (post_maximal_pane_position);
4083         }
4084 }
4085
4086 void
4087 Editor::restore_editing_space ()
4088 {
4089         // user changed width of pane during fullscreen
4090         if(post_maximal_pane_position != edit_pane.get_position()) {
4091                 post_maximal_pane_position = edit_pane.get_position();
4092         }
4093
4094         unfullscreen();
4095
4096         mouse_mode_tearoff->set_visible (true);
4097         tools_tearoff->set_visible (true);
4098         post_maximal_editor_width = this->get_width();
4099
4100
4101         edit_pane.set_position (
4102                 pre_maximal_pane_position + abs(this->get_width() - pre_maximal_editor_width)
4103         );
4104 }
4105
4106 /**
4107  *  Make new playlists for a given track and also any others that belong
4108  *  to the same active edit group.
4109  *  @param v Track.
4110  */
4111
4112 void 
4113 Editor::new_playlists (TimeAxisView* v)
4114 {
4115         begin_reversible_command (_("new playlists"));
4116         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4117         session->get_playlists(playlists);
4118         mapover_audio_tracks ( bind(mem_fun (*this, &Editor::mapped_use_new_playlist), playlists), v );
4119         commit_reversible_command ();
4120 }
4121
4122
4123 /**
4124  *  Use a copy of the current playlist for a given track and also any others that belong
4125  *  to the same active edit group.
4126  *  @param v Track.
4127  */
4128
4129 void
4130 Editor::copy_playlists (TimeAxisView* v)
4131 {
4132         begin_reversible_command (_("copy playlists"));
4133         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4134         session->get_playlists(playlists);
4135         mapover_audio_tracks ( bind(mem_fun (*this, &Editor::mapped_use_copy_playlist), playlists), v );
4136         commit_reversible_command ();
4137 }
4138
4139
4140 /**
4141  *  Clear the current playlist 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::clear_playlists (TimeAxisView* v)
4148 {
4149         begin_reversible_command (_("clear playlists"));
4150         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4151         session->get_playlists(playlists);
4152         mapover_audio_tracks ( mem_fun (*this, &Editor::mapped_clear_playlist), v );
4153         commit_reversible_command ();
4154 }
4155
4156 void 
4157 Editor::mapped_use_new_playlist (AudioTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4158 {
4159         atv.use_new_playlist (sz > 1 ? false : true, playlists);
4160 }
4161
4162 void
4163 Editor::mapped_use_copy_playlist (AudioTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4164 {
4165         atv.use_copy_playlist (sz > 1 ? false : true, playlists);
4166 }
4167
4168 void 
4169 Editor::mapped_clear_playlist (AudioTimeAxisView& atv, uint32_t sz)
4170 {
4171         atv.clear_playlist ();
4172 }
4173
4174 bool
4175 Editor::on_key_press_event (GdkEventKey* ev)
4176 {
4177         return key_press_focus_accelerator_handler (*this, ev);
4178 }
4179
4180 bool
4181 Editor::on_key_release_event (GdkEventKey* ev)
4182 {
4183         return Gtk::Window::on_key_release_event (ev);
4184         // return key_press_focus_accelerator_handler (*this, ev);
4185 }
4186
4187 void
4188 Editor::reset_x_origin (nframes64_t frame)
4189 {
4190         //cerr << "resetting x origin" << endl;
4191         queue_visual_change (frame);
4192 }
4193
4194 void
4195 Editor::reset_zoom (double fpu)
4196 {
4197         queue_visual_change (fpu);
4198 }
4199
4200 void
4201 Editor::reposition_and_zoom (nframes64_t frame, double fpu)
4202 {
4203         //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
4204         reset_x_origin (frame);
4205         reset_zoom (fpu);
4206
4207         if (!no_save_visual) {
4208                 undo_visual_stack.push_back (current_visual_state(false));
4209         }
4210 }
4211
4212 Editor::VisualState*
4213 Editor::current_visual_state (bool with_tracks)
4214 {
4215         VisualState* vs = new VisualState;
4216         vs->y_position = vertical_adjustment.get_value();
4217         vs->frames_per_unit = frames_per_unit;
4218         vs->leftmost_frame = leftmost_frame;
4219         vs->zoom_focus = zoom_focus;
4220         vs->zoomed_to_region = zoomed_to_region;
4221
4222         if (with_tracks) {
4223                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4224                         vs->track_states.push_back (TAVState ((*i), &(*i)->get_state()));
4225                 }
4226         }
4227         
4228         return vs;
4229 }
4230
4231 void
4232 Editor::undo_visual_state ()
4233 {
4234         if (undo_visual_stack.empty()) {
4235                 return;
4236         }
4237
4238         VisualState* vs = undo_visual_stack.back();
4239         undo_visual_stack.pop_back();
4240         use_visual_state (*vs);
4241         redo_visual_stack.push_back (vs);
4242 }
4243
4244 void
4245 Editor::redo_visual_state ()
4246 {
4247         if (redo_visual_stack.empty()) {
4248                 return;
4249         }
4250
4251         VisualState* vs = redo_visual_stack.back();
4252         redo_visual_stack.pop_back();
4253         use_visual_state (*vs);
4254         undo_visual_stack.push_back (vs);
4255 }
4256
4257 void
4258 Editor::swap_visual_state ()
4259 {
4260         if (undo_visual_stack.empty()) {
4261                 redo_visual_state ();
4262         } else {
4263                 undo_visual_state ();
4264         }
4265 }
4266
4267 void
4268 Editor::use_visual_state (VisualState& vs)
4269 {
4270         no_save_visual = true;
4271         no_route_list_redisplay = true;
4272
4273         vertical_adjustment.set_value (vs.y_position);
4274
4275         set_zoom_focus (vs.zoom_focus);
4276         reposition_and_zoom (vs.leftmost_frame, vs.frames_per_unit);
4277         zoomed_to_region = vs.zoomed_to_region;
4278         
4279         for (list<TAVState>::iterator i = vs.track_states.begin(); i != vs.track_states.end(); ++i) {
4280                 TrackViewList::iterator t;
4281
4282                 /* check if the track still exists - it could have been deleted */
4283
4284                 if ((t = find (track_views.begin(), track_views.end(), i->first)) != track_views.end()) {
4285                         (*t)->set_state (*(i->second));
4286                 }
4287         }
4288
4289         if (!vs.track_states.empty()) {
4290                 update_route_visibility ();
4291         } 
4292
4293         no_route_list_redisplay = false;
4294         redisplay_route_list ();
4295
4296         no_save_visual = false;
4297 }
4298
4299 void
4300 Editor::set_frames_per_unit (double fpu)
4301 {
4302         /* this is the core function that controls the zoom level of the canvas. it is called
4303            whenever one or more calls are made to reset_zoom(). it executes in an idle handler.
4304         */
4305
4306         if (fpu == frames_per_unit) {
4307                 return;
4308         }
4309
4310         if (fpu < 2.0) {
4311                 fpu = 2.0;
4312         }
4313
4314         
4315         /* don't allow zooms that fit more than the maximum number
4316            of frames into an 800 pixel wide space.
4317         */
4318
4319         if (max_frames / fpu < 800.0) {
4320                 return;
4321         }
4322
4323         if (tempo_lines) {
4324                 tempo_lines->tempo_map_changed();
4325         }
4326
4327         frames_per_unit = fpu;
4328         post_zoom ();
4329 }
4330
4331 void
4332 Editor::post_zoom ()
4333 {
4334         nframes64_t cef = 0;
4335 /*
4336         // convert fpu to frame count
4337
4338         nframes64_t frames = (nframes64_t) floor (frames_per_unit * canvas_width);
4339         
4340         if (frames_per_unit != zoom_range_clock.current_duration()) {
4341                 zoom_range_clock.set (frames);
4342         }
4343 */
4344         if (mouse_mode == MouseRange && selection->time.start () != selection->time.end_frame ()) {
4345                 if (!selection->tracks.empty()) {
4346                         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4347                                 (*i)->reshow_selection (selection->time);
4348                         }
4349                 } else {
4350                         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4351                                 (*i)->reshow_selection (selection->time);
4352                         }
4353                 }
4354         }
4355         update_loop_range_view (false);
4356         update_punch_range_view (false);
4357
4358         if (playhead_cursor) {
4359                 playhead_cursor->set_position (playhead_cursor->current_frame);
4360         }
4361
4362         ZoomChanged (); /* EMIT_SIGNAL */
4363
4364         reset_hscrollbar_stepping ();
4365
4366         if (session) {
4367                 cef = session->current_end_frame() + (current_page_frames() / 10);// Add a little extra so we can see the end marker
4368         }
4369         horizontal_adjustment.set_upper (cef / frames_per_unit);
4370
4371         //reset_scrolling_region ();
4372
4373         instant_save ();
4374 }
4375
4376 void
4377 Editor::queue_visual_change (nframes64_t where)
4378 {
4379 //      pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::TimeOrigin);
4380 //      pending_visual_change.time_origin = where;
4381
4382         if (pending_visual_change.idle_handler_id < 0) {
4383                 pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::TimeOrigin);
4384                 pending_visual_change.time_origin = where;
4385                 pending_visual_change.idle_handler_id = g_idle_add (_idle_visual_changer, this);
4386         }
4387 }
4388
4389 void
4390 Editor::queue_visual_change (double fpu)
4391 {
4392         pending_visual_change.pending = VisualChange::Type (pending_visual_change.pending | VisualChange::ZoomLevel);
4393         pending_visual_change.frames_per_unit = fpu;
4394
4395         if (pending_visual_change.idle_handler_id < 0) {
4396                 pending_visual_change.idle_handler_id = g_idle_add_full (G_PRIORITY_HIGH_IDLE, _idle_visual_changer, this, 0);
4397         }
4398 }
4399
4400 int
4401 Editor::_idle_visual_changer (void* arg)
4402 {
4403         return static_cast<Editor*>(arg)->idle_visual_changer ();
4404 }
4405
4406 int
4407 Editor::idle_visual_changer ()
4408 {
4409         VisualChange::Type p = pending_visual_change.pending;
4410         pending_visual_change.pending = (VisualChange::Type) 0;
4411
4412
4413         if (p & VisualChange::ZoomLevel) {
4414                 set_frames_per_unit (pending_visual_change.frames_per_unit);
4415         }
4416
4417         if (p & VisualChange::TimeOrigin) {
4418                 horizontal_adjustment.set_value (pending_visual_change.time_origin / frames_per_unit);
4419         }
4420
4421         //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
4422         pending_visual_change.idle_handler_id = -1;
4423         return 0; /* this is always a one-shot call */
4424 }
4425
4426 struct EditorOrderTimeAxisSorter {
4427     bool operator() (const TimeAxisView* a, const TimeAxisView* b) const {
4428             return a->order < b->order;
4429     }
4430 };
4431         
4432 void
4433 Editor::sort_track_selection (TrackSelection* sel)
4434 {
4435         EditorOrderTimeAxisSorter cmp;
4436
4437         if (sel) {
4438                 sel->sort (cmp);
4439         } else {
4440                 selection->tracks.sort (cmp);
4441         }
4442 }
4443
4444 nframes64_t
4445 Editor::get_preferred_edit_position (bool ignore_playhead)
4446 {
4447         bool ignored;
4448         nframes64_t where = 0;
4449         EditPoint ep = _edit_point;
4450
4451         if (entered_marker) {
4452                 return entered_marker->position();
4453         }
4454
4455         if (ignore_playhead && ep == EditAtPlayhead) {
4456                 ep = EditAtSelectedMarker;
4457         }
4458
4459         switch (ep) {
4460         case EditAtPlayhead:
4461                 where = session->audible_frame();
4462                 break;
4463                 
4464         case EditAtSelectedMarker:
4465                 if (!selection->markers.empty()) {
4466                         bool is_start;
4467                         Location* loc = find_location_from_marker (selection->markers.front(), is_start);
4468                         if (loc) {
4469                                 if (is_start) {
4470                                         where =  loc->start();
4471                                 } else {
4472                                         where = loc->end();
4473                                 }
4474                                 break;
4475                         }
4476                 } 
4477                 /* fallthru */
4478                 
4479         default:
4480         case EditAtMouse:
4481                 if (!mouse_frame (where, ignored)) {
4482                         /* XXX not right but what can we do ? */
4483                         return 0;
4484                 }
4485                 snap_to (where);
4486                 break;
4487         }
4488
4489         return where;
4490 }
4491
4492 void
4493 Editor::set_loop_range (nframes64_t start, nframes64_t end, string cmd)
4494 {
4495         if (!session) return;
4496
4497         begin_reversible_command (cmd);
4498         
4499         Location* tll;
4500
4501         if ((tll = transport_loop_location()) == 0) {
4502                 Location* loc = new Location (start, end, _("Loop"),  Location::IsAutoLoop);
4503                 XMLNode &before = session->locations()->get_state();
4504                 session->locations()->add (loc, true);
4505                 session->set_auto_loop_location (loc);
4506                 XMLNode &after = session->locations()->get_state();
4507                 session->add_command (new MementoCommand<Locations>(*(session->locations()), &before, &after));
4508         } else {
4509                 XMLNode &before = tll->get_state();
4510                 tll->set_hidden (false, this);
4511                 tll->set (start, end);
4512                 XMLNode &after = tll->get_state();
4513                 session->add_command (new MementoCommand<Location>(*tll, &before, &after));
4514         }
4515         
4516         commit_reversible_command ();
4517 }
4518
4519 void
4520 Editor::set_punch_range (nframes64_t start, nframes64_t end, string cmd)
4521 {
4522         if (!session) return;
4523
4524         begin_reversible_command (cmd);
4525         
4526         Location* tpl;
4527
4528         if ((tpl = transport_punch_location()) == 0) {
4529                 Location* loc = new Location (start, end, _("Loop"),  Location::IsAutoPunch);
4530                 XMLNode &before = session->locations()->get_state();
4531                 session->locations()->add (loc, true);
4532                 session->set_auto_loop_location (loc);
4533                 XMLNode &after = session->locations()->get_state();
4534                 session->add_command (new MementoCommand<Locations>(*(session->locations()), &before, &after));
4535         }
4536         else {
4537                 XMLNode &before = tpl->get_state();
4538                 tpl->set_hidden (false, this);
4539                 tpl->set (start, end);
4540                 XMLNode &after = tpl->get_state();
4541                 session->add_command (new MementoCommand<Location>(*tpl, &before, &after));
4542         }
4543         
4544         commit_reversible_command ();
4545 }
4546
4547 void
4548 Editor::get_regions_at (RegionSelection& rs, nframes64_t where, const TrackSelection& ts) const
4549 {
4550         const TrackSelection* tracks;
4551
4552         if (ts.empty()) {
4553                 tracks = &track_views;
4554         } else {
4555                 tracks = &ts;
4556         }
4557
4558         for (TrackSelection::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
4559         
4560                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(*t);
4561
4562                 if (atv) {
4563                         boost::shared_ptr<Diskstream> ds;
4564                         boost::shared_ptr<Playlist> pl;
4565                         
4566                         if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()))) {
4567
4568                                 Playlist::RegionList* regions = pl->regions_at ((nframes64_t) floor ( (double)where * ds->speed()));
4569
4570                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
4571
4572                                         RegionView* rv = atv->audio_view()->find_view (*i);
4573
4574                                         if (rv) {
4575                                                 rs.add (rv);
4576                                         }
4577                                 }
4578
4579                                 delete regions;
4580                         }
4581                 }
4582         }
4583 }
4584
4585 void
4586 Editor::get_regions_after (RegionSelection& rs, nframes64_t where, const TrackSelection& ts) const
4587 {
4588         const TrackSelection* tracks;
4589
4590         if (ts.empty()) {
4591                 tracks = &track_views;
4592         } else {
4593                 tracks = &ts;
4594         }
4595
4596         for (TrackSelection::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
4597         
4598                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(*t);
4599
4600                 if (atv) {
4601                         boost::shared_ptr<Diskstream> ds;
4602                         boost::shared_ptr<Playlist> pl;
4603                         
4604                         if ((ds = atv->get_diskstream()) && ((pl = ds->playlist()))) {
4605
4606                                 Playlist::RegionList* regions = pl->regions_touched ((nframes64_t) floor ( (double)where * ds->speed()), max_frames);
4607
4608                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
4609
4610                                         RegionView* rv = atv->audio_view()->find_view (*i);
4611
4612                                         if (rv) {
4613                                                 rs.push_back (rv);
4614                                         }
4615                                 }
4616
4617                                 delete regions;
4618                         }
4619                 }
4620         }
4621 }
4622
4623 void
4624 Editor::get_regions_for_action (RegionSelection& rs, bool allow_entered)
4625 {
4626         if (selection->regions.empty()) {
4627
4628                 if (selection->tracks.empty()) {
4629
4630                         /* no regions or tracks selected
4631                         */
4632                         
4633                         if (entered_regionview && mouse_mode == Editing::MouseObject) {
4634
4635                                 /*  entered regionview is valid and we're in object mode - 
4636                                     just use entered regionview
4637                                 */
4638
4639                                 rs.add (entered_regionview);
4640                         }
4641
4642                         return;
4643
4644                 } else {
4645
4646                         /* no regions selected, so get all regions at the edit point across
4647                            all selected tracks. 
4648                         */
4649
4650                         nframes64_t where = get_preferred_edit_position();
4651                         get_regions_at (rs, where, selection->tracks);
4652
4653                         /* if the entered regionview wasn't selected and neither was its track
4654                            then add it.
4655                         */
4656
4657                         if (entered_regionview != 0 &&
4658                             !selection->selected (entered_regionview) && 
4659                             !selection->selected (&entered_regionview->get_time_axis_view())) {
4660                                 rs.add (entered_regionview);
4661                         }
4662                 }
4663
4664         } else {
4665                 
4666                 /* just use the selected regions */
4667
4668                 rs = selection->regions;
4669
4670                 /* if the entered regionview wasn't selected and we allow this sort of thing,
4671                    then add it.
4672                 */
4673
4674                 if (allow_entered && entered_regionview && !selection->selected (entered_regionview)) {
4675                         rs.add (entered_regionview);
4676                 }
4677
4678         }
4679 }
4680
4681 void
4682 Editor::get_regions_corresponding_to (boost::shared_ptr<Region> region, vector<RegionView*>& regions)
4683 {
4684
4685         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4686                 
4687                 RouteTimeAxisView* tatv;
4688                 
4689                 if ((tatv = dynamic_cast<RouteTimeAxisView*> (*i)) != 0) {
4690                         
4691                         boost::shared_ptr<Playlist> pl;
4692                         vector<boost::shared_ptr<Region> > results;
4693                         RegionView* marv;
4694                         boost::shared_ptr<Diskstream> ds;
4695                         
4696                         if ((ds = tatv->get_diskstream()) == 0) {
4697                                 /* bus */
4698                                 continue;
4699                         }
4700                         
4701                         if ((pl = (ds->playlist())) != 0) {
4702                                 pl->get_region_list_equivalent_regions (region, results);
4703                         }
4704                         
4705                         for (vector<boost::shared_ptr<Region> >::iterator ir = results.begin(); ir != results.end(); ++ir) {
4706                                 if ((marv = tatv->view()->find_view (*ir)) != 0) {
4707                                         regions.push_back (marv);
4708                                 }
4709                         }
4710                         
4711                 }
4712         }
4713 }       
4714
4715 void
4716 Editor::show_rhythm_ferret ()
4717 {
4718         if (rhythm_ferret == 0) {
4719                 rhythm_ferret = new RhythmFerret(*this);
4720         }
4721
4722         rhythm_ferret->set_session (session);
4723         rhythm_ferret->show ();
4724         rhythm_ferret->present ();
4725 }
4726
4727 void
4728 Editor::first_idle ()
4729 {
4730         MessageDialog* dialog = 0;
4731
4732         if (track_views.size() > 1) { 
4733                 dialog = new MessageDialog (*this, 
4734                                             _("Please wait while Ardour loads visual data"),
4735                                             true,
4736                                             Gtk::MESSAGE_INFO,
4737                                             Gtk::BUTTONS_NONE);
4738                 dialog->present ();
4739                 ARDOUR_UI::instance()->flush_pending ();
4740         }
4741
4742         for (TrackViewList::iterator t = track_views.begin(); t != track_views.end(); ++t) {
4743                 (*t)->first_idle();
4744         }
4745
4746         // first idle adds route children (automation tracks), so we need to redisplay here
4747         redisplay_route_list();
4748         
4749         if (dialog) {
4750                 delete dialog;
4751         }
4752
4753         _have_idled = true;
4754 }
4755
4756 void
4757 Editor::start_resize_line_ops ()
4758 {
4759 #if 0
4760         old_resize_line_y = -1;
4761         resize_line_y = -1;
4762         need_resize_line = true;
4763 #endif  
4764 }
4765
4766 void
4767 Editor::end_resize_line_ops ()
4768 {
4769 #if 0
4770         need_resize_line = false;
4771
4772         if (old_resize_line_y >= 0) {
4773                 Gdk::Rectangle r (0, old_resize_line_y, (int) canvas_width, 3);
4774                 Glib::RefPtr<Gdk::Window> win = get_window();
4775                 cerr << "Final invalidation at " << old_resize_line_y << endl;
4776                 win->invalidate_rect (r, false);
4777         }
4778 #endif
4779 }
4780
4781 void
4782 Editor::queue_draw_resize_line (int at)
4783 {
4784 #if 0   
4785         Glib::RefPtr<Gdk::Window> win = get_window();
4786
4787         resize_line_y = at;
4788
4789         if (win && canvas_width) {
4790
4791                 int controls_width = controls_layout.get_width();
4792                 int xroot, discard;
4793                 
4794                 controls_layout.get_window()->get_origin (xroot, discard);
4795
4796                 if (old_resize_line_y >= 0) {
4797                         
4798                         /* redraw where it used to be */
4799                         
4800                         
4801                         Gdk::Rectangle r (0, old_resize_line_y - 1, controls_width + (int) canvas_width, 3);
4802                         win->invalidate_rect (r, true);
4803                         cerr << "invalidate " << xroot << "," << old_resize_line_y - 1 << ' ' 
4804                              << controls_width + canvas_width << " x 3\n";
4805                 }
4806
4807                 /* draw where it is */
4808
4809                 Gdk::Rectangle r (0, at - 1, controls_width + (int) canvas_width, 3);
4810                 win->invalidate_rect (r, true);
4811         }
4812 #endif
4813 }
4814
4815 bool
4816 Editor::on_expose_event (GdkEventExpose* ev)
4817 {
4818         /* cerr << "+++ editor expose "
4819              << ev->area.x << ',' << ev->area.y
4820              << ' '
4821              << ev->area.width << " x " << ev->area.height
4822              << " need reize ? " << need_resize_line
4823              << endl;
4824         */
4825         bool ret = Window::on_expose_event (ev);
4826
4827 #if 0
4828         if (need_resize_line) {
4829                 
4830                 int xroot, yroot, discard;
4831                 int controls_width;
4832
4833                 /* Our root coordinates for drawing the line will be the left edge 
4834                    of the track controls, and the upper left edge of our own window.
4835                 */
4836
4837                 get_window()->get_origin (discard, yroot);
4838                 controls_layout.get_window()->get_origin (xroot, discard);
4839                 controls_width = controls_layout.get_width();
4840                 
4841                 GdkRectangle lr;
4842                 GdkRectangle intersection;
4843
4844                 lr.x = 0;
4845                 lr.y = resize_line_y;
4846                 lr.width = controls_width + (int) canvas_width;
4847                 lr.height = 3;
4848
4849                 if (gdk_rectangle_intersect (&lr, &ev->area, &intersection)) {
4850                         
4851                         Glib::RefPtr<Gtk::Style> style (get_style());
4852                         Glib::RefPtr<Gdk::GC> black_gc (style->get_black_gc ());
4853                         Glib::RefPtr<Gdk::GC> gc = wrap (black_gc->gobj_copy(), false);
4854
4855                         /* draw on root window */
4856
4857                         GdkWindow* win = gdk_get_default_root_window();
4858                         
4859                         gc->set_subwindow (Gdk::INCLUDE_INFERIORS);
4860                         gc->set_line_attributes (3, Gdk::LINE_SOLID, 
4861                                                  Gdk::CAP_NOT_LAST,
4862                                                  Gdk::JOIN_MITER);
4863                         
4864                         gdk_draw_line (win, gc->gobj(), 
4865                                        0,
4866                                        resize_line_y, 
4867                                        (int) canvas_width + controls_width,
4868                                        resize_line_y);
4869 #if 0
4870                         cerr << "drew line @ " << xroot << ", " << yroot + resize_line_y 
4871                              << " to " << xroot + (int) canvas_width + controls_width
4872                              << ", " << yroot + resize_line_y
4873                              << endl;
4874 #endif
4875                         old_resize_line_y = resize_line_y;
4876                         cerr << "NEXT EXPOSE SHOULD BE AT " << old_resize_line_y << endl;
4877                 } else {
4878                         cerr << "no intersect with "
4879                              << lr.x << ',' << lr.y
4880                              << ' '
4881                              << lr.width << " x " << lr.height
4882                              << endl;
4883                 }
4884         }
4885
4886         //cerr << "--- editor expose\n";
4887 #endif
4888
4889         return ret;
4890 }
4891
4892 static gboolean
4893 _idle_resizer (gpointer arg)
4894 {
4895         return ((Editor*)arg)->idle_resize ();
4896 }
4897
4898 void
4899 Editor::add_to_idle_resize (TimeAxisView* view, uint32_t h)
4900 {
4901         if (resize_idle_id < 0) {
4902                 resize_idle_id = g_idle_add (_idle_resizer, this);
4903         }
4904
4905         resize_idle_target = h;
4906
4907         pending_resizes.push_back (view);
4908
4909         if (selection->selected (view) && !selection->tracks.empty()) {
4910                 pending_resizes.insert (pending_resizes.end(), selection->tracks.begin(), selection->tracks.end());
4911         }
4912 }
4913
4914 bool
4915 Editor::idle_resize ()
4916 {
4917         for (vector<TimeAxisView*>::iterator i = pending_resizes.begin(); i != pending_resizes.end(); ++i) {
4918                 (*i)->idle_resize (resize_idle_target);
4919         }
4920         pending_resizes.clear();
4921         resize_idle_id = -1;
4922         return false;
4923 }