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