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