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