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