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