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