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