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