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