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