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