Allow markers to be glued to bar/beat time. Fixes #1815.
[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->StepEditStatusChange.connect (_session_connections, invalidator (*this), ui_bind(&Editor::step_edit_status_change, this, _1), gui_context());
1106         _session->TransportStateChange.connect (_session_connections, invalidator (*this), boost::bind (&Editor::map_transport_state, this), gui_context());
1107         _session->PositionChanged.connect (_session_connections, invalidator (*this), ui_bind (&Editor::map_position_change, this, _1), gui_context());
1108         _session->RouteAdded.connect (_session_connections, invalidator (*this), ui_bind (&Editor::handle_new_route, this, _1), gui_context());
1109         _session->DirtyChanged.connect (_session_connections, invalidator (*this), boost::bind (&Editor::update_title, this), gui_context());
1110         _session->TimecodeOffsetChanged.connect (_session_connections, invalidator (*this), boost::bind (&Editor::update_just_timecode, this), gui_context());
1111         _session->tempo_map().PropertyChanged.connect (_session_connections, invalidator (*this), ui_bind (&Editor::tempo_map_changed, this, _1), gui_context());
1112         _session->Located.connect (_session_connections, invalidator (*this), boost::bind (&Editor::located, this), gui_context());
1113         _session->config.ParameterChanged.connect (_session_connections, invalidator (*this), ui_bind (&Editor::parameter_changed, this, _1), gui_context());
1114         _session->StateSaved.connect (_session_connections, invalidator (*this), ui_bind (&Editor::session_state_saved, this, _1), gui_context());
1115         _session->locations()->added.connect (_session_connections, invalidator (*this), ui_bind (&Editor::add_new_location, this, _1), gui_context());
1116         _session->locations()->removed.connect (_session_connections, invalidator (*this), ui_bind (&Editor::location_gone, this, _1), gui_context());
1117         _session->locations()->changed.connect (_session_connections, invalidator (*this), boost::bind (&Editor::refresh_location_display, this), gui_context());
1118         _session->locations()->StateChanged.connect (_session_connections, invalidator (*this), ui_bind (&Editor::refresh_location_display_s, this, _1), gui_context());
1119         _session->history().Changed.connect (_session_connections, invalidator (*this), boost::bind (&Editor::history_changed, this), gui_context());
1120
1121         if (Profile->get_sae()) {
1122                 BBT_Time bbt;
1123                 bbt.bars = 0;
1124                 bbt.beats = 0;
1125                 bbt.ticks = 120;
1126                 nframes_t pos = _session->tempo_map().bbt_duration_at (0, bbt, 1);
1127                 nudge_clock.set_mode(AudioClock::BBT);
1128                 nudge_clock.set (pos, true, 0, AudioClock::BBT);
1129
1130         } else {
1131                 nudge_clock.set (_session->frame_rate() * 5, true, 0, AudioClock::Timecode); // default of 5 seconds
1132         }
1133
1134         playhead_cursor->canvas_item.show ();
1135
1136         Location* loc = _session->locations()->auto_loop_location();
1137         if (loc == 0) {
1138                 loc = new Location (*_session, 0, _session->current_end_frame(), _("Loop"),(Location::Flags) (Location::IsAutoLoop | Location::IsHidden));
1139                 if (loc->start() == loc->end()) {
1140                         loc->set_end (loc->start() + 1);
1141                 }
1142                 _session->locations()->add (loc, false);
1143                 _session->set_auto_loop_location (loc);
1144         } else {
1145                 // force name
1146                 loc->set_name (_("Loop"));
1147         }
1148
1149         loc = _session->locations()->auto_punch_location();
1150         if (loc == 0) {
1151                 loc = new Location (*_session, 0, _session->current_end_frame(), _("Punch"), (Location::Flags) (Location::IsAutoPunch | Location::IsHidden));
1152                 if (loc->start() == loc->end()) {
1153                         loc->set_end (loc->start() + 1);
1154                 }
1155                 _session->locations()->add (loc, false);
1156                 _session->set_auto_punch_location (loc);
1157         } else {
1158                 // force name
1159                 loc->set_name (_("Punch"));
1160         }
1161
1162         boost::function<void (string)> pc (boost::bind (&Editor::parameter_changed, this, _1));
1163         Config->map_parameters (pc);
1164         _session->config.map_parameters (pc);
1165
1166         refresh_location_display ();
1167
1168         restore_ruler_visibility ();
1169         //tempo_map_changed (PropertyChange (0));
1170         _session->tempo_map().apply_with_metrics (*this, &Editor::draw_metric_marks);
1171
1172         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
1173                 (static_cast<TimeAxisView*>(*i))->set_samples_per_unit (frames_per_unit);
1174         }
1175
1176         super_rapid_screen_update_connection = ARDOUR_UI::instance()->SuperRapidScreenUpdate.connect (
1177                 sigc::mem_fun (*this, &Editor::super_rapid_screen_update)
1178                 );
1179         
1180         switch (_snap_type) {
1181         case SnapToRegionStart:
1182         case SnapToRegionEnd:
1183         case SnapToRegionSync:
1184         case SnapToRegionBoundary:
1185                 build_region_boundary_cache ();
1186                 break;
1187
1188         default:
1189                 break;
1190         }
1191
1192         /* register for undo history */
1193         _session->register_with_memento_command_factory(_id, this);
1194
1195         start_updating_meters ();
1196 }
1197
1198 void
1199 Editor::build_cursors ()
1200 {
1201         using namespace Gdk;
1202
1203         Gdk::Color mbg ("#000000" ); /* Black */
1204         Gdk::Color mfg ("#0000ff" ); /* Blue. */
1205
1206         {
1207                 RefPtr<Bitmap> source, mask;
1208                 source = Bitmap::create (mag_bits, mag_width, mag_height);
1209                 mask = Bitmap::create (magmask_bits, mag_width, mag_height);
1210                 zoom_cursor = new Gdk::Cursor (source, mask, mfg, mbg, mag_x_hot, mag_y_hot);
1211         }
1212
1213         Gdk::Color fbg ("#ffffff" );
1214         Gdk::Color ffg  ("#000000" );
1215
1216         {
1217                 RefPtr<Bitmap> source, mask;
1218
1219                 source = Bitmap::create (fader_cursor_bits, fader_cursor_width, fader_cursor_height);
1220                 mask = Bitmap::create (fader_cursor_mask_bits, fader_cursor_width, fader_cursor_height);
1221                 fader_cursor = new Gdk::Cursor (source, mask, ffg, fbg, fader_cursor_x_hot, fader_cursor_y_hot);
1222         }
1223
1224         {
1225                 RefPtr<Bitmap> source, mask;
1226                 source = Bitmap::create (speaker_cursor_bits, speaker_cursor_width, speaker_cursor_height);
1227                 mask = Bitmap::create (speaker_cursor_mask_bits, speaker_cursor_width, speaker_cursor_height);
1228                 speaker_cursor = new Gdk::Cursor (source, mask, ffg, fbg, speaker_cursor_x_hot, speaker_cursor_y_hot);
1229         }
1230
1231         {
1232                 RefPtr<Bitmap> bits;
1233                 char pix[4] = { 0, 0, 0, 0 };
1234                 bits = Bitmap::create (pix, 2, 2);
1235                 Gdk::Color c;
1236                 transparent_cursor = new Gdk::Cursor (bits, bits, c, c, 0, 0);
1237         }
1238
1239         {
1240                 RefPtr<Bitmap> bits;
1241                 char pix[4] = { 0, 0, 0, 0 };
1242                 bits = Bitmap::create (pix, 2, 2);
1243                 Gdk::Color c;
1244                 transparent_cursor = new Gdk::Cursor (bits, bits, c, c, 0, 0);
1245         }
1246
1247
1248         grabber_cursor = new Gdk::Cursor (HAND2);
1249
1250         {
1251                 Glib::RefPtr<Gdk::Pixbuf> grabber_note_pixbuf (::get_icon ("grabber_note"));
1252                 grabber_note_cursor = new Gdk::Cursor (Gdk::Display::get_default(), grabber_note_pixbuf, 5, 10);
1253         }
1254
1255         {
1256                 Glib::RefPtr<Gdk::Pixbuf> grabber_edit_point_pixbuf (::get_icon ("grabber_edit_point"));
1257                 grabber_edit_point_cursor = new Gdk::Cursor (Gdk::Display::get_default(), grabber_edit_point_pixbuf, 5, 17);
1258         }
1259
1260         cross_hair_cursor = new Gdk::Cursor (CROSSHAIR);
1261         trimmer_cursor =  new Gdk::Cursor (SB_H_DOUBLE_ARROW);
1262
1263         {
1264                 Glib::RefPtr<Gdk::Pixbuf> apixbuf (::get_icon ("trim_left_cursor"));
1265                 left_side_trim_cursor = new Gdk::Cursor (Gdk::Display::get_default(), apixbuf, 5, 11);
1266         }
1267
1268         {
1269                 Glib::RefPtr<Gdk::Pixbuf> apixbuf (::get_icon ("trim_right_cursor"));
1270                 right_side_trim_cursor = new Gdk::Cursor (Gdk::Display::get_default(), apixbuf, 23, 11);
1271         }
1272
1273         {
1274                 Glib::RefPtr<Gdk::Pixbuf> apixbuf (::get_icon ("fade_in_cursor"));
1275                 fade_in_cursor = new Gdk::Cursor (Gdk::Display::get_default(), apixbuf, 0, 40);
1276         }
1277
1278         {
1279                 Glib::RefPtr<Gdk::Pixbuf> apixbuf (::get_icon ("fade_out_cursor"));
1280                 fade_out_cursor = new Gdk::Cursor (Gdk::Display::get_default(), apixbuf, 27, 40);
1281         }
1282
1283         selector_cursor = new Gdk::Cursor (XTERM);
1284         time_fx_cursor = new Gdk::Cursor (SIZING);
1285         wait_cursor = new Gdk::Cursor  (WATCH);
1286         timebar_cursor = new Gdk::Cursor(LEFT_PTR);
1287         midi_pencil_cursor = new Gdk::Cursor (PENCIL);
1288         midi_select_cursor = new Gdk::Cursor (CENTER_PTR);
1289         midi_resize_cursor = new Gdk::Cursor (SIZING);
1290         midi_erase_cursor = new Gdk::Cursor (DRAPED_BOX);
1291 }
1292
1293 /** Pop up a context menu for when the user clicks on a fade in or fade out */
1294 void
1295 Editor::popup_fade_context_menu (int button, int32_t time, ArdourCanvas::Item* item, ItemType item_type)
1296 {
1297         using namespace Menu_Helpers;
1298         AudioRegionView* arv = static_cast<AudioRegionView*> (item->get_data ("regionview"));
1299
1300         if (arv == 0) {
1301                 fatal << _("programming error: fade in canvas item has no regionview data pointer!") << endmsg;
1302                 /*NOTREACHED*/
1303         }
1304
1305         MenuList& items (fade_context_menu.items());
1306
1307         items.clear ();
1308
1309         switch (item_type) {
1310         case FadeInItem:
1311         case FadeInHandleItem:
1312                 if (arv->audio_region()->fade_in_active()) {
1313                         items.push_back (MenuElem (_("Deactivate"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_active), false)));
1314                 } else {
1315                         items.push_back (MenuElem (_("Activate"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_active), true)));
1316                 }
1317
1318                 items.push_back (SeparatorElem());
1319
1320                 if (Profile->get_sae()) {
1321                         items.push_back (MenuElem (_("Linear"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Linear)));
1322                         items.push_back (MenuElem (_("Slowest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Fast)));
1323                 } else {
1324                         items.push_back (MenuElem (_("Linear"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Linear)));
1325                         items.push_back (MenuElem (_("Slowest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Fast)));
1326                         items.push_back (MenuElem (_("Slow"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::LogB)));
1327                         items.push_back (MenuElem (_("Fast"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::LogA)));
1328                         items.push_back (MenuElem (_("Fastest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_in_shape), AudioRegion::Slow)));
1329                 }
1330
1331                 break;
1332
1333         case FadeOutItem:
1334         case FadeOutHandleItem:
1335                 if (arv->audio_region()->fade_out_active()) {
1336                         items.push_back (MenuElem (_("Deactivate"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_active), false)));
1337                 } else {
1338                         items.push_back (MenuElem (_("Activate"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_active), true)));
1339                 }
1340
1341                 items.push_back (SeparatorElem());
1342
1343                 if (Profile->get_sae()) {
1344                         items.push_back (MenuElem (_("Linear"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Linear)));
1345                         items.push_back (MenuElem (_("Slowest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Slow)));
1346                 } else {
1347                         items.push_back (MenuElem (_("Linear"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Linear)));
1348                         items.push_back (MenuElem (_("Slowest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Slow)));
1349                         items.push_back (MenuElem (_("Slow"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::LogA)));
1350                         items.push_back (MenuElem (_("Fast"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::LogB)));
1351                         items.push_back (MenuElem (_("Fastest"), sigc::bind (sigc::mem_fun (*this, &Editor::set_fade_out_shape), AudioRegion::Fast)));
1352                 }
1353
1354                 break;
1355
1356         default:
1357                 fatal << _("programming error: ")
1358                       << X_("non-fade canvas item passed to popup_fade_context_menu()")
1359                       << endmsg;
1360                 /*NOTREACHED*/
1361         }
1362
1363         fade_context_menu.popup (button, time);
1364 }
1365
1366 void
1367 Editor::popup_track_context_menu (int button, int32_t time, ItemType item_type, bool with_selection, nframes64_t frame)
1368 {
1369         using namespace Menu_Helpers;
1370         Menu* (Editor::*build_menu_function)(nframes64_t);
1371         Menu *menu;
1372
1373         switch (item_type) {
1374         case RegionItem:
1375         case RegionViewName:
1376         case RegionViewNameHighlight:
1377         case LeftFrameHandle:
1378         case RightFrameHandle:
1379                 if (with_selection) {
1380                         build_menu_function = &Editor::build_track_selection_context_menu;
1381                 } else {
1382                         build_menu_function = &Editor::build_track_region_context_menu;
1383                 }
1384                 break;
1385
1386         case SelectionItem:
1387                 if (with_selection) {
1388                         build_menu_function = &Editor::build_track_selection_context_menu;
1389                 } else {
1390                         build_menu_function = &Editor::build_track_context_menu;
1391                 }
1392                 break;
1393
1394         case CrossfadeViewItem:
1395                 build_menu_function = &Editor::build_track_crossfade_context_menu;
1396                 break;
1397
1398         case StreamItem:
1399                 if (clicked_routeview->track()) {
1400                         build_menu_function = &Editor::build_track_context_menu;
1401                 } else {
1402                         build_menu_function = &Editor::build_track_bus_context_menu;
1403                 }
1404                 break;
1405
1406         default:
1407                 /* probably shouldn't happen but if it does, we don't care */
1408                 return;
1409         }
1410
1411         menu = (this->*build_menu_function)(frame);
1412         menu->set_name ("ArdourContextMenu");
1413
1414         /* now handle specific situations */
1415
1416         switch (item_type) {
1417         case RegionItem:
1418         case RegionViewName:
1419         case RegionViewNameHighlight:
1420         case LeftFrameHandle:
1421         case RightFrameHandle:
1422                 if (!with_selection) {
1423                         if (region_edit_menu_split_item) {
1424                                 if (clicked_regionview && clicked_regionview->region()->covers (get_preferred_edit_position())) {
1425                                         ActionManager::set_sensitive (ActionManager::edit_point_in_region_sensitive_actions, true);
1426                                 } else {
1427                                         ActionManager::set_sensitive (ActionManager::edit_point_in_region_sensitive_actions, false);
1428                                 }
1429                         }
1430                         if (region_edit_menu_split_multichannel_item) {
1431                                 if (clicked_regionview && clicked_regionview->region()->n_channels() > 1) {
1432                                         region_edit_menu_split_multichannel_item->set_sensitive (true);
1433                                 } else {
1434                                         region_edit_menu_split_multichannel_item->set_sensitive (false);
1435                                 }
1436                         }
1437                 }
1438                 break;
1439
1440         case SelectionItem:
1441                 break;
1442
1443         case CrossfadeViewItem:
1444                 break;
1445
1446         case StreamItem:
1447                 break;
1448
1449         default:
1450                 /* probably shouldn't happen but if it does, we don't care */
1451                 return;
1452         }
1453
1454         if (item_type != SelectionItem && clicked_routeview && clicked_routeview->audio_track()) {
1455
1456                 /* Bounce to disk */
1457
1458                 using namespace Menu_Helpers;
1459                 MenuList& edit_items  = menu->items();
1460
1461                 edit_items.push_back (SeparatorElem());
1462
1463                 switch (clicked_routeview->audio_track()->freeze_state()) {
1464                 case AudioTrack::NoFreeze:
1465                         edit_items.push_back (MenuElem (_("Freeze"), sigc::mem_fun(*this, &Editor::freeze_route)));
1466                         break;
1467
1468                 case AudioTrack::Frozen:
1469                         edit_items.push_back (MenuElem (_("Unfreeze"), sigc::mem_fun(*this, &Editor::unfreeze_route)));
1470                         break;
1471
1472                 case AudioTrack::UnFrozen:
1473                         edit_items.push_back (MenuElem (_("Freeze"), sigc::mem_fun(*this, &Editor::freeze_route)));
1474                         break;
1475                 }
1476
1477         }
1478
1479         if (item_type == StreamItem && clicked_routeview) {
1480                 clicked_routeview->build_underlay_menu(menu);
1481         }
1482
1483         menu->popup (button, time);
1484 }
1485
1486 Menu*
1487 Editor::build_track_context_menu (nframes64_t)
1488 {
1489         using namespace Menu_Helpers;
1490
1491         MenuList& edit_items = track_context_menu.items();
1492         edit_items.clear();
1493
1494         add_dstream_context_items (edit_items);
1495         return &track_context_menu;
1496 }
1497
1498 Menu*
1499 Editor::build_track_bus_context_menu (nframes64_t)
1500 {
1501         using namespace Menu_Helpers;
1502
1503         MenuList& edit_items = track_context_menu.items();
1504         edit_items.clear();
1505
1506         add_bus_context_items (edit_items);
1507         return &track_context_menu;
1508 }
1509
1510 Menu*
1511 Editor::build_track_region_context_menu (nframes64_t frame)
1512 {
1513         using namespace Menu_Helpers;
1514         MenuList& edit_items  = track_region_context_menu.items();
1515         edit_items.clear();
1516
1517         /* we've just cleared the track region context menu, so the menu that these
1518            two items were on will have disappeared; stop them dangling.
1519         */
1520         region_edit_menu_split_item = 0;
1521         region_edit_menu_split_multichannel_item = 0;
1522
1523         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (clicked_axisview);
1524
1525         if (rtv) {
1526                 boost::shared_ptr<Track> tr;
1527                 boost::shared_ptr<Playlist> pl;
1528
1529                 /* Don't offer a region submenu if we are in internal edit mode, as we don't select regions in this
1530                    mode and so offering region context is somewhat confusing.
1531                 */
1532                 if ((tr = rtv->track()) && ((pl = tr->playlist())) && !internal_editing()) {
1533                         Playlist::RegionList* regions = pl->regions_at ((nframes64_t) floor ( (double)frame * tr->speed()));
1534
1535                         if (selection->regions.size() > 1) {
1536                                 // there's already a multiple selection: just add a
1537                                 // single region context menu that will act on all
1538                                 // selected regions
1539                                 boost::shared_ptr<Region> dummy_region; // = NULL
1540                                 add_region_context_items (rtv->view(), dummy_region, edit_items);
1541                         } else {
1542                                 for (Playlist::RegionList::reverse_iterator i = regions->rbegin(); i != regions->rend(); ++i) {
1543                                         add_region_context_items (rtv->view(), (*i), edit_items);
1544                                 }
1545                         }
1546
1547                         delete regions;
1548                 }
1549         }
1550
1551         add_dstream_context_items (edit_items);
1552
1553         return &track_region_context_menu;
1554 }
1555
1556 Menu*
1557 Editor::build_track_crossfade_context_menu (nframes64_t frame)
1558 {
1559         using namespace Menu_Helpers;
1560         MenuList& edit_items  = track_crossfade_context_menu.items();
1561         edit_items.clear ();
1562
1563         AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*> (clicked_axisview);
1564
1565         if (atv) {
1566                 boost::shared_ptr<Track> tr;
1567                 boost::shared_ptr<Playlist> pl;
1568                 boost::shared_ptr<AudioPlaylist> apl;
1569
1570                 if ((tr = atv->track()) && ((pl = tr->playlist()) != 0) && ((apl = boost::dynamic_pointer_cast<AudioPlaylist> (pl)) != 0)) {
1571
1572                         Playlist::RegionList* regions = pl->regions_at (frame);
1573                         AudioPlaylist::Crossfades xfades;
1574
1575                         apl->crossfades_at (frame, xfades);
1576
1577                         bool many = xfades.size() > 1;
1578
1579                         for (AudioPlaylist::Crossfades::iterator i = xfades.begin(); i != xfades.end(); ++i) {
1580                                 add_crossfade_context_items (atv->audio_view(), (*i), edit_items, many);
1581                         }
1582
1583                         if (selection->regions.size() > 1) {
1584                                 // there's already a multiple selection: just add a
1585                                 // single region context menu that will act on all
1586                                 // selected regions
1587                                 boost::shared_ptr<Region> dummy_region; // = NULL
1588                                 add_region_context_items (atv->audio_view(), dummy_region, edit_items);
1589                         } else {
1590                                 for (Playlist::RegionList::reverse_iterator i = regions->rbegin(); i != regions->rend(); ++i) {
1591                                         add_region_context_items (atv->audio_view(), (*i), edit_items);
1592                                 }
1593                         }
1594                         delete regions;
1595                 }
1596         }
1597
1598         add_dstream_context_items (edit_items);
1599
1600         return &track_crossfade_context_menu;
1601 }
1602
1603 void
1604 Editor::analyze_region_selection()
1605 {
1606         if (analysis_window == 0) {
1607                 analysis_window = new AnalysisWindow();
1608
1609                 if (_session != 0)
1610                         analysis_window->set_session(_session);
1611
1612                 analysis_window->show_all();
1613         }
1614
1615         analysis_window->set_regionmode();
1616         analysis_window->analyze();
1617
1618         analysis_window->present();
1619 }
1620
1621 void
1622 Editor::analyze_range_selection()
1623 {
1624         if (analysis_window == 0) {
1625                 analysis_window = new AnalysisWindow();
1626
1627                 if (_session != 0)
1628                         analysis_window->set_session(_session);
1629
1630                 analysis_window->show_all();
1631         }
1632
1633         analysis_window->set_rangemode();
1634         analysis_window->analyze();
1635
1636         analysis_window->present();
1637 }
1638
1639 Menu*
1640 Editor::build_track_selection_context_menu (nframes64_t)
1641 {
1642         using namespace Menu_Helpers;
1643         MenuList& edit_items  = track_selection_context_menu.items();
1644         edit_items.clear ();
1645
1646         add_selection_context_items (edit_items);
1647         // edit_items.push_back (SeparatorElem());
1648         // add_dstream_context_items (edit_items);
1649
1650         return &track_selection_context_menu;
1651 }
1652
1653 /** Add context menu items relevant to crossfades.
1654  * @param edit_items List to add the items to.
1655  */
1656 void
1657 Editor::add_crossfade_context_items (AudioStreamView* /*view*/, boost::shared_ptr<Crossfade> xfade, Menu_Helpers::MenuList& edit_items, bool many)
1658 {
1659         using namespace Menu_Helpers;
1660         Menu     *xfade_menu = manage (new Menu);
1661         MenuList& items       = xfade_menu->items();
1662         xfade_menu->set_name ("ArdourContextMenu");
1663         string str;
1664
1665         if (xfade->active()) {
1666                 str = _("Mute");
1667         } else {
1668                 str = _("Unmute");
1669         }
1670
1671         items.push_back (MenuElem (str, sigc::bind (sigc::mem_fun(*this, &Editor::toggle_xfade_active), boost::weak_ptr<Crossfade> (xfade))));
1672         items.push_back (MenuElem (_("Edit..."), sigc::bind (sigc::mem_fun(*this, &Editor::edit_xfade), boost::weak_ptr<Crossfade> (xfade))));
1673
1674         if (xfade->can_follow_overlap()) {
1675
1676                 if (xfade->following_overlap()) {
1677                         str = _("Convert to Short");
1678                 } else {
1679                         str = _("Convert to Full");
1680                 }
1681
1682                 items.push_back (MenuElem (str, sigc::bind (sigc::mem_fun(*this, &Editor::toggle_xfade_length), xfade)));
1683         }
1684
1685         if (many) {
1686                 str = xfade->out()->name();
1687                 str += "->";
1688                 str += xfade->in()->name();
1689         } else {
1690                 str = _("Crossfade");
1691         }
1692
1693         edit_items.push_back (MenuElem (str, *xfade_menu));
1694         edit_items.push_back (SeparatorElem());
1695 }
1696
1697 void
1698 Editor::xfade_edit_left_region ()
1699 {
1700         if (clicked_crossfadeview) {
1701                 clicked_crossfadeview->left_view.show_region_editor ();
1702         }
1703 }
1704
1705 void
1706 Editor::xfade_edit_right_region ()
1707 {
1708         if (clicked_crossfadeview) {
1709                 clicked_crossfadeview->right_view.show_region_editor ();
1710         }
1711 }
1712
1713 void
1714 Editor::add_region_context_items (StreamView* sv, boost::shared_ptr<Region> region, Menu_Helpers::MenuList& edit_items)
1715 {
1716         using namespace Menu_Helpers;
1717         Gtk::MenuItem* foo_item;
1718         Menu     *region_menu = manage (new Menu);
1719         MenuList& items       = region_menu->items();
1720         region_menu->set_name ("ArdourContextMenu");
1721
1722         boost::shared_ptr<AudioRegion> ar;
1723         boost::shared_ptr<MidiRegion>  mr;
1724
1725         if (region) {
1726                 ar = boost::dynamic_pointer_cast<AudioRegion> (region);
1727                 mr = boost::dynamic_pointer_cast<MidiRegion> (region);
1728
1729                 /* when this particular menu pops up, make the relevant region
1730                    become selected.
1731                 */
1732
1733                 region_menu->signal_map_event().connect (
1734                         sigc::bind (sigc::mem_fun(*this, &Editor::set_selected_regionview_from_map_event), sv, boost::weak_ptr<Region>(region)));
1735
1736                 items.push_back (MenuElem (_("Rename..."), sigc::mem_fun(*this, &Editor::rename_region)));
1737                 if (mr) {
1738                         items.push_back (MenuElem (_("List Editor..."), sigc::mem_fun(*this, &Editor::show_midi_list_editor)));
1739                 }
1740                 items.push_back (MenuElem (_("Region Properties..."), sigc::mem_fun(*this, &Editor::edit_region)));
1741         }
1742
1743         items.push_back (MenuElem (_("Raise to Top Layer"), sigc::mem_fun(*this, &Editor::raise_region_to_top)));
1744         items.push_back (MenuElem (_("Lower to Bottom Layer"), sigc::mem_fun  (*this, &Editor::lower_region_to_bottom)));
1745         items.push_back (SeparatorElem());
1746         items.push_back (MenuElem (_("Define Sync Point"), sigc::mem_fun(*this, &Editor::set_region_sync_from_edit_point)));
1747         if (_edit_point == EditAtMouse) {
1748                 items.back ().set_sensitive (false);
1749         }
1750         items.push_back (MenuElem (_("Remove Sync Point"), sigc::mem_fun(*this, &Editor::remove_region_sync)));
1751         items.push_back (SeparatorElem());
1752
1753         items.push_back (MenuElem (_("Audition"), sigc::mem_fun(*this, &Editor::play_selected_region)));
1754         items.push_back (MenuElem (_("Export..."), sigc::mem_fun(*this, &Editor::export_region)));
1755         items.push_back (MenuElem (_("Bounce"), sigc::mem_fun(*this, &Editor::bounce_region_selection)));
1756
1757         if (ar) {
1758                 items.push_back (MenuElem (_("Spectral Analysis..."), sigc::mem_fun(*this, &Editor::analyze_region_selection)));
1759         }
1760
1761         items.push_back (SeparatorElem());
1762
1763         sigc::connection fooc;
1764         boost::shared_ptr<Region> region_to_check;
1765
1766         if (region) {
1767                 region_to_check = region;
1768         } else {
1769                 region_to_check = selection->regions.front()->region();
1770         }
1771
1772         items.push_back (CheckMenuElem (_("Lock")));
1773         CheckMenuItem* region_lock_item = static_cast<CheckMenuItem*>(&items.back());
1774         if (region_to_check->locked()) {
1775                 region_lock_item->set_active();
1776         }
1777         region_lock_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_region_lock));
1778
1779         items.push_back (CheckMenuElem (_("Glue to Bars and Beats")));
1780         CheckMenuItem* bbt_glue_item = static_cast<CheckMenuItem*>(&items.back());
1781
1782         switch (region_to_check->position_lock_style()) {
1783         case MusicTime:
1784                 bbt_glue_item->set_active (true);
1785                 break;
1786         default:
1787                 bbt_glue_item->set_active (false);
1788                 break;
1789         }
1790
1791         bbt_glue_item->signal_activate().connect (sigc::mem_fun (*this, &Editor::toggle_region_lock_style));
1792
1793         items.push_back (CheckMenuElem (_("Mute")));
1794         CheckMenuItem* region_mute_item = static_cast<CheckMenuItem*>(&items.back());
1795         fooc = region_mute_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_region_mute));
1796         if (region_to_check->muted()) {
1797                 fooc.block (true);
1798                 region_mute_item->set_active();
1799                 fooc.block (false);
1800         }
1801         
1802         items.push_back (MenuElem (_("Transpose..."), mem_fun(*this, &Editor::pitch_shift_regions)));
1803
1804         if (!Profile->get_sae()) {
1805                 items.push_back (CheckMenuElem (_("Opaque")));
1806                 CheckMenuItem* region_opaque_item = static_cast<CheckMenuItem*>(&items.back());
1807                 fooc = region_opaque_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_region_opaque));
1808                 if (region_to_check->opaque()) {
1809                         fooc.block (true);
1810                         region_opaque_item->set_active();
1811                         fooc.block (false);
1812                 }
1813         }
1814
1815         items.push_back (CheckMenuElem (_("Original Position"), sigc::mem_fun(*this, &Editor::naturalize)));
1816         if (region_to_check->at_natural_position()) {
1817                 items.back().set_sensitive (false);
1818         }
1819
1820         items.push_back (SeparatorElem());
1821
1822         if (ar) {
1823
1824                 RegionView* rv = sv->find_view (ar);
1825                 AudioRegionView* arv = dynamic_cast<AudioRegionView*>(rv);
1826
1827                 if (!Profile->get_sae()) {
1828                         items.push_back (MenuElem (_("Reset Envelope"), sigc::mem_fun(*this, &Editor::reset_region_gain_envelopes)));
1829
1830                         items.push_back (CheckMenuElem (_("Envelope Visible")));
1831                         CheckMenuItem* region_envelope_visible_item = static_cast<CheckMenuItem*> (&items.back());
1832                         fooc = region_envelope_visible_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_gain_envelope_visibility));
1833                         if (arv->envelope_visible()) {
1834                                 fooc.block (true);
1835                                 region_envelope_visible_item->set_active (true);
1836                                 fooc.block (false);
1837                         }
1838
1839                         items.push_back (CheckMenuElem (_("Envelope Active")));
1840                         CheckMenuItem* region_envelope_active_item = static_cast<CheckMenuItem*> (&items.back());
1841                         fooc = region_envelope_active_item->signal_activate().connect (sigc::mem_fun(*this, &Editor::toggle_gain_envelope_active));
1842
1843                         if (ar->envelope_active()) {
1844                                 fooc.block (true);
1845                                 region_envelope_active_item->set_active (true);
1846                                 fooc.block (false);
1847                         }
1848
1849                         items.push_back (SeparatorElem());
1850                 }
1851
1852                 items.push_back (MenuElem (_("Normalize..."), sigc::mem_fun(*this, &Editor::normalize_region)));
1853                 if (ar->scale_amplitude() != 1) {
1854                         items.push_back (MenuElem (_("Reset Gain"), sigc::mem_fun(*this, &Editor::reset_region_scale_amplitude)));
1855                 }
1856
1857         } else if (mr) {
1858                 items.push_back (MenuElem (_("Quantize"), sigc::mem_fun(*this, &Editor::quantize_region)));
1859                 items.push_back (MenuElem (_("Fork"), sigc::mem_fun(*this, &Editor::fork_region)));
1860                 items.push_back (SeparatorElem());
1861         }
1862
1863         items.push_back (MenuElem (_("Strip Silence..."), sigc::mem_fun (*this, &Editor::strip_region_silence)));
1864         items.push_back (MenuElem (_("Reverse"), sigc::mem_fun(*this, &Editor::reverse_region)));
1865         items.push_back (SeparatorElem());
1866
1867         /* range related stuff */
1868
1869         items.push_back (MenuElem (_("Add Single Range"), sigc::mem_fun (*this, &Editor::add_location_from_audio_region)));
1870         items.push_back (MenuElem (_("Add Range Markers"), sigc::mem_fun (*this, &Editor::add_locations_from_audio_region)));
1871         if (selection->regions.size() < 2) {
1872                 items.back().set_sensitive (false);
1873         }
1874
1875         items.push_back (MenuElem (_("Set Range Selection"), sigc::mem_fun (*this, &Editor::set_selection_from_region)));
1876         items.push_back (SeparatorElem());
1877
1878         /* Nudge region */
1879
1880         Menu *nudge_menu = manage (new Menu());
1881         MenuList& nudge_items = nudge_menu->items();
1882         nudge_menu->set_name ("ArdourContextMenu");
1883
1884         nudge_items.push_back (MenuElem (_("Nudge Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_forward), false, false))));
1885         nudge_items.push_back (MenuElem (_("Nudge Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_backward), false, false))));
1886         nudge_items.push_back (MenuElem (_("Nudge Forward by Capture Offset"), (sigc::mem_fun(*this, &Editor::nudge_forward_capture_offset))));
1887         nudge_items.push_back (MenuElem (_("Nudge Backward by Capture Offset"), (sigc::mem_fun(*this, &Editor::nudge_backward_capture_offset))));
1888
1889         items.push_back (MenuElem (_("Nudge"), *nudge_menu));
1890         items.push_back (SeparatorElem());
1891
1892         Menu *trim_menu = manage (new Menu);
1893         MenuList& trim_items = trim_menu->items();
1894         trim_menu->set_name ("ArdourContextMenu");
1895
1896         trim_items.push_back (MenuElem (_("Start to Edit Point"), sigc::mem_fun(*this, &Editor::trim_region_from_edit_point)));
1897         foo_item = &trim_items.back();
1898         if (_edit_point == EditAtMouse) {
1899                 foo_item->set_sensitive (false);
1900         }
1901         trim_items.push_back (MenuElem (_("Edit Point to End"), sigc::mem_fun(*this, &Editor::trim_region_to_edit_point)));
1902         foo_item = &trim_items.back();
1903         if (_edit_point == EditAtMouse) {
1904                 foo_item->set_sensitive (false);
1905         }
1906         trim_items.push_back (MenuElem (_("Trim to Loop"), sigc::mem_fun(*this, &Editor::trim_region_to_loop)));
1907         trim_items.push_back (MenuElem (_("Trim to Punch"), sigc::mem_fun(*this, &Editor::trim_region_to_punch)));
1908
1909         items.push_back (MenuElem (_("Trim"), *trim_menu));
1910         items.push_back (SeparatorElem());
1911
1912         items.push_back (MenuElem (_("Split"), (sigc::mem_fun(*this, &Editor::split))));
1913         region_edit_menu_split_item = &items.back();
1914
1915         if (_edit_point == EditAtMouse) {
1916                 region_edit_menu_split_item->set_sensitive (false);
1917         }
1918
1919         items.push_back (MenuElem (_("Make Mono Regions"), (sigc::mem_fun(*this, &Editor::split_multichannel_region))));
1920         region_edit_menu_split_multichannel_item = &items.back();
1921
1922         items.push_back (MenuElem (_("Duplicate"), (sigc::bind (sigc::mem_fun(*this, &Editor::duplicate_dialog), false))));
1923         items.push_back (MenuElem (_("Multi-Duplicate..."), (sigc::bind (sigc::mem_fun(*this, &Editor::duplicate_dialog), true))));
1924         items.push_back (MenuElem (_("Fill Track"), (sigc::mem_fun(*this, &Editor::region_fill_track))));
1925         items.push_back (SeparatorElem());
1926         items.push_back (MenuElem (_("Remove"), sigc::mem_fun(*this, &Editor::remove_selected_regions)));
1927
1928         /* OK, stick the region submenu at the top of the list, and then add
1929            the standard items.
1930         */
1931
1932         /* we have to hack up the region name because "_" has a special
1933            meaning for menu titles.
1934         */
1935
1936         string::size_type pos = 0;
1937         string menu_item_name = (region) ? region->name() : _("Selected Regions");
1938
1939         while ((pos = menu_item_name.find ("_", pos)) != string::npos) {
1940                 menu_item_name.replace (pos, 1, "__");
1941                 pos += 2;
1942         }
1943
1944         edit_items.push_back (MenuElem (menu_item_name, *region_menu));
1945         edit_items.push_back (SeparatorElem());
1946 }
1947
1948 /** Add context menu items relevant to selection ranges.
1949  * @param edit_items List to add the items to.
1950  */
1951 void
1952 Editor::add_selection_context_items (Menu_Helpers::MenuList& edit_items)
1953 {
1954         using namespace Menu_Helpers;
1955
1956         edit_items.push_back (MenuElem (_("Play Range"), sigc::mem_fun(*this, &Editor::play_selection)));
1957         edit_items.push_back (MenuElem (_("Loop Range"), sigc::bind (sigc::mem_fun(*this, &Editor::set_loop_from_selection), true)));
1958
1959         edit_items.push_back (SeparatorElem());
1960         edit_items.push_back (MenuElem (_("Spectral Analysis"), sigc::mem_fun(*this, &Editor::analyze_range_selection)));
1961
1962         if (!selection->regions.empty()) {
1963                 edit_items.push_back (SeparatorElem());
1964                 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)));
1965                 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)));
1966         }
1967
1968         edit_items.push_back (SeparatorElem());
1969         edit_items.push_back (MenuElem (_("Convert to region in-place"), mem_fun(*this, &Editor::separate_region_from_selection)));
1970         edit_items.push_back (MenuElem (_("Convert to Region in Region List"), sigc::mem_fun(*this, &Editor::new_region_from_selection)));
1971
1972         edit_items.push_back (SeparatorElem());
1973         edit_items.push_back (MenuElem (_("Select All in Range"), sigc::mem_fun(*this, &Editor::select_all_selectables_using_time_selection)));
1974
1975         edit_items.push_back (SeparatorElem());
1976         edit_items.push_back (MenuElem (_("Set Loop from Range"), sigc::bind (sigc::mem_fun(*this, &Editor::set_loop_from_selection), false)));
1977         edit_items.push_back (MenuElem (_("Set Punch from Range"), sigc::mem_fun(*this, &Editor::set_punch_from_selection)));
1978
1979         edit_items.push_back (SeparatorElem());
1980         edit_items.push_back (MenuElem (_("Add Range Markers"), sigc::mem_fun (*this, &Editor::add_location_from_selection)));
1981
1982         edit_items.push_back (SeparatorElem());
1983         edit_items.push_back (MenuElem (_("Crop Region to Range"), sigc::mem_fun(*this, &Editor::crop_region_to_selection)));
1984         edit_items.push_back (MenuElem (_("Fill Range with Region"), sigc::mem_fun(*this, &Editor::region_fill_selection)));
1985         edit_items.push_back (MenuElem (_("Duplicate Range"), sigc::bind (sigc::mem_fun(*this, &Editor::duplicate_dialog), false)));
1986
1987         edit_items.push_back (SeparatorElem());
1988         edit_items.push_back (MenuElem (_("Consolidate Range"), sigc::bind (sigc::mem_fun(*this, &Editor::bounce_range_selection), true, false)));
1989         edit_items.push_back (MenuElem (_("Consolidate Range With Processing"), sigc::bind (sigc::mem_fun(*this, &Editor::bounce_range_selection), true, true)));
1990         edit_items.push_back (MenuElem (_("Bounce Range to Region List"), sigc::bind (sigc::mem_fun(*this, &Editor::bounce_range_selection), false, false)));
1991         edit_items.push_back (MenuElem (_("Bounce Range to Region List With Processing"), sigc::bind (sigc::mem_fun(*this, &Editor::bounce_range_selection), false, true)));
1992         edit_items.push_back (MenuElem (_("Export Range"), sigc::mem_fun(*this, &Editor::export_selection)));
1993 }
1994
1995
1996 void
1997 Editor::add_dstream_context_items (Menu_Helpers::MenuList& edit_items)
1998 {
1999         using namespace Menu_Helpers;
2000
2001         /* Playback */
2002
2003         Menu *play_menu = manage (new Menu);
2004         MenuList& play_items = play_menu->items();
2005         play_menu->set_name ("ArdourContextMenu");
2006
2007         play_items.push_back (MenuElem (_("Play From Edit Point"), sigc::mem_fun(*this, &Editor::play_from_edit_point)));
2008         play_items.push_back (MenuElem (_("Play From Start"), sigc::mem_fun(*this, &Editor::play_from_start)));
2009         play_items.push_back (MenuElem (_("Play Region"), sigc::mem_fun(*this, &Editor::play_selected_region)));
2010         play_items.push_back (SeparatorElem());
2011         play_items.push_back (MenuElem (_("Loop Region"), sigc::mem_fun(*this, &Editor::loop_selected_region)));
2012
2013         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2014
2015         /* Selection */
2016
2017         Menu *select_menu = manage (new Menu);
2018         MenuList& select_items = select_menu->items();
2019         select_menu->set_name ("ArdourContextMenu");
2020
2021         select_items.push_back (MenuElem (_("Select All in Track"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2022         select_items.push_back (MenuElem (_("Select All"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all), Selection::Set)));
2023         select_items.push_back (MenuElem (_("Invert Selection in Track"), sigc::mem_fun(*this, &Editor::invert_selection_in_track)));
2024         select_items.push_back (MenuElem (_("Invert Selection"), sigc::mem_fun(*this, &Editor::invert_selection)));
2025         select_items.push_back (SeparatorElem());
2026         select_items.push_back (MenuElem (_("Set Range to Loop Range"), sigc::mem_fun(*this, &Editor::set_selection_from_loop)));
2027         select_items.push_back (MenuElem (_("Set Range to Punch Range"), sigc::mem_fun(*this, &Editor::set_selection_from_punch)));
2028         select_items.push_back (SeparatorElem());
2029         select_items.push_back (MenuElem (_("Select All After Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_edit), true)));
2030         select_items.push_back (MenuElem (_("Select All Before Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_edit), false)));
2031         select_items.push_back (MenuElem (_("Select All After Playhead"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2032         select_items.push_back (MenuElem (_("Select All Before Playhead"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2033         select_items.push_back (MenuElem (_("Select All Between Playhead and Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_between), false)));
2034         select_items.push_back (MenuElem (_("Select All Within Playhead and Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_between), true)));
2035         select_items.push_back (MenuElem (_("Select Range Between Playhead and Edit Point"), sigc::mem_fun(*this, &Editor::select_range_between)));
2036
2037         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2038
2039         /* Cut-n-Paste */
2040
2041         Menu *cutnpaste_menu = manage (new Menu);
2042         MenuList& cutnpaste_items = cutnpaste_menu->items();
2043         cutnpaste_menu->set_name ("ArdourContextMenu");
2044
2045         cutnpaste_items.push_back (MenuElem (_("Cut"), sigc::mem_fun(*this, &Editor::cut)));
2046         cutnpaste_items.push_back (MenuElem (_("Copy"), sigc::mem_fun(*this, &Editor::copy)));
2047         cutnpaste_items.push_back (MenuElem (_("Paste"), sigc::bind (sigc::mem_fun(*this, &Editor::paste), 1.0f)));
2048
2049         cutnpaste_items.push_back (SeparatorElem());
2050
2051         cutnpaste_items.push_back (MenuElem (_("Align"), sigc::bind (sigc::mem_fun(*this, &Editor::align), ARDOUR::SyncPoint)));
2052         cutnpaste_items.push_back (MenuElem (_("Align Relative"), sigc::bind (sigc::mem_fun(*this, &Editor::align_relative), ARDOUR::SyncPoint)));
2053
2054         edit_items.push_back (MenuElem (_("Edit"), *cutnpaste_menu));
2055
2056         /* Adding new material */
2057
2058         edit_items.push_back (SeparatorElem());
2059         edit_items.push_back (MenuElem (_("Insert Selected Region"), sigc::bind (sigc::mem_fun(*this, &Editor::insert_region_list_selection), 1.0f)));
2060         edit_items.push_back (MenuElem (_("Insert Existing Media"), sigc::bind (sigc::mem_fun(*this, &Editor::add_external_audio_action), ImportToTrack)));
2061
2062         /* Nudge track */
2063
2064         Menu *nudge_menu = manage (new Menu());
2065         MenuList& nudge_items = nudge_menu->items();
2066         nudge_menu->set_name ("ArdourContextMenu");
2067
2068         edit_items.push_back (SeparatorElem());
2069         nudge_items.push_back (MenuElem (_("Nudge Entire Track Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), false, true))));
2070         nudge_items.push_back (MenuElem (_("Nudge Track After Edit Point Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), true, true))));
2071         nudge_items.push_back (MenuElem (_("Nudge Entire Track Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), false, false))));
2072         nudge_items.push_back (MenuElem (_("Nudge Track After Edit Point Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), true, false))));
2073
2074         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2075 }
2076
2077 void
2078 Editor::add_bus_context_items (Menu_Helpers::MenuList& edit_items)
2079 {
2080         using namespace Menu_Helpers;
2081
2082         /* Playback */
2083
2084         Menu *play_menu = manage (new Menu);
2085         MenuList& play_items = play_menu->items();
2086         play_menu->set_name ("ArdourContextMenu");
2087
2088         play_items.push_back (MenuElem (_("Play From Edit Point"), sigc::mem_fun(*this, &Editor::play_from_edit_point)));
2089         play_items.push_back (MenuElem (_("Play From Start"), sigc::mem_fun(*this, &Editor::play_from_start)));
2090         edit_items.push_back (MenuElem (_("Play"), *play_menu));
2091
2092         /* Selection */
2093
2094         Menu *select_menu = manage (new Menu);
2095         MenuList& select_items = select_menu->items();
2096         select_menu->set_name ("ArdourContextMenu");
2097
2098         select_items.push_back (MenuElem (_("Select All in Track"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_in_track), Selection::Set)));
2099         select_items.push_back (MenuElem (_("Select All"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all), Selection::Set)));
2100         select_items.push_back (MenuElem (_("Invert Selection in Track"), sigc::mem_fun(*this, &Editor::invert_selection_in_track)));
2101         select_items.push_back (MenuElem (_("Invert Selection"), sigc::mem_fun(*this, &Editor::invert_selection)));
2102         select_items.push_back (SeparatorElem());
2103         select_items.push_back (MenuElem (_("Select All After Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_edit), true)));
2104         select_items.push_back (MenuElem (_("Select All Before Edit Point"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_edit), false)));
2105         select_items.push_back (MenuElem (_("Select All After Playhead"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, true)));
2106         select_items.push_back (MenuElem (_("Select All Before Playhead"), sigc::bind (sigc::mem_fun(*this, &Editor::select_all_selectables_using_cursor), playhead_cursor, false)));
2107
2108         edit_items.push_back (MenuElem (_("Select"), *select_menu));
2109
2110         /* Cut-n-Paste */
2111
2112         Menu *cutnpaste_menu = manage (new Menu);
2113         MenuList& cutnpaste_items = cutnpaste_menu->items();
2114         cutnpaste_menu->set_name ("ArdourContextMenu");
2115
2116         cutnpaste_items.push_back (MenuElem (_("Cut"), sigc::mem_fun(*this, &Editor::cut)));
2117         cutnpaste_items.push_back (MenuElem (_("Copy"), sigc::mem_fun(*this, &Editor::copy)));
2118         cutnpaste_items.push_back (MenuElem (_("Paste"), sigc::bind (sigc::mem_fun(*this, &Editor::paste), 1.0f)));
2119
2120         Menu *nudge_menu = manage (new Menu());
2121         MenuList& nudge_items = nudge_menu->items();
2122         nudge_menu->set_name ("ArdourContextMenu");
2123
2124         edit_items.push_back (SeparatorElem());
2125         nudge_items.push_back (MenuElem (_("Nudge Entire Track Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), false, true))));
2126         nudge_items.push_back (MenuElem (_("Nudge Track After Edit Point Forward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), true, true))));
2127         nudge_items.push_back (MenuElem (_("Nudge Entire Track Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), false, false))));
2128         nudge_items.push_back (MenuElem (_("Nudge Track After Edit Point Backward"), (sigc::bind (sigc::mem_fun(*this, &Editor::nudge_track), true, false))));
2129
2130         edit_items.push_back (MenuElem (_("Nudge"), *nudge_menu));
2131 }
2132
2133 SnapType
2134 Editor::snap_type() const
2135 {
2136         return _snap_type;
2137 }
2138
2139 SnapMode
2140 Editor::snap_mode() const
2141 {
2142         return _snap_mode;
2143 }
2144
2145 void
2146 Editor::set_snap_to (SnapType st)
2147 {
2148         unsigned int snap_ind = (unsigned int)st;
2149
2150         _snap_type = st;
2151
2152         if (snap_ind > snap_type_strings.size() - 1) {
2153                 snap_ind = 0;
2154                 _snap_type = (SnapType)snap_ind;
2155         }
2156
2157         string str = snap_type_strings[snap_ind];
2158
2159         if (str != snap_type_selector.get_active_text()) {
2160                 snap_type_selector.set_active_text (str);
2161         }
2162
2163         instant_save ();
2164
2165         switch (_snap_type) {
2166         case SnapToBeatDiv32:
2167         case SnapToBeatDiv28:
2168         case SnapToBeatDiv24:
2169         case SnapToBeatDiv16:
2170         case SnapToBeatDiv14:
2171         case SnapToBeatDiv12:
2172         case SnapToBeatDiv10:
2173         case SnapToBeatDiv8:
2174         case SnapToBeatDiv7:
2175         case SnapToBeatDiv6:
2176         case SnapToBeatDiv5:
2177         case SnapToBeatDiv4:
2178         case SnapToBeatDiv3:
2179         case SnapToBeatDiv2:
2180                 compute_bbt_ruler_scale (leftmost_frame, leftmost_frame + current_page_frames());
2181                 update_tempo_based_rulers ();
2182                 break;
2183
2184         case SnapToRegionStart:
2185         case SnapToRegionEnd:
2186         case SnapToRegionSync:
2187         case SnapToRegionBoundary:
2188                 build_region_boundary_cache ();
2189                 break;
2190
2191         default:
2192                 /* relax */
2193                 break;
2194         }
2195
2196         SnapChanged (); /* EMIT SIGNAL */
2197 }
2198
2199 void
2200 Editor::set_snap_mode (SnapMode mode)
2201 {
2202         _snap_mode = mode;
2203         string str = snap_mode_strings[(int)mode];
2204
2205         if (str != snap_mode_selector.get_active_text ()) {
2206                 snap_mode_selector.set_active_text (str);
2207         }
2208
2209         instant_save ();
2210 }
2211 void
2212 Editor::set_edit_point_preference (EditPoint ep, bool force)
2213 {
2214         bool changed = (_edit_point != ep);
2215
2216         _edit_point = ep;
2217         string str = edit_point_strings[(int)ep];
2218
2219         if (str != edit_point_selector.get_active_text ()) {
2220                 edit_point_selector.set_active_text (str);
2221         }
2222
2223         set_canvas_cursor ();
2224
2225         if (!force && !changed) {
2226                 return;
2227         }
2228
2229         const char* action=NULL;
2230
2231         switch (_edit_point) {
2232         case EditAtPlayhead:
2233                 action = "edit-at-playhead";
2234                 break;
2235         case EditAtSelectedMarker:
2236                 action = "edit-at-marker";
2237                 break;
2238         case EditAtMouse:
2239                 action = "edit-at-mouse";
2240                 break;
2241         }
2242
2243         Glib::RefPtr<Action> act = ActionManager::get_action ("Editor", action);
2244         if (act) {
2245                 Glib::RefPtr<RadioAction>::cast_dynamic(act)->set_active (true);
2246         }
2247
2248         nframes64_t foo;
2249         bool in_track_canvas;
2250
2251         if (!mouse_frame (foo, in_track_canvas)) {
2252                 in_track_canvas = false;
2253         }
2254
2255         reset_canvas_action_sensitivity (in_track_canvas);
2256
2257         instant_save ();
2258 }
2259
2260 int
2261 Editor::set_state (const XMLNode& node, int /*version*/)
2262 {
2263         const XMLProperty* prop;
2264         XMLNode* geometry;
2265         int x, y, xoff, yoff;
2266         Gdk::Geometry g;
2267
2268         if ((prop = node.property ("id")) != 0) {
2269                 _id = prop->value ();
2270         }
2271
2272         g.base_width = default_width;
2273         g.base_height = default_height;
2274         x = 1;
2275         y = 1;
2276         xoff = 0;
2277         yoff = 21;
2278
2279         if ((geometry = find_named_node (node, "geometry")) != 0) {
2280
2281                 XMLProperty* prop;
2282
2283                 if ((prop = geometry->property("x_size")) == 0) {
2284                         prop = geometry->property ("x-size");
2285                 }
2286                 if (prop) {
2287                         g.base_width = atoi(prop->value());
2288                 }
2289                 if ((prop = geometry->property("y_size")) == 0) {
2290                         prop = geometry->property ("y-size");
2291                 }
2292                 if (prop) {
2293                         g.base_height = atoi(prop->value());
2294                 }
2295
2296                 if ((prop = geometry->property ("x_pos")) == 0) {
2297                         prop = geometry->property ("x-pos");
2298                 }
2299                 if (prop) {
2300                         x = atoi (prop->value());
2301
2302                 }
2303                 if ((prop = geometry->property ("y_pos")) == 0) {
2304                         prop = geometry->property ("y-pos");
2305                 }
2306                 if (prop) {
2307                         y = atoi (prop->value());
2308                 }
2309
2310                 if ((prop = geometry->property ("x_off")) == 0) {
2311                         prop = geometry->property ("x-off");
2312                 }
2313                 if (prop) {
2314                         xoff = atoi (prop->value());
2315                 }
2316                 if ((prop = geometry->property ("y_off")) == 0) {
2317                         prop = geometry->property ("y-off");
2318                 }
2319                 if (prop) {
2320                         yoff = atoi (prop->value());
2321                 }
2322         }
2323
2324         set_default_size (g.base_width, g.base_height);
2325         move (x, y);
2326
2327         if (_session && (prop = node.property ("playhead"))) {
2328                 nframes64_t pos;
2329                 sscanf (prop->value().c_str(), "%" PRIi64, &pos);
2330                 playhead_cursor->set_position (pos);
2331         } else {
2332                 playhead_cursor->set_position (0);
2333         }
2334         
2335         if ((prop = node.property ("mixer-width"))) {
2336                 editor_mixer_strip_width = Width (string_2_enum (prop->value(), editor_mixer_strip_width));
2337         }
2338
2339         if ((prop = node.property ("zoom-focus"))) {
2340                 set_zoom_focus ((ZoomFocus) atoi (prop->value()));
2341         }
2342
2343         if ((prop = node.property ("zoom"))) {
2344                 reset_zoom (PBD::atof (prop->value()));
2345         }
2346
2347         if ((prop = node.property ("snap-to"))) {
2348                 set_snap_to ((SnapType) atoi (prop->value()));
2349         }
2350
2351         if ((prop = node.property ("snap-mode"))) {
2352                 set_snap_mode ((SnapMode) atoi (prop->value()));
2353         }
2354
2355         if ((prop = node.property ("mouse-mode"))) {
2356                 MouseMode m = str2mousemode(prop->value());
2357                 set_mouse_mode (m, true);
2358         } else {
2359                 set_mouse_mode (MouseObject, true);
2360         }
2361
2362         if ((prop = node.property ("left-frame")) != 0){
2363                 nframes64_t pos;
2364                 if (sscanf (prop->value().c_str(), "%" PRId64, &pos) == 1) {
2365                         reset_x_origin (pos);
2366                 }
2367         }
2368
2369         if ((prop = node.property ("y-origin")) != 0) {
2370                 reset_y_origin (atof (prop->value ()));
2371         }
2372
2373         if ((prop = node.property ("internal-edit"))) {
2374                 bool yn = string_is_affirmative (prop->value());
2375                 RefPtr<Action> act = ActionManager::get_action (X_("MouseMode"), X_("toggle-internal-edit"));
2376                 if (act) {
2377                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2378                         tact->set_active (!yn);
2379                         tact->set_active (yn);
2380                 }
2381         }
2382
2383         if ((prop = node.property ("join-object-range"))) {
2384                 join_object_range_button.set_active (string_is_affirmative (prop->value ()));
2385         }
2386
2387         if ((prop = node.property ("edit-point"))) {
2388                 set_edit_point_preference ((EditPoint) string_2_enum (prop->value(), _edit_point), true);
2389         }
2390
2391         if ((prop = node.property ("show-measures"))) {
2392                 bool yn = string_is_affirmative (prop->value());
2393                 _show_measures = !yn;
2394                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("ToggleMeasureVisibility"));
2395                 if (act) {
2396                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2397                         /* do it twice to force the change */
2398                         tact->set_active (!yn);
2399                         tact->set_active (yn);
2400                 }
2401         }
2402
2403         if ((prop = node.property ("follow-playhead"))) {
2404                 bool yn = string_is_affirmative (prop->value());
2405                 set_follow_playhead (yn);
2406                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
2407                 if (act) {
2408                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2409                         if (tact->get_active() != yn) {
2410                                 tact->set_active (yn);
2411                         }
2412                 }
2413         }
2414
2415         if ((prop = node.property ("stationary-playhead"))) {
2416                 bool yn = (prop->value() == "yes");
2417                 set_stationary_playhead (yn);
2418                 RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-stationary-playhead"));
2419                 if (act) {
2420                         RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
2421                         if (tact->get_active() != yn) {
2422                                 tact->set_active (yn);
2423                         }
2424                 }
2425         }
2426         
2427         if ((prop = node.property ("region-list-sort-type"))) {
2428                 RegionListSortType st;
2429                 _regions->reset_sort_type ((RegionListSortType) string_2_enum (prop->value(), st), true);
2430         }
2431
2432         if ((prop = node.property ("xfades-visible"))) {
2433                 bool yn = string_is_affirmative (prop->value());
2434                 _xfade_visibility = !yn;
2435                 // set_xfade_visibility (yn);
2436         }
2437
2438         if ((prop = node.property ("show-editor-mixer"))) {
2439
2440                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2441                 if (act) {
2442
2443                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2444                         bool yn = string_is_affirmative (prop->value());
2445
2446                         /* do it twice to force the change */
2447
2448                         tact->set_active (!yn);
2449                         tact->set_active (yn);
2450                 }
2451         }
2452
2453         if ((prop = node.property ("show-editor-list"))) {
2454
2455                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-list"));
2456                 assert(act);
2457                 if (act) {
2458
2459                         Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2460                         bool yn = string_is_affirmative (prop->value());
2461
2462                         /* do it twice to force the change */
2463
2464                         tact->set_active (!yn);
2465                         tact->set_active (yn);
2466                 }
2467         }
2468
2469         if ((prop = node.property (X_("editor-list-page")))) {
2470                 the_notebook.set_current_page (atoi (prop->value ()));
2471         }
2472
2473         return 0;
2474 }
2475
2476 XMLNode&
2477 Editor::get_state ()
2478 {
2479         XMLNode* node = new XMLNode ("Editor");
2480         char buf[32];
2481
2482         _id.print (buf, sizeof (buf));
2483         node->add_property ("id", buf);
2484
2485         if (is_realized()) {
2486                 Glib::RefPtr<Gdk::Window> win = get_window();
2487
2488                 int x, y, xoff, yoff, width, height;
2489                 win->get_root_origin(x, y);
2490                 win->get_position(xoff, yoff);
2491                 win->get_size(width, height);
2492
2493                 XMLNode* geometry = new XMLNode ("geometry");
2494
2495                 snprintf(buf, sizeof(buf), "%d", width);
2496                 geometry->add_property("x-size", string(buf));
2497                 snprintf(buf, sizeof(buf), "%d", height);
2498                 geometry->add_property("y-size", string(buf));
2499                 snprintf(buf, sizeof(buf), "%d", x);
2500                 geometry->add_property("x-pos", string(buf));
2501                 snprintf(buf, sizeof(buf), "%d", y);
2502                 geometry->add_property("y-pos", string(buf));
2503                 snprintf(buf, sizeof(buf), "%d", xoff);
2504                 geometry->add_property("x-off", string(buf));
2505                 snprintf(buf, sizeof(buf), "%d", yoff);
2506                 geometry->add_property("y-off", string(buf));
2507                 snprintf(buf,sizeof(buf), "%d",gtk_paned_get_position (static_cast<Paned*>(&edit_pane)->gobj()));
2508                 geometry->add_property("edit-horizontal-pane-pos", string(buf));
2509                 snprintf(buf,sizeof(buf), "%d",gtk_paned_get_position (static_cast<Paned*>(&editor_summary_pane)->gobj()));
2510                 geometry->add_property("edit-vertical-pane-pos", string(buf));
2511
2512                 node->add_child_nocopy (*geometry);
2513         }
2514
2515         maybe_add_mixer_strip_width (*node);
2516
2517         snprintf (buf, sizeof(buf), "%d", (int) zoom_focus);
2518         node->add_property ("zoom-focus", buf);
2519         snprintf (buf, sizeof(buf), "%f", frames_per_unit);
2520         node->add_property ("zoom", buf);
2521         snprintf (buf, sizeof(buf), "%d", (int) _snap_type);
2522         node->add_property ("snap-to", buf);
2523         snprintf (buf, sizeof(buf), "%d", (int) _snap_mode);
2524         node->add_property ("snap-mode", buf);
2525
2526         node->add_property ("edit-point", enum_2_string (_edit_point));
2527
2528         snprintf (buf, sizeof (buf), "%" PRIi64, playhead_cursor->current_frame);
2529         node->add_property ("playhead", buf);
2530         snprintf (buf, sizeof (buf), "%" PRIi64, leftmost_frame);
2531         node->add_property ("left-frame", buf);
2532         snprintf (buf, sizeof (buf), "%f", vertical_adjustment.get_value ());
2533         node->add_property ("y-origin", buf);
2534
2535         node->add_property ("show-measures", _show_measures ? "yes" : "no");
2536         node->add_property ("follow-playhead", _follow_playhead ? "yes" : "no");
2537         node->add_property ("stationary-playhead", _stationary_playhead ? "yes" : "no");
2538         node->add_property ("xfades-visible", _xfade_visibility ? "yes" : "no");
2539         node->add_property ("region-list-sort-type", enum_2_string (_regions->sort_type ()));
2540         node->add_property ("mouse-mode", enum2str(mouse_mode));
2541         node->add_property ("internal-edit", _internal_editing ? "yes" : "no");
2542         node->add_property ("join-object-range", join_object_range_button.get_active () ? "yes" : "no");
2543
2544         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("show-editor-mixer"));
2545         if (act) {
2546                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2547                 node->add_property (X_("show-editor-mixer"), tact->get_active() ? "yes" : "no");
2548         }
2549
2550         act = ActionManager::get_action (X_("Editor"), X_("show-editor-list"));
2551         if (act) {
2552                 Glib::RefPtr<ToggleAction> tact = Glib::RefPtr<ToggleAction>::cast_dynamic(act);
2553                 node->add_property (X_("show-editor-list"), tact->get_active() ? "yes" : "no");
2554         }
2555
2556         snprintf (buf, sizeof (buf), "%d", the_notebook.get_current_page ());
2557         node->add_property (X_("editor-list-page"), buf);
2558
2559         return *node;
2560 }
2561
2562
2563
2564 /** @param y y offset from the top of all trackviews.
2565  *  @return pair: TimeAxisView that y is over, layer index.
2566  *  TimeAxisView may be 0.  Layer index is the layer number if the TimeAxisView is valid and is
2567  *  in stacked region display mode, otherwise 0.
2568  */
2569 std::pair<TimeAxisView *, layer_t>
2570 Editor::trackview_by_y_position (double y)
2571 {
2572         for (TrackViewList::iterator iter = track_views.begin(); iter != track_views.end(); ++iter) {
2573
2574                 std::pair<TimeAxisView*, int> const r = (*iter)->covers_y_position (y);
2575                 if (r.first) {
2576                         return r;
2577                 }
2578         }
2579
2580         return std::make_pair ( (TimeAxisView *) 0, 0);
2581 }
2582
2583 /** Snap a position to the grid, if appropriate, taking into account current
2584  *  grid settings and also the state of any snap modifier keys that may be pressed.
2585  *  @param start Position to snap.
2586  *  @param event Event to get current key modifier information from, or 0.
2587  */
2588 void
2589 Editor::snap_to_with_modifier (nframes64_t& start, GdkEvent const * event, int32_t direction, bool for_mark)
2590 {
2591         if (!_session || !event) {
2592                 return;
2593         }
2594
2595         if (Keyboard::modifier_state_contains (event->button.state, Keyboard::snap_modifier())) {
2596                 if (_snap_mode == SnapOff) {
2597                         snap_to_internal (start, direction, for_mark);
2598                 }
2599         } else {
2600                 if (_snap_mode != SnapOff) {
2601                         snap_to_internal (start, direction, for_mark);
2602                 }
2603         }
2604 }
2605
2606 void
2607 Editor::snap_to (nframes64_t& start, int32_t direction, bool for_mark)
2608 {
2609         if (!_session || _snap_mode == SnapOff) {
2610                 return;
2611         }
2612
2613         snap_to_internal (start, direction, for_mark);
2614 }
2615
2616 void
2617 Editor::timecode_snap_to_internal (nframes64_t& start, int32_t direction, bool /*for_mark*/)
2618 {
2619         const nframes64_t one_timecode_second = (nframes64_t)(rint(_session->timecode_frames_per_second()) * _session->frames_per_timecode_frame());
2620         nframes64_t one_timecode_minute = (nframes64_t)(rint(_session->timecode_frames_per_second()) * _session->frames_per_timecode_frame() * 60);
2621
2622         switch (_snap_type) {
2623         case SnapToTimecodeFrame:
2624                 if (((direction == 0) && (fmod((double)start, (double)_session->frames_per_timecode_frame()) > (_session->frames_per_timecode_frame() / 2))) || (direction > 0)) {
2625                         start = (nframes64_t) (ceil ((double) start / _session->frames_per_timecode_frame()) * _session->frames_per_timecode_frame());
2626                 } else {
2627                         start = (nframes64_t) (floor ((double) start / _session->frames_per_timecode_frame()) *  _session->frames_per_timecode_frame());
2628                 }
2629                 break;
2630
2631         case SnapToTimecodeSeconds:
2632                 if (_session->timecode_offset_negative())
2633                 {
2634                         start += _session->timecode_offset ();
2635                 } else {
2636                         start -= _session->timecode_offset ();
2637                 }
2638                 if (((direction == 0) && (start % one_timecode_second > one_timecode_second / 2)) || direction > 0) {
2639                         start = (nframes64_t) ceil ((double) start / one_timecode_second) * one_timecode_second;
2640                 } else {
2641                         start = (nframes64_t) floor ((double) start / one_timecode_second) * one_timecode_second;
2642                 }
2643
2644                 if (_session->timecode_offset_negative())
2645                 {
2646                         start -= _session->timecode_offset ();
2647                 } else {
2648                         start += _session->timecode_offset ();
2649                 }
2650                 break;
2651
2652         case SnapToTimecodeMinutes:
2653                 if (_session->timecode_offset_negative())
2654                 {
2655                         start += _session->timecode_offset ();
2656                 } else {
2657                         start -= _session->timecode_offset ();
2658                 }
2659                 if (((direction == 0) && (start % one_timecode_minute > one_timecode_minute / 2)) || direction > 0) {
2660                         start = (nframes64_t) ceil ((double) start / one_timecode_minute) * one_timecode_minute;
2661                 } else {
2662                         start = (nframes64_t) floor ((double) start / one_timecode_minute) * one_timecode_minute;
2663                 }
2664                 if (_session->timecode_offset_negative())
2665                 {
2666                         start -= _session->timecode_offset ();
2667                 } else {
2668                         start += _session->timecode_offset ();
2669                 }
2670                 break;
2671         default:
2672                 fatal << "Editor::smpte_snap_to_internal() called with non-timecode snap type!" << endmsg;
2673                 /*NOTREACHED*/
2674         }
2675 }
2676
2677 void
2678 Editor::snap_to_internal (nframes64_t& start, int32_t direction, bool for_mark)
2679 {
2680         const nframes64_t one_second = _session->frame_rate();
2681         const nframes64_t one_minute = _session->frame_rate() * 60;
2682         nframes64_t presnap = start;
2683         nframes64_t before;
2684         nframes64_t after;
2685
2686         switch (_snap_type) {
2687         case SnapToTimecodeFrame:
2688         case SnapToTimecodeSeconds:
2689         case SnapToTimecodeMinutes:
2690                 return timecode_snap_to_internal (start, direction, for_mark);
2691
2692         case SnapToCDFrame:
2693                 if (((direction == 0) && (start % (one_second/75) > (one_second/75) / 2)) || (direction > 0)) {
2694                         start = (nframes64_t) ceil ((double) start / (one_second / 75)) * (one_second / 75);
2695                 } else {
2696                         start = (nframes64_t) floor ((double) start / (one_second / 75)) * (one_second / 75);
2697                 }
2698                 break;
2699
2700         case SnapToSeconds:
2701                 if (((direction == 0) && (start % one_second > one_second / 2)) || (direction > 0)) {
2702                         start = (nframes64_t) ceil ((double) start / one_second) * one_second;
2703                 } else {
2704                         start = (nframes64_t) floor ((double) start / one_second) * one_second;
2705                 }
2706                 break;
2707
2708         case SnapToMinutes:
2709                 if (((direction == 0) && (start % one_minute > one_minute / 2)) || (direction > 0)) {
2710                         start = (nframes64_t) ceil ((double) start / one_minute) * one_minute;
2711                 } else {
2712                         start = (nframes64_t) floor ((double) start / one_minute) * one_minute;
2713                 }
2714                 break;
2715
2716         case SnapToBar:
2717                 start = _session->tempo_map().round_to_bar (start, direction);
2718                 break;
2719
2720         case SnapToBeat:
2721                 start = _session->tempo_map().round_to_beat (start, direction);
2722                 break;
2723
2724         case SnapToBeatDiv32:
2725                 start = _session->tempo_map().round_to_beat_subdivision (start, 32, direction);
2726                 break;
2727         case SnapToBeatDiv28:
2728                 start = _session->tempo_map().round_to_beat_subdivision (start, 28, direction);
2729                 break;
2730         case SnapToBeatDiv24:
2731                 start = _session->tempo_map().round_to_beat_subdivision (start, 24, direction);
2732                 break;
2733         case SnapToBeatDiv16:
2734                 start = _session->tempo_map().round_to_beat_subdivision (start, 16, direction);
2735                 break;
2736         case SnapToBeatDiv14:
2737                 start = _session->tempo_map().round_to_beat_subdivision (start, 14, direction);
2738                 break;
2739         case SnapToBeatDiv12:
2740                 start = _session->tempo_map().round_to_beat_subdivision (start, 12, direction);
2741                 break;
2742         case SnapToBeatDiv10:
2743                 start = _session->tempo_map().round_to_beat_subdivision (start, 10, direction);
2744                 break;
2745         case SnapToBeatDiv8:
2746                 start = _session->tempo_map().round_to_beat_subdivision (start, 8, direction);
2747                 break;
2748         case SnapToBeatDiv7:
2749                 start = _session->tempo_map().round_to_beat_subdivision (start, 7, direction);
2750                 break;
2751         case SnapToBeatDiv6:
2752                 start = _session->tempo_map().round_to_beat_subdivision (start, 6, direction);
2753                 break;
2754         case SnapToBeatDiv5:
2755                 start = _session->tempo_map().round_to_beat_subdivision (start, 5, direction);
2756                 break;
2757         case SnapToBeatDiv4:
2758                 start = _session->tempo_map().round_to_beat_subdivision (start, 4, direction);
2759                 break;
2760         case SnapToBeatDiv3:
2761                 start = _session->tempo_map().round_to_beat_subdivision (start, 3, direction);
2762                 break;
2763         case SnapToBeatDiv2:
2764                 start = _session->tempo_map().round_to_beat_subdivision (start, 2, direction);
2765                 break;
2766
2767         case SnapToMark:
2768                 if (for_mark) {
2769                         return;
2770                 }
2771
2772                 _session->locations()->marks_either_side (start, before, after);
2773
2774                 if (before == max_frames) {
2775                         start = after;
2776                 } else if (after == max_frames) {
2777                         start = before;
2778                 } else if (before != max_frames && after != max_frames) {
2779                         /* have before and after */
2780                         if ((start - before) < (after - start)) {
2781                                 start = before;
2782                         } else {
2783                                 start = after;
2784                         }
2785                 }
2786
2787                 break;
2788
2789         case SnapToRegionStart:
2790         case SnapToRegionEnd:
2791         case SnapToRegionSync:
2792         case SnapToRegionBoundary:
2793                 if (!region_boundary_cache.empty()) {
2794
2795                         vector<nframes64_t>::iterator prev = region_boundary_cache.end ();
2796                         vector<nframes64_t>::iterator next = region_boundary_cache.end ();
2797
2798                         if (direction > 0) {
2799                                 next = std::upper_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2800                         } else {
2801                                 next = std::lower_bound (region_boundary_cache.begin(), region_boundary_cache.end(), start);
2802                         }
2803
2804                         if (next != region_boundary_cache.begin ()) {
2805                                 prev = next;
2806                                 prev--;
2807                         }
2808
2809                         nframes64_t const p = (prev == region_boundary_cache.end()) ? region_boundary_cache.front () : *prev;
2810                         nframes64_t const n = (next == region_boundary_cache.end()) ? region_boundary_cache.back () : *next;
2811
2812                         if (start > (p + n) / 2) {
2813                                 start = n;
2814                         } else {
2815                                 start = p;
2816                         }
2817                 }
2818                 break;
2819         }
2820
2821         switch (_snap_mode) {
2822         case SnapNormal:
2823                 return;
2824
2825         case SnapMagnetic:
2826
2827                 if (presnap > start) {
2828                         if (presnap > (start + unit_to_frame(snap_threshold))) {
2829                                 start = presnap;
2830                         }
2831
2832                 } else if (presnap < start) {
2833                         if (presnap < (start - unit_to_frame(snap_threshold))) {
2834                                 start = presnap;
2835                         }
2836                 }
2837
2838         default:
2839                 /* handled at entry */
2840                 return;
2841
2842         }
2843 }
2844
2845
2846 void
2847 Editor::setup_toolbar ()
2848 {
2849         string pixmap_path;
2850
2851         /* Mode Buttons (tool selection) */
2852
2853         mouse_move_button.set_relief(Gtk::RELIEF_NONE);
2854         mouse_select_button.set_relief(Gtk::RELIEF_NONE);
2855         mouse_gain_button.set_relief(Gtk::RELIEF_NONE);
2856         mouse_zoom_button.set_relief(Gtk::RELIEF_NONE);
2857         mouse_timefx_button.set_relief(Gtk::RELIEF_NONE);
2858         mouse_audition_button.set_relief(Gtk::RELIEF_NONE);
2859         // internal_edit_button.set_relief(Gtk::RELIEF_NONE);
2860         join_object_range_button.set_relief(Gtk::RELIEF_NONE);
2861
2862         HBox* mode_box = manage(new HBox);
2863         mode_box->set_border_width (2);
2864         mode_box->set_spacing(4);
2865
2866         /* table containing mode buttons */
2867
2868         HBox* mouse_mode_button_box = manage (new HBox ());
2869
2870         if (Profile->get_sae()) {
2871                 mouse_mode_button_box->pack_start (mouse_move_button);
2872         } else {
2873                 mouse_mode_button_box->pack_start (mouse_move_button);
2874                 mouse_mode_button_box->pack_start (join_object_range_button);
2875                 mouse_mode_button_box->pack_start (mouse_select_button);
2876         }
2877
2878         mouse_mode_button_box->pack_start (mouse_zoom_button);
2879
2880         if (!Profile->get_sae()) {
2881                 mouse_mode_button_box->pack_start (mouse_gain_button);
2882         }
2883
2884         mouse_mode_button_box->pack_start (mouse_timefx_button);
2885         mouse_mode_button_box->pack_start (mouse_audition_button);
2886         mouse_mode_button_box->pack_start (internal_edit_button);
2887
2888         vector<string> edit_mode_strings;
2889         edit_mode_strings.push_back (edit_mode_to_string (Slide));
2890         if (!Profile->get_sae()) {
2891                 edit_mode_strings.push_back (edit_mode_to_string (Splice));
2892         }
2893         edit_mode_strings.push_back (edit_mode_to_string (Lock));
2894
2895         edit_mode_selector.set_name ("EditModeSelector");
2896         set_popdown_strings (edit_mode_selector, edit_mode_strings, true);
2897         edit_mode_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::edit_mode_selection_done));
2898
2899         mode_box->pack_start (edit_mode_selector);
2900         mode_box->pack_start (*mouse_mode_button_box);
2901
2902         _mouse_mode_tearoff = manage (new TearOff (*mode_box));
2903         _mouse_mode_tearoff->set_name ("MouseModeBase");
2904         _mouse_mode_tearoff->tearoff_window().signal_key_press_event().connect (sigc::bind (sigc::ptr_fun (relay_key_press), &_mouse_mode_tearoff->tearoff_window()), false);
2905
2906         if (Profile->get_sae()) {
2907                 _mouse_mode_tearoff->set_can_be_torn_off (false);
2908         }
2909
2910         _mouse_mode_tearoff->Detach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
2911                                                          &_mouse_mode_tearoff->tearoff_window()));
2912         _mouse_mode_tearoff->Attach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
2913                                                          &_mouse_mode_tearoff->tearoff_window(), 1));
2914         _mouse_mode_tearoff->Hidden.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
2915                                                          &_mouse_mode_tearoff->tearoff_window()));
2916         _mouse_mode_tearoff->Visible.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
2917                                                           &_mouse_mode_tearoff->tearoff_window(), 1));
2918
2919         mouse_move_button.set_mode (false);
2920         mouse_select_button.set_mode (false);
2921         mouse_gain_button.set_mode (false);
2922         mouse_zoom_button.set_mode (false);
2923         mouse_timefx_button.set_mode (false);
2924         mouse_audition_button.set_mode (false);
2925         join_object_range_button.set_mode (false);
2926
2927         mouse_move_button.set_name ("MouseModeButton");
2928         mouse_select_button.set_name ("MouseModeButton");
2929         mouse_gain_button.set_name ("MouseModeButton");
2930         mouse_zoom_button.set_name ("MouseModeButton");
2931         mouse_timefx_button.set_name ("MouseModeButton");
2932         mouse_audition_button.set_name ("MouseModeButton");
2933         internal_edit_button.set_name ("MouseModeButton");
2934         join_object_range_button.set_name ("MouseModeButton");
2935
2936         mouse_move_button.unset_flags (CAN_FOCUS);
2937         mouse_select_button.unset_flags (CAN_FOCUS);
2938         mouse_gain_button.unset_flags (CAN_FOCUS);
2939         mouse_zoom_button.unset_flags (CAN_FOCUS);
2940         mouse_timefx_button.unset_flags (CAN_FOCUS);
2941         mouse_audition_button.unset_flags (CAN_FOCUS);
2942         internal_edit_button.unset_flags (CAN_FOCUS);
2943         join_object_range_button.unset_flags (CAN_FOCUS);
2944
2945         /* Zoom */
2946
2947         _zoom_box.set_spacing (1);
2948         _zoom_box.set_border_width (0);
2949
2950         zoom_in_button.set_name ("EditorTimeButton");
2951         zoom_in_button.set_image (*(manage (new Image (Stock::ZOOM_IN, Gtk::ICON_SIZE_MENU))));
2952         zoom_in_button.signal_clicked().connect (sigc::bind (sigc::mem_fun(*this, &Editor::temporal_zoom_step), false));
2953
2954         zoom_out_button.set_name ("EditorTimeButton");
2955         zoom_out_button.set_image (*(manage (new Image (Stock::ZOOM_OUT, Gtk::ICON_SIZE_MENU))));
2956         zoom_out_button.signal_clicked().connect (sigc::bind (sigc::mem_fun(*this, &Editor::temporal_zoom_step), true));
2957
2958         zoom_out_full_button.set_name ("EditorTimeButton");
2959         zoom_out_full_button.set_image (*(manage (new Image (Stock::ZOOM_100, Gtk::ICON_SIZE_MENU))));
2960         zoom_out_full_button.signal_clicked().connect (sigc::mem_fun(*this, &Editor::temporal_zoom_session));
2961
2962         zoom_focus_selector.set_name ("ZoomFocusSelector");
2963         set_popdown_strings (zoom_focus_selector, zoom_focus_strings, true);
2964         zoom_focus_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::zoom_focus_selection_done));
2965
2966         _zoom_box.pack_start (zoom_out_button, false, false);
2967         _zoom_box.pack_start (zoom_in_button, false, false);
2968         _zoom_box.pack_start (zoom_out_full_button, false, false);
2969
2970         /* Track zoom buttons */
2971         tav_expand_button.set_name ("TrackHeightButton");
2972         tav_expand_button.set_size_request(-1,20);
2973         tav_expand_button.add (*(manage (new Image (::get_icon("tav_exp")))));
2974         tav_expand_button.signal_clicked().connect (sigc::bind (sigc::mem_fun(*this, &Editor::tav_zoom_step), true));
2975
2976         tav_shrink_button.set_name ("TrackHeightButton");
2977         tav_shrink_button.set_size_request(-1,20);
2978         tav_shrink_button.add (*(manage (new Image (::get_icon("tav_shrink")))));
2979         tav_shrink_button.signal_clicked().connect (sigc::bind (sigc::mem_fun(*this, &Editor::tav_zoom_step), false));
2980
2981         _zoom_box.pack_start (tav_expand_button);
2982         _zoom_box.pack_start (tav_shrink_button);
2983
2984         _zoom_box.pack_start (zoom_focus_selector);
2985         
2986         _zoom_tearoff = manage (new TearOff (_zoom_box));
2987
2988         _zoom_tearoff->Detach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
2989                                                    &_zoom_tearoff->tearoff_window()));
2990         _zoom_tearoff->Attach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
2991                                                    &_zoom_tearoff->tearoff_window(), 0));
2992         _zoom_tearoff->Hidden.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
2993                                                    &_zoom_tearoff->tearoff_window()));
2994         _zoom_tearoff->Visible.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
2995                                                     &_zoom_tearoff->tearoff_window(), 0));
2996         
2997         snap_box.set_spacing (1);
2998         snap_box.set_border_width (2);
2999
3000         snap_type_selector.set_name ("SnapTypeSelector");
3001         set_popdown_strings (snap_type_selector, snap_type_strings, true);
3002         snap_type_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::snap_type_selection_done));
3003
3004         snap_mode_selector.set_name ("SnapModeSelector");
3005         set_popdown_strings (snap_mode_selector, snap_mode_strings, true);
3006         snap_mode_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::snap_mode_selection_done));
3007
3008         edit_point_selector.set_name ("EditPointSelector");
3009         set_popdown_strings (edit_point_selector, edit_point_strings, true);
3010         edit_point_selector.signal_changed().connect (sigc::mem_fun(*this, &Editor::edit_point_selection_done));
3011
3012         snap_box.pack_start (snap_mode_selector, false, false);
3013         snap_box.pack_start (snap_type_selector, false, false);
3014         snap_box.pack_start (edit_point_selector, false, false);
3015
3016         /* Nudge */
3017
3018         HBox *nudge_box = manage (new HBox);
3019         nudge_box->set_spacing(1);
3020         nudge_box->set_border_width (2);
3021
3022         nudge_forward_button.signal_button_release_event().connect (sigc::mem_fun(*this, &Editor::nudge_forward_release), false);
3023         nudge_backward_button.signal_button_release_event().connect (sigc::mem_fun(*this, &Editor::nudge_backward_release), false);
3024
3025         nudge_box->pack_start (nudge_backward_button, false, false);
3026         nudge_box->pack_start (nudge_forward_button, false, false);
3027         nudge_box->pack_start (nudge_clock, false, false);
3028
3029
3030         /* Pack everything in... */
3031
3032         HBox* hbox = manage (new HBox);
3033         hbox->set_spacing(10);
3034
3035         _tools_tearoff = manage (new TearOff (*hbox));
3036         _tools_tearoff->set_name ("MouseModeBase");
3037         _tools_tearoff->tearoff_window().signal_key_press_event().connect (sigc::bind (sigc::ptr_fun (relay_key_press), &_tools_tearoff->tearoff_window()), false);
3038         
3039         if (Profile->get_sae()) {
3040                 _tools_tearoff->set_can_be_torn_off (false);
3041         }
3042
3043         _tools_tearoff->Detach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
3044                                                     &_tools_tearoff->tearoff_window()));
3045         _tools_tearoff->Attach.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3046                                                     &_tools_tearoff->tearoff_window(), 0));
3047         _tools_tearoff->Hidden.connect (sigc::bind (sigc::mem_fun(*this, &Editor::detach_tearoff), static_cast<Box*>(&toolbar_hbox),
3048                                                     &_tools_tearoff->tearoff_window()));
3049         _tools_tearoff->Visible.connect (sigc::bind (sigc::mem_fun(*this, &Editor::reattach_tearoff), static_cast<Box*> (&toolbar_hbox),
3050                                                      &_tools_tearoff->tearoff_window(), 0));
3051
3052         toolbar_hbox.set_spacing (10);
3053         toolbar_hbox.set_border_width (1);
3054
3055         toolbar_hbox.pack_start (*_mouse_mode_tearoff, false, false);
3056         toolbar_hbox.pack_start (*_zoom_tearoff, false, false);
3057         toolbar_hbox.pack_start (*_tools_tearoff, false, false);
3058
3059         hbox->pack_start (snap_box, false, false);
3060         hbox->pack_start (*nudge_box, false, false);
3061         hbox->pack_start (panic_box, false, false);
3062
3063         hbox->show_all ();
3064
3065         toolbar_base.set_name ("ToolBarBase");
3066         toolbar_base.add (toolbar_hbox);
3067
3068         toolbar_frame.set_shadow_type (SHADOW_OUT);
3069         toolbar_frame.set_name ("BaseFrame");
3070         toolbar_frame.add (toolbar_base);
3071 }
3072
3073 void
3074 Editor::setup_tooltips ()
3075 {
3076         ARDOUR_UI::instance()->set_tip (mouse_move_button, _("Select/Move Objects"));
3077         ARDOUR_UI::instance()->set_tip (mouse_gain_button, _("Draw Gain Automation"));
3078         ARDOUR_UI::instance()->set_tip (mouse_zoom_button, _("Select Zoom Range"));
3079         ARDOUR_UI::instance()->set_tip (mouse_timefx_button, _("Stretch/Shrink Regions and MIDI Notes"));
3080         ARDOUR_UI::instance()->set_tip (mouse_audition_button, _("Listen to Specific Regions"));
3081         ARDOUR_UI::instance()->set_tip (join_object_range_button, _("Select/Move Objects or Ranges"));
3082         ARDOUR_UI::instance()->set_tip (internal_edit_button, _("Edit Region Contents (e.g. notes)"));
3083         ARDOUR_UI::instance()->set_tip (*_group_tabs, _("Groups: context-click for possible operations"));
3084         ARDOUR_UI::instance()->set_tip (nudge_forward_button, _("Nudge Region/Selection Forwards"));
3085         ARDOUR_UI::instance()->set_tip (nudge_backward_button, _("Nudge Region/Selection Backwards"));
3086         ARDOUR_UI::instance()->set_tip (zoom_in_button, _("Zoom In"));
3087         ARDOUR_UI::instance()->set_tip (zoom_out_button, _("Zoom Out"));
3088         ARDOUR_UI::instance()->set_tip (zoom_out_full_button, _("Zoom to Session"));
3089         ARDOUR_UI::instance()->set_tip (zoom_focus_selector, _("Zoom focus"));
3090         ARDOUR_UI::instance()->set_tip (tav_expand_button, _("Expand Tracks"));
3091         ARDOUR_UI::instance()->set_tip (tav_shrink_button, _("Shrink Tracks"));
3092         ARDOUR_UI::instance()->set_tip (snap_type_selector, _("Snap/Grid Units"));
3093         ARDOUR_UI::instance()->set_tip (snap_mode_selector, _("Snap/Grid Mode"));
3094         ARDOUR_UI::instance()->set_tip (edit_point_selector, _("Edit point"));
3095         ARDOUR_UI::instance()->set_tip (midi_sound_notes, _("Sound Notes"));
3096         ARDOUR_UI::instance()->set_tip (midi_panic_button, _("Send note off and reset controller messages on all MIDI channels"));
3097         ARDOUR_UI::instance()->set_tip (edit_mode_selector, _("Edit Mode"));
3098 }
3099
3100 void
3101 Editor::midi_panic ()
3102 {
3103         cerr << "MIDI panic\n";
3104
3105         if (_session) {
3106                 _session->midi_panic();
3107         }
3108 }
3109
3110 void
3111 Editor::setup_midi_toolbar ()
3112 {
3113         RefPtr<Action> act;
3114
3115         /* Midi sound notes */
3116         midi_sound_notes.add (*(manage (new Image (::get_icon("midi_sound_notes")))));
3117         midi_sound_notes.set_relief(Gtk::RELIEF_NONE);
3118         midi_sound_notes.unset_flags (CAN_FOCUS);
3119
3120         /* Panic */
3121
3122         act = ActionManager::get_action (X_("MIDI"), X_("panic"));
3123         midi_panic_button.set_name("MidiPanicButton");
3124         act->connect_proxy (midi_panic_button);
3125
3126         panic_box.pack_start (midi_sound_notes , true, true);
3127         panic_box.pack_start (midi_panic_button, true, true);
3128 }
3129
3130 int
3131 Editor::convert_drop_to_paths (
3132                 vector<ustring>&                paths,
3133                 const RefPtr<Gdk::DragContext>& /*context*/,
3134                 gint                            /*x*/,
3135                 gint                            /*y*/,
3136                 const SelectionData&            data,
3137                 guint                           /*info*/,
3138                 guint                           /*time*/)
3139 {
3140         if (_session == 0) {
3141                 return -1;
3142         }
3143
3144         vector<ustring> uris = data.get_uris();
3145
3146         if (uris.empty()) {
3147
3148                 /* This is seriously fucked up. Nautilus doesn't say that its URI lists
3149                    are actually URI lists. So do it by hand.
3150                 */
3151
3152                 if (data.get_target() != "text/plain") {
3153                         return -1;
3154                 }
3155
3156                 /* Parse the "uri-list" format that Nautilus provides,
3157                    where each pathname is delimited by \r\n.
3158
3159                    THERE MAY BE NO NULL TERMINATING CHAR!!!
3160                 */
3161
3162                 ustring txt = data.get_text();
3163                 const char* p;
3164                 const char* q;
3165
3166                 p = (const char *) malloc (txt.length() + 1);
3167                 txt.copy ((char *) p, txt.length(), 0);
3168                 ((char*)p)[txt.length()] = '\0';
3169
3170                 while (p)
3171                 {
3172                         if (*p != '#')
3173                         {
3174                                 while (g_ascii_isspace (*p))
3175                                         p++;
3176
3177                                 q = p;
3178                                 while (*q && (*q != '\n') && (*q != '\r')) {
3179                                         q++;
3180                                 }
3181
3182                                 if (q > p)
3183                                 {
3184                                         q--;
3185                                         while (q > p && g_ascii_isspace (*q))
3186                                                 q--;
3187
3188                                         if (q > p)
3189                                         {
3190                                                 uris.push_back (ustring (p, q - p + 1));
3191                                         }
3192                                 }
3193                         }
3194                         p = strchr (p, '\n');
3195                         if (p)
3196                                 p++;
3197                 }
3198
3199                 free ((void*)p);
3200
3201                 if (uris.empty()) {
3202                         return -1;
3203                 }
3204         }
3205
3206         for (vector<ustring>::iterator i = uris.begin(); i != uris.end(); ++i) {
3207
3208                 if ((*i).substr (0,7) == "file://") {
3209
3210                         ustring p = *i;
3211                         PBD::url_decode (p);
3212
3213                         // scan forward past three slashes
3214
3215                         ustring::size_type slashcnt = 0;
3216                         ustring::size_type n = 0;
3217                         ustring::iterator x = p.begin();
3218
3219                         while (slashcnt < 3 && x != p.end()) {
3220                                 if ((*x) == '/') {
3221                                         slashcnt++;
3222                                 } else if (slashcnt == 3) {
3223                                         break;
3224                                 }
3225                                 ++n;
3226                                 ++x;
3227                         }
3228
3229                         if (slashcnt != 3 || x == p.end()) {
3230                                 error << _("malformed URL passed to drag-n-drop code") << endmsg;
3231                                 continue;
3232                         }
3233
3234                         paths.push_back (p.substr (n - 1));
3235                 }
3236         }
3237
3238         return 0;
3239 }
3240
3241 void
3242 Editor::new_tempo_section ()
3243
3244 {
3245 }
3246
3247 void
3248 Editor::map_transport_state ()
3249 {
3250         ENSURE_GUI_THREAD (*this, &Editor::map_transport_state)
3251
3252         if (_session && _session->transport_stopped()) {
3253                 have_pending_keyboard_selection = false;
3254         }
3255
3256         update_loop_range_view (true);
3257 }
3258
3259 /* UNDO/REDO */
3260
3261 Editor::State::State (PublicEditor const * e)
3262 {
3263         selection = new Selection (e);
3264 }
3265
3266 Editor::State::~State ()
3267 {
3268         delete selection;
3269 }
3270
3271 void
3272 Editor::begin_reversible_command (string name)
3273 {
3274         if (_session) {
3275                 _session->begin_reversible_command (name);
3276         }
3277 }
3278
3279 void
3280 Editor::commit_reversible_command ()
3281 {
3282         if (_session) {
3283                 _session->commit_reversible_command ();
3284         }
3285 }
3286
3287 void
3288 Editor::set_route_group_solo (Route& route, bool yn)
3289 {
3290         RouteGroup *route_group;
3291
3292         if ((route_group = route.route_group()) != 0) {
3293                 route_group->apply (&Route::set_solo, yn, this);
3294         } else {
3295                 route.set_solo (yn, this);
3296         }
3297 }
3298
3299 void
3300 Editor::set_route_group_mute (Route& route, bool yn)
3301 {
3302         RouteGroup *route_group = 0;
3303
3304         if ((route_group = route.route_group()) != 0) {
3305                 route_group->apply (&Route::set_mute, yn, this);
3306         } else {
3307                 route.set_mute (yn, this);
3308         }
3309 }
3310
3311 void
3312 Editor::history_changed ()
3313 {
3314         string label;
3315
3316         if (undo_action && _session) {
3317                 if (_session->undo_depth() == 0) {
3318                         label = _("Undo");
3319                 } else {
3320                         label = string_compose(_("Undo (%1)"), _session->next_undo());
3321                 }
3322                 undo_action->property_label() = label;
3323         }
3324
3325         if (redo_action && _session) {
3326                 if (_session->redo_depth() == 0) {
3327                         label = _("Redo");
3328                 } else {
3329                         label = string_compose(_("Redo (%1)"), _session->next_redo());
3330                 }
3331                 redo_action->property_label() = label;
3332         }
3333 }
3334
3335 void
3336 Editor::duplicate_dialog (bool with_dialog)
3337 {
3338         float times = 1.0f;
3339
3340         if (mouse_mode == MouseRange) {
3341                 if (selection->time.length() == 0) {
3342                         return;
3343                 }
3344         }
3345
3346         RegionSelection rs;
3347         get_regions_for_action (rs);
3348
3349         if (mouse_mode != MouseRange) {
3350
3351                 if (rs.empty()) {
3352                         return;
3353                 }
3354         }
3355
3356         if (with_dialog) {
3357
3358                 ArdourDialog win (_("Duplicate"));
3359                 Label label (_("Number of duplications:"));
3360                 Adjustment adjustment (1.0, 1.0, 1000000.0, 1.0, 5.0);
3361                 SpinButton spinner (adjustment, 0.0, 1);
3362                 HBox hbox;
3363
3364                 win.get_vbox()->set_spacing (12);
3365                 win.get_vbox()->pack_start (hbox);
3366                 hbox.set_border_width (6);
3367                 hbox.pack_start (label, PACK_EXPAND_PADDING, 12);
3368
3369                 /* dialogs have ::add_action_widget() but that puts the spinner in the wrong
3370                    place, visually. so do this by hand.
3371                 */
3372
3373                 hbox.pack_start (spinner, PACK_EXPAND_PADDING, 12);
3374                 spinner.signal_activate().connect (sigc::bind (sigc::mem_fun (win, &ArdourDialog::response), RESPONSE_ACCEPT));
3375                 spinner.grab_focus();
3376
3377                 hbox.show ();
3378                 label.show ();
3379                 spinner.show ();
3380
3381                 win.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3382                 win.add_button (_("Duplicate"), RESPONSE_ACCEPT);
3383                 win.set_default_response (RESPONSE_ACCEPT);
3384
3385                 win.set_position (WIN_POS_MOUSE);
3386
3387                 spinner.grab_focus ();
3388
3389                 switch (win.run ()) {
3390                 case RESPONSE_ACCEPT:
3391                         break;
3392                 default:
3393                         return;
3394                 }
3395
3396                 times = adjustment.get_value();
3397         }
3398
3399         if (mouse_mode == MouseRange) {
3400                 duplicate_selection (times);
3401         } else {
3402                 duplicate_some_regions (rs, times);
3403         }
3404 }
3405
3406 void
3407 Editor::show_verbose_canvas_cursor ()
3408 {
3409         verbose_canvas_cursor->raise_to_top();
3410         verbose_canvas_cursor->show();
3411         verbose_cursor_visible = true;
3412 }
3413
3414 void
3415 Editor::hide_verbose_canvas_cursor ()
3416 {
3417         verbose_canvas_cursor->hide();
3418         verbose_cursor_visible = false;
3419 }
3420
3421 double
3422 Editor::clamp_verbose_cursor_x (double x)
3423 {
3424         if (x < 0) {
3425                 x = 0;
3426         } else {
3427                 x = min (_canvas_width - 200.0, x);
3428         }
3429         return x;
3430 }
3431
3432 double
3433 Editor::clamp_verbose_cursor_y (double y)
3434 {
3435         if (y < canvas_timebars_vsize) {
3436                 y = canvas_timebars_vsize;
3437         } else {
3438                 y = min (_canvas_height - 50, y);
3439         }
3440         return y;
3441 }
3442
3443 void
3444 Editor::show_verbose_canvas_cursor_with (const string & txt)
3445 {
3446         verbose_canvas_cursor->property_text() = txt.c_str();
3447
3448         int x, y;
3449         double wx, wy;
3450
3451         track_canvas->get_pointer (x, y);
3452         track_canvas->window_to_world (x, y, wx, wy);
3453
3454         /* don't get too close to the edge */
3455         verbose_canvas_cursor->property_x() = clamp_verbose_cursor_x (wx);
3456         verbose_canvas_cursor->property_y() = clamp_verbose_cursor_y (wy);
3457
3458         show_verbose_canvas_cursor ();
3459 }
3460
3461 void
3462 Editor::set_verbose_canvas_cursor (const string & txt, double x, double y)
3463 {
3464         verbose_canvas_cursor->property_text() = txt.c_str();
3465         /* don't get too close to the edge */
3466         verbose_canvas_cursor->property_x() = clamp_verbose_cursor_x (x);
3467         verbose_canvas_cursor->property_y() = clamp_verbose_cursor_y (y);
3468 }
3469
3470 void
3471 Editor::set_verbose_canvas_cursor_text (const string & txt)
3472 {
3473         verbose_canvas_cursor->property_text() = txt.c_str();
3474 }
3475
3476 void
3477 Editor::set_edit_mode (EditMode m)
3478 {
3479         Config->set_edit_mode (m);
3480 }
3481
3482 void
3483 Editor::cycle_edit_mode ()
3484 {
3485         switch (Config->get_edit_mode()) {
3486         case Slide:
3487                 if (Profile->get_sae()) {
3488                         Config->set_edit_mode (Lock);
3489                 } else {
3490                         Config->set_edit_mode (Splice);
3491                 }
3492                 break;
3493         case Splice:
3494                 Config->set_edit_mode (Lock);
3495                 break;
3496         case Lock:
3497                 Config->set_edit_mode (Slide);
3498                 break;
3499         }
3500 }
3501
3502 void
3503 Editor::edit_mode_selection_done ()
3504 {
3505         Config->set_edit_mode (string_to_edit_mode (edit_mode_selector.get_active_text ()));
3506 }
3507
3508 void
3509 Editor::snap_type_selection_done ()
3510 {
3511         string choice = snap_type_selector.get_active_text();
3512         SnapType snaptype = SnapToBeat;
3513
3514         if (choice == _("Beats/2")) {
3515                 snaptype = SnapToBeatDiv2;
3516         } else if (choice == _("Beats/3")) {
3517                 snaptype = SnapToBeatDiv3;
3518         } else if (choice == _("Beats/4")) {
3519                 snaptype = SnapToBeatDiv4;
3520         } else if (choice == _("Beats/5")) {
3521                 snaptype = SnapToBeatDiv5;
3522         } else if (choice == _("Beats/6")) {
3523                 snaptype = SnapToBeatDiv6;
3524         } else if (choice == _("Beats/7")) {
3525                 snaptype = SnapToBeatDiv7;
3526         } else if (choice == _("Beats/8")) {
3527                 snaptype = SnapToBeatDiv8;
3528         } else if (choice == _("Beats/10")) {
3529                 snaptype = SnapToBeatDiv10;
3530         } else if (choice == _("Beats/12")) {
3531                 snaptype = SnapToBeatDiv12;
3532         } else if (choice == _("Beats/14")) {
3533                 snaptype = SnapToBeatDiv14;
3534         } else if (choice == _("Beats/16")) {
3535                 snaptype = SnapToBeatDiv16;
3536         } else if (choice == _("Beats/24")) {
3537                 snaptype = SnapToBeatDiv24;
3538         } else if (choice == _("Beats/28")) {
3539                 snaptype = SnapToBeatDiv28;
3540         } else if (choice == _("Beats/32")) {
3541                 snaptype = SnapToBeatDiv32;
3542         } else if (choice == _("Beats")) {
3543                 snaptype = SnapToBeat;
3544         } else if (choice == _("Bars")) {
3545                 snaptype = SnapToBar;
3546         } else if (choice == _("Marks")) {
3547                 snaptype = SnapToMark;
3548         } else if (choice == _("Region starts")) {
3549                 snaptype = SnapToRegionStart;
3550         } else if (choice == _("Region ends")) {
3551                 snaptype = SnapToRegionEnd;
3552         } else if (choice == _("Region bounds")) {
3553                 snaptype = SnapToRegionBoundary;
3554         } else if (choice == _("Region syncs")) {
3555                 snaptype = SnapToRegionSync;
3556         } else if (choice == _("CD Frames")) {
3557                 snaptype = SnapToCDFrame;
3558         } else if (choice == _("Timecode Frames")) {
3559                 snaptype = SnapToTimecodeFrame;
3560         } else if (choice == _("Timecode Seconds")) {
3561                 snaptype = SnapToTimecodeSeconds;
3562         } else if (choice == _("Timecode Minutes")) {
3563                 snaptype = SnapToTimecodeMinutes;
3564         } else if (choice == _("Seconds")) {
3565                 snaptype = SnapToSeconds;
3566         } else if (choice == _("Minutes")) {
3567                 snaptype = SnapToMinutes;
3568         }
3569
3570         RefPtr<RadioAction> ract = snap_type_action (snaptype);
3571         if (ract) {
3572                 ract->set_active ();
3573         }
3574 }
3575
3576 void
3577 Editor::snap_mode_selection_done ()
3578 {
3579         string choice = snap_mode_selector.get_active_text();
3580         SnapMode mode = SnapNormal;
3581
3582         if (choice == _("No Grid")) {
3583                 mode = SnapOff;
3584         } else if (choice == _("Grid")) {
3585                 mode = SnapNormal;
3586         } else if (choice == _("Magnetic")) {
3587                 mode = SnapMagnetic;
3588         }
3589
3590         RefPtr<RadioAction> ract = snap_mode_action (mode);
3591
3592         if (ract) {
3593                 ract->set_active (true);
3594         }
3595 }
3596
3597 void
3598 Editor::cycle_edit_point (bool with_marker)
3599 {
3600         switch (_edit_point) {
3601         case EditAtMouse:
3602                 set_edit_point_preference (EditAtPlayhead);
3603                 break;
3604         case EditAtPlayhead:
3605                 if (with_marker) {
3606                         set_edit_point_preference (EditAtSelectedMarker);
3607                 } else {
3608                         set_edit_point_preference (EditAtMouse);
3609                 }
3610                 break;
3611         case EditAtSelectedMarker:
3612                 set_edit_point_preference (EditAtMouse);
3613                 break;
3614         }
3615 }
3616
3617 void
3618 Editor::edit_point_selection_done ()
3619 {
3620         string choice = edit_point_selector.get_active_text();
3621         EditPoint ep = EditAtSelectedMarker;
3622
3623         if (choice == _("Marker")) {
3624                 set_edit_point_preference (EditAtSelectedMarker);
3625         } else if (choice == _("Playhead")) {
3626                 set_edit_point_preference (EditAtPlayhead);
3627         } else {
3628                 set_edit_point_preference (EditAtMouse);
3629         }
3630
3631         RefPtr<RadioAction> ract = edit_point_action (ep);
3632
3633         if (ract) {
3634                 ract->set_active (true);
3635         }
3636 }
3637
3638 void
3639 Editor::zoom_focus_selection_done ()
3640 {
3641         string choice = zoom_focus_selector.get_active_text();
3642         ZoomFocus focus_type = ZoomFocusLeft;
3643
3644         if (choice == _("Left")) {
3645                 focus_type = ZoomFocusLeft;
3646         } else if (choice == _("Right")) {
3647                 focus_type = ZoomFocusRight;
3648         } else if (choice == _("Center")) {
3649                 focus_type = ZoomFocusCenter;
3650         } else if (choice == _("Playhead")) {
3651                 focus_type = ZoomFocusPlayhead;
3652         } else if (choice == _("Mouse")) {
3653                 focus_type = ZoomFocusMouse;
3654         } else if (choice == _("Edit point")) {
3655                 focus_type = ZoomFocusEdit;
3656         }
3657
3658         RefPtr<RadioAction> ract = zoom_focus_action (focus_type);
3659
3660         if (ract) {
3661                 ract->set_active ();
3662         }
3663 }
3664
3665 gint
3666 Editor::edit_controls_button_release (GdkEventButton* ev)
3667 {
3668         if (Keyboard::is_context_menu_event (ev)) {
3669                 ARDOUR_UI::instance()->add_route (this);
3670         }
3671         return TRUE;
3672 }
3673
3674 gint
3675 Editor::mouse_select_button_release (GdkEventButton* ev)
3676 {
3677         /* this handles just right-clicks */
3678
3679         if (ev->button != 3) {
3680                 return false;
3681         }
3682
3683         return true;
3684 }
3685
3686 void
3687 Editor::set_zoom_focus (ZoomFocus f)
3688 {
3689         string str = zoom_focus_strings[(int)f];
3690
3691         if (str != zoom_focus_selector.get_active_text()) {
3692                 zoom_focus_selector.set_active_text (str);
3693         }
3694
3695         if (zoom_focus != f) {
3696                 zoom_focus = f;
3697
3698                 ZoomFocusChanged (); /* EMIT_SIGNAL */
3699
3700                 instant_save ();
3701         }
3702 }
3703
3704 void
3705 Editor::ensure_float (Window& win)
3706 {
3707         win.set_transient_for (*this);
3708 }
3709
3710 void
3711 Editor::pane_allocation_handler (Allocation &alloc, Paned* which)
3712 {
3713         /* recover or initialize pane positions. do this here rather than earlier because
3714            we don't want the positions to change the child allocations, which they seem to do.
3715          */
3716
3717         int pos;
3718         XMLProperty* prop;
3719         char buf[32];
3720         XMLNode* node = ARDOUR_UI::instance()->editor_settings();
3721         int width, height;
3722
3723         enum Pane {
3724                 Horizontal = 0x1,
3725                 Vertical = 0x2
3726         };
3727
3728         static Pane done;
3729         
3730         XMLNode* geometry;
3731
3732         width = default_width;
3733         height = default_height;
3734
3735         if ((geometry = find_named_node (*node, "geometry")) != 0) {
3736
3737                 prop = geometry->property ("x-size");
3738                 if (prop) {
3739                         width = atoi (prop->value());
3740                 }
3741                 prop = geometry->property ("y-size");
3742                 if (prop) {
3743                         height = atoi (prop->value());
3744                 }
3745         }
3746
3747         if (which == static_cast<Paned*> (&edit_pane)) {
3748
3749                 if (done & Horizontal) {
3750                         return;
3751                 }
3752
3753                 if (!geometry || (prop = geometry->property ("edit-horizontal-pane-pos")) == 0) {
3754                         /* initial allocation is 90% to canvas, 10% to notebook */
3755                         pos = (int) floor (alloc.get_width() * 0.90f);
3756                         snprintf (buf, sizeof(buf), "%d", pos);
3757                 } else {
3758                         pos = atoi (prop->value());
3759                 }
3760
3761                 if (GTK_WIDGET(edit_pane.gobj())->allocation.width > pos) {
3762                         edit_pane.set_position (pos);
3763                         pre_maximal_horizontal_pane_position = pos;
3764                 }
3765
3766                 done = (Pane) (done | Horizontal);
3767                 
3768         } else if (which == static_cast<Paned*> (&editor_summary_pane)) {
3769
3770                 if (done & Vertical) {
3771                         return;
3772                 }
3773
3774                 if (!geometry || (prop = geometry->property ("edit-vertical-pane-pos")) == 0) {
3775                         /* initial allocation is 90% to canvas, 10% to summary */
3776                         pos = (int) floor (alloc.get_height() * 0.90f);
3777                         snprintf (buf, sizeof(buf), "%d", pos);
3778                 } else {
3779                         pos = atoi (prop->value());
3780                 }
3781
3782                 if (GTK_WIDGET(editor_summary_pane.gobj())->allocation.height > pos) {
3783                         editor_summary_pane.set_position (pos);
3784                         pre_maximal_vertical_pane_position = pos;
3785                 }
3786
3787                 done = (Pane) (done | Vertical);
3788         }
3789 }
3790
3791 void
3792 Editor::detach_tearoff (Box* /*b*/, Window* /*w*/)
3793 {
3794         if (_tools_tearoff->torn_off() && _mouse_mode_tearoff->torn_off()) {
3795                 top_hbox.remove (toolbar_frame);
3796         }
3797 }
3798
3799 void
3800 Editor::reattach_tearoff (Box* /*b*/, Window* /*w*/, int32_t /*n*/)
3801 {
3802         if (toolbar_frame.get_parent() == 0) {
3803                 top_hbox.pack_end (toolbar_frame);
3804         }
3805 }
3806
3807 void
3808 Editor::set_show_measures (bool yn)
3809 {
3810         if (_show_measures != yn) {
3811                 hide_measures ();
3812
3813                 if ((_show_measures = yn) == true) {
3814                         if (tempo_lines)
3815                                 tempo_lines->show();
3816                         draw_measures ();
3817                 }
3818                 instant_save ();
3819         }
3820 }
3821
3822 void
3823 Editor::toggle_follow_playhead ()
3824 {
3825         RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-follow-playhead"));
3826         if (act) {
3827                 RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
3828                 set_follow_playhead (tact->get_active());
3829         }
3830 }
3831
3832 void
3833 Editor::set_follow_playhead (bool yn)
3834 {
3835         if (_follow_playhead != yn) {
3836                 if ((_follow_playhead = yn) == true) {
3837                         /* catch up */
3838                         reset_x_origin_to_follow_playhead ();
3839                 }
3840                 instant_save ();
3841         }
3842 }
3843
3844 void
3845 Editor::toggle_stationary_playhead ()
3846 {
3847        RefPtr<Action> act = ActionManager::get_action (X_("Editor"), X_("toggle-stationary-playhead"));
3848        if (act) {
3849                RefPtr<ToggleAction> tact = RefPtr<ToggleAction>::cast_dynamic(act);
3850                set_stationary_playhead (tact->get_active());
3851        }
3852 }
3853
3854 void
3855 Editor::set_stationary_playhead (bool yn)
3856 {
3857        if (_stationary_playhead != yn) {
3858                if ((_stationary_playhead = yn) == true) {
3859                        /* catch up */
3860                        // FIXME need a 3.0 equivalent of this 2.X call
3861                        // update_current_screen ();
3862                }
3863                instant_save ();
3864        }
3865 }
3866
3867 void
3868 Editor::toggle_xfade_active (boost::weak_ptr<Crossfade> wxfade)
3869 {
3870         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3871         if (xfade) {
3872                 xfade->set_active (!xfade->active());
3873         }
3874 }
3875
3876 void
3877 Editor::toggle_xfade_length (boost::weak_ptr<Crossfade> wxfade)
3878 {
3879         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3880         if (xfade) {
3881                 xfade->set_follow_overlap (!xfade->following_overlap());
3882         }
3883 }
3884
3885 void
3886 Editor::edit_xfade (boost::weak_ptr<Crossfade> wxfade)
3887 {
3888         boost::shared_ptr<Crossfade> xfade (wxfade.lock());
3889
3890         if (!xfade) {
3891                 return;
3892         }
3893
3894         CrossfadeEditor cew (_session, xfade, xfade->fade_in().get_min_y(), 1.0);
3895
3896         ensure_float (cew);
3897
3898         switch (cew.run ()) {
3899         case RESPONSE_ACCEPT:
3900                 break;
3901         default:
3902                 return;
3903         }
3904
3905         cew.apply ();
3906         PropertyChange all_crossfade_properties;
3907         all_crossfade_properties.add (ARDOUR::Properties::active);
3908         all_crossfade_properties.add (ARDOUR::Properties::follow_overlap);
3909         xfade->PropertyChanged (all_crossfade_properties);
3910 }
3911
3912 PlaylistSelector&
3913 Editor::playlist_selector () const
3914 {
3915         return *_playlist_selector;
3916 }
3917
3918 Evoral::MusicalTime
3919 Editor::get_grid_type_as_beats (bool& success, nframes64_t position)
3920 {
3921         success = true;
3922
3923         switch (_snap_type) {
3924         case SnapToBeat:
3925                 return 1.0;
3926                 break;
3927
3928         case SnapToBeatDiv32:
3929                 return 1.0/32.0;
3930                 break;
3931         case SnapToBeatDiv28:
3932                 return 1.0/28.0;
3933                 break;
3934         case SnapToBeatDiv24:
3935                 return 1.0/24.0;
3936                 break;
3937         case SnapToBeatDiv16:
3938                 return 1.0/16.0;
3939                 break;
3940         case SnapToBeatDiv14:
3941                 return 1.0/14.0;
3942                 break;
3943         case SnapToBeatDiv12:
3944                 return 1.0/12.0;
3945                 break;
3946         case SnapToBeatDiv10:
3947                 return 1.0/10.0;
3948                 break;
3949         case SnapToBeatDiv8:
3950                 return 1.0/8.0;
3951                 break;
3952         case SnapToBeatDiv7:
3953                 return 1.0/7.0;
3954                 break;
3955         case SnapToBeatDiv6:
3956                 return 1.0/6.0;
3957                 break;
3958         case SnapToBeatDiv5:
3959                 return 1.0/5.0;
3960                 break;
3961         case SnapToBeatDiv4:
3962                 return 1.0/4.0;
3963                 break;
3964         case SnapToBeatDiv3:
3965                 return 1.0/3.0;
3966                 break;
3967         case SnapToBeatDiv2:
3968                 return 1.0/2.0;
3969                 break;
3970
3971         case SnapToBar:
3972                 if (_session) {
3973                         return _session->tempo_map().meter_at (position).beats_per_bar();
3974                 }
3975                 break;
3976
3977         case SnapToCDFrame:
3978         case SnapToTimecodeFrame:
3979         case SnapToTimecodeSeconds:
3980         case SnapToTimecodeMinutes:
3981         case SnapToSeconds:
3982         case SnapToMinutes:
3983         case SnapToRegionStart:
3984         case SnapToRegionEnd:
3985         case SnapToRegionSync:
3986         case SnapToRegionBoundary:
3987         default:
3988                 success = false;
3989                 break;
3990         }
3991
3992         return 0.0;
3993 }
3994
3995 nframes64_t
3996 Editor::get_nudge_distance (nframes64_t pos, nframes64_t& next)
3997 {
3998         nframes64_t ret;
3999
4000         ret = nudge_clock.current_duration (pos);
4001         next = ret + 1; /* XXXX fix me */
4002
4003         return ret;
4004 }
4005
4006 int
4007 Editor::playlist_deletion_dialog (boost::shared_ptr<Playlist> pl)
4008 {
4009         ArdourDialog dialog (_("Playlist Deletion"));
4010         Label  label (string_compose (_("Playlist %1 is currently unused.\n"
4011                                         "If left alone, no audio files used by it will be cleaned.\n"
4012                                         "If deleted, audio files used by it alone by will cleaned."),
4013                                       pl->name()));
4014
4015         dialog.set_position (WIN_POS_CENTER);
4016         dialog.get_vbox()->pack_start (label);
4017
4018         label.show ();
4019
4020         dialog.add_button (_("Delete playlist"), RESPONSE_ACCEPT);
4021         dialog.add_button (_("Keep playlist"), RESPONSE_REJECT);
4022         dialog.add_button (_("Cancel"), RESPONSE_CANCEL);
4023
4024         switch (dialog.run ()) {
4025         case RESPONSE_ACCEPT:
4026                 /* delete the playlist */
4027                 return 0;
4028                 break;
4029
4030         case RESPONSE_REJECT:
4031                 /* keep the playlist */
4032                 return 1;
4033                 break;
4034
4035         default:
4036                 break;
4037         }
4038
4039         return -1;
4040 }
4041
4042 bool
4043 Editor::audio_region_selection_covers (nframes64_t where)
4044 {
4045         for (RegionSelection::iterator a = selection->regions.begin(); a != selection->regions.end(); ++a) {
4046                 if ((*a)->region()->covers (where)) {
4047                         return true;
4048                 }
4049         }
4050
4051         return false;
4052 }
4053
4054 void
4055 Editor::prepare_for_cleanup ()
4056 {
4057         cut_buffer->clear_regions ();
4058         cut_buffer->clear_playlists ();
4059
4060         selection->clear_regions ();
4061         selection->clear_playlists ();
4062
4063         _regions->suspend_redisplay ();
4064 }
4065
4066 void
4067 Editor::finish_cleanup ()
4068 {
4069         _regions->resume_redisplay ();
4070 }
4071
4072 Location*
4073 Editor::transport_loop_location()
4074 {
4075         if (_session) {
4076                 return _session->locations()->auto_loop_location();
4077         } else {
4078                 return 0;
4079         }
4080 }
4081
4082 Location*
4083 Editor::transport_punch_location()
4084 {
4085         if (_session) {
4086                 return _session->locations()->auto_punch_location();
4087         } else {
4088                 return 0;
4089         }
4090 }
4091
4092 bool
4093 Editor::control_layout_scroll (GdkEventScroll* ev)
4094 {
4095         if (Keyboard::some_magic_widget_has_focus()) {
4096                 return false;
4097         }
4098
4099         switch (ev->direction) {
4100         case GDK_SCROLL_UP:
4101                 scroll_tracks_up_line ();
4102                 return true;
4103                 break;
4104
4105         case GDK_SCROLL_DOWN:
4106                 scroll_tracks_down_line ();
4107                 return true;
4108
4109         default:
4110                 /* no left/right handling yet */
4111                 break;
4112         }
4113
4114         return false;
4115 }
4116
4117 void
4118 Editor::session_state_saved (string snap_name)
4119 {
4120         ENSURE_GUI_THREAD (*this, &Editor::session_state_saved, snap_name);
4121         
4122         update_title ();        
4123         _snapshots->redisplay ();
4124 }
4125
4126 void
4127 Editor::maximise_editing_space ()
4128 {
4129         _mouse_mode_tearoff->set_visible (false);
4130         _tools_tearoff->set_visible (false);
4131         _zoom_tearoff->set_visible (false);
4132
4133         pre_maximal_horizontal_pane_position = edit_pane.get_position ();
4134         pre_maximal_vertical_pane_position = editor_summary_pane.get_position ();
4135         pre_maximal_editor_width = this->get_width ();
4136         pre_maximal_editor_height = this->get_height ();
4137
4138         if (post_maximal_horizontal_pane_position == 0) {
4139                 post_maximal_horizontal_pane_position = edit_pane.get_width();
4140         }
4141
4142         if (post_maximal_vertical_pane_position == 0) {
4143                 post_maximal_vertical_pane_position = editor_summary_pane.get_height();
4144         }
4145         
4146         fullscreen ();
4147
4148         if (post_maximal_editor_width) {
4149                 edit_pane.set_position (post_maximal_horizontal_pane_position -
4150                         abs(post_maximal_editor_width - pre_maximal_editor_width));
4151         } else {
4152                 edit_pane.set_position (post_maximal_horizontal_pane_position);
4153         }
4154
4155         if (post_maximal_editor_height) {
4156                 editor_summary_pane.set_position (post_maximal_vertical_pane_position -
4157                         abs(post_maximal_editor_height - pre_maximal_editor_height));
4158         } else {
4159                 editor_summary_pane.set_position (post_maximal_vertical_pane_position);
4160         }
4161
4162         if (Config->get_keep_tearoffs()) {
4163                 _mouse_mode_tearoff->set_visible (true);
4164                 _tools_tearoff->set_visible (true);
4165                 _zoom_tearoff->set_visible (true);
4166         }
4167 }
4168
4169 void
4170 Editor::restore_editing_space ()
4171 {
4172         // user changed width/height of panes during fullscreen
4173
4174         if (post_maximal_horizontal_pane_position != edit_pane.get_position()) {
4175                 post_maximal_horizontal_pane_position = edit_pane.get_position();
4176         }
4177
4178         if (post_maximal_vertical_pane_position != editor_summary_pane.get_position()) {
4179                 post_maximal_vertical_pane_position = editor_summary_pane.get_position();
4180         }
4181         
4182         unfullscreen();
4183
4184         _mouse_mode_tearoff->set_visible (true);
4185         _tools_tearoff->set_visible (true);
4186         _zoom_tearoff->set_visible (true);
4187         post_maximal_editor_width = this->get_width();
4188         post_maximal_editor_height = this->get_height();
4189
4190         edit_pane.set_position (pre_maximal_horizontal_pane_position + abs(this->get_width() - pre_maximal_editor_width));
4191         editor_summary_pane.set_position (pre_maximal_vertical_pane_position + abs(this->get_height() - pre_maximal_editor_height));
4192 }
4193
4194 /**
4195  *  Make new playlists for a given track and also any others that belong
4196  *  to the same active route group with the `edit' property.
4197  *  @param v Track.
4198  */
4199
4200 void
4201 Editor::new_playlists (TimeAxisView* v)
4202 {
4203         begin_reversible_command (_("new playlists"));
4204         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4205         _session->playlists->get (playlists);
4206         mapover_tracks (sigc::bind (sigc::mem_fun (*this, &Editor::mapped_use_new_playlist), playlists), v, ARDOUR::Properties::edit.property_id);
4207         commit_reversible_command ();
4208 }
4209
4210 /**
4211  *  Use a copy of the current playlist for a given track and also any others that belong
4212  *  to the same active route group with the `edit' property.
4213  *  @param v Track.
4214  */
4215
4216 void
4217 Editor::copy_playlists (TimeAxisView* v)
4218 {
4219         begin_reversible_command (_("copy playlists"));
4220         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4221         _session->playlists->get (playlists);
4222         mapover_tracks (sigc::bind (sigc::mem_fun (*this, &Editor::mapped_use_copy_playlist), playlists), v, ARDOUR::Properties::edit.property_id);
4223         commit_reversible_command ();
4224 }
4225
4226 /** Clear the current playlist for a given track and also any others that belong
4227  *  to the same active route group with the `edit' property.
4228  *  @param v Track.
4229  */
4230
4231 void
4232 Editor::clear_playlists (TimeAxisView* v)
4233 {
4234         begin_reversible_command (_("clear playlists"));
4235         vector<boost::shared_ptr<ARDOUR::Playlist> > playlists;
4236         _session->playlists->get (playlists);
4237         mapover_tracks (sigc::mem_fun (*this, &Editor::mapped_clear_playlist), v, ARDOUR::Properties::edit.property_id);
4238         commit_reversible_command ();
4239 }
4240
4241 void
4242 Editor::mapped_use_new_playlist (RouteTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4243 {
4244         atv.use_new_playlist (sz > 1 ? false : true, playlists);
4245 }
4246
4247 void
4248 Editor::mapped_use_copy_playlist (RouteTimeAxisView& atv, uint32_t sz, vector<boost::shared_ptr<ARDOUR::Playlist> > const & playlists)
4249 {
4250         atv.use_copy_playlist (sz > 1 ? false : true, playlists);
4251 }
4252
4253 void
4254 Editor::mapped_clear_playlist (RouteTimeAxisView& atv, uint32_t /*sz*/)
4255 {
4256         atv.clear_playlist ();
4257 }
4258
4259 bool
4260 Editor::on_key_press_event (GdkEventKey* ev)
4261 {
4262         return key_press_focus_accelerator_handler (*this, ev);
4263 }
4264
4265 bool
4266 Editor::on_key_release_event (GdkEventKey* ev)
4267 {
4268         return Gtk::Window::on_key_release_event (ev);
4269         // return key_press_focus_accelerator_handler (*this, ev);
4270 }
4271
4272 /** Queue up a change to the viewport x origin.
4273  *  @param frame New x origin.
4274  */
4275 void
4276 Editor::reset_x_origin (nframes64_t frame)
4277 {
4278         queue_visual_change (frame);
4279 }
4280
4281 void
4282 Editor::reset_y_origin (double y)
4283 {
4284         queue_visual_change_y (y);
4285 }
4286
4287 void
4288 Editor::reset_zoom (double fpu)
4289 {
4290         queue_visual_change (fpu);
4291 }
4292
4293 void
4294 Editor::reposition_and_zoom (nframes64_t frame, double fpu)
4295 {
4296         reset_x_origin (frame);
4297         reset_zoom (fpu);
4298
4299         if (!no_save_visual) {
4300                 undo_visual_stack.push_back (current_visual_state(false));
4301         }
4302 }
4303
4304 Editor::VisualState*
4305 Editor::current_visual_state (bool with_tracks)
4306 {
4307         VisualState* vs = new VisualState;
4308         vs->y_position = vertical_adjustment.get_value();
4309         vs->frames_per_unit = frames_per_unit;
4310         vs->leftmost_frame = leftmost_frame;
4311         vs->zoom_focus = zoom_focus;
4312
4313         if (with_tracks) {
4314                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4315                         vs->track_states.push_back (TAVState ((*i), &(*i)->get_state()));
4316                 }
4317         }
4318
4319         return vs;
4320 }
4321
4322 void
4323 Editor::undo_visual_state ()
4324 {
4325         if (undo_visual_stack.empty()) {
4326                 return;
4327         }
4328
4329         redo_visual_stack.push_back (current_visual_state());
4330
4331         VisualState* vs = undo_visual_stack.back();
4332         undo_visual_stack.pop_back();
4333         use_visual_state (*vs);
4334 }
4335
4336 void
4337 Editor::redo_visual_state ()
4338 {
4339         if (redo_visual_stack.empty()) {
4340                 return;
4341         }
4342
4343         undo_visual_stack.push_back (current_visual_state());
4344
4345         VisualState* vs = redo_visual_stack.back();
4346         redo_visual_stack.pop_back();
4347         use_visual_state (*vs);
4348 }
4349
4350 void
4351 Editor::swap_visual_state ()
4352 {
4353         if (undo_visual_stack.empty()) {
4354                 redo_visual_state ();
4355         } else {
4356                 undo_visual_state ();
4357         }
4358 }
4359
4360 void
4361 Editor::use_visual_state (VisualState& vs)
4362 {
4363         no_save_visual = true;
4364
4365         _routes->suspend_redisplay ();
4366
4367         vertical_adjustment.set_value (vs.y_position);
4368
4369         set_zoom_focus (vs.zoom_focus);
4370         reposition_and_zoom (vs.leftmost_frame, vs.frames_per_unit);
4371
4372         for (list<TAVState>::iterator i = vs.track_states.begin(); i != vs.track_states.end(); ++i) {
4373                 TrackViewList::iterator t;
4374
4375                 /* check if the track still exists - it could have been deleted */
4376
4377                 if ((t = find (track_views.begin(), track_views.end(), i->first)) != track_views.end()) {
4378                         (*t)->set_state (*(i->second), Stateful::loading_state_version);
4379                 }
4380         }
4381
4382
4383         if (!vs.track_states.empty()) {
4384                 _routes->update_visibility ();
4385         }
4386
4387         _routes->resume_redisplay ();
4388
4389         no_save_visual = false;
4390 }
4391
4392 void
4393 Editor::set_frames_per_unit (double fpu)
4394 {
4395         /* this is the core function that controls the zoom level of the canvas. it is called
4396            whenever one or more calls are made to reset_zoom(). it executes in an idle handler.
4397         */
4398
4399         if (fpu == frames_per_unit) {
4400                 return;
4401         }
4402
4403         if (fpu < 2.0) {
4404                 fpu = 2.0;
4405         }
4406
4407
4408         /* don't allow zooms that fit more than the maximum number
4409            of frames into an 800 pixel wide space.
4410         */
4411
4412         if (max_frames / fpu < 800.0) {
4413                 return;
4414         }
4415
4416         if (tempo_lines)
4417                 tempo_lines->tempo_map_changed();
4418
4419         frames_per_unit = fpu;
4420         post_zoom ();
4421 }
4422
4423 void
4424 Editor::post_zoom ()
4425 {
4426         // convert fpu to frame count
4427
4428         nframes64_t frames = (nframes64_t) floor (frames_per_unit * _canvas_width);
4429
4430         if (frames_per_unit != zoom_range_clock.current_duration()) {
4431                 zoom_range_clock.set (frames);
4432         }
4433
4434         if (mouse_mode == MouseRange && selection->time.start () != selection->time.end_frame ()) {
4435                 for (TrackViewList::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4436                         (*i)->reshow_selection (selection->time);
4437                 }
4438         }
4439
4440         ZoomChanged (); /* EMIT_SIGNAL */
4441
4442         //reset_scrolling_region ();
4443
4444         if (playhead_cursor) {
4445                 playhead_cursor->set_position (playhead_cursor->current_frame);
4446         }
4447
4448         refresh_location_display();
4449         _summary->set_overlays_dirty ();
4450
4451         instant_save ();
4452 }
4453
4454 void
4455 Editor::queue_visual_change (nframes64_t where)
4456 {
4457         pending_visual_change.add (VisualChange::TimeOrigin);
4458         pending_visual_change.time_origin = where;
4459         ensure_visual_change_idle_handler ();
4460 }
4461
4462 void
4463 Editor::queue_visual_change (double fpu)
4464 {
4465         pending_visual_change.add (VisualChange::ZoomLevel);
4466         pending_visual_change.frames_per_unit = fpu;
4467
4468         ensure_visual_change_idle_handler ();
4469 }
4470
4471 void
4472 Editor::queue_visual_change_y (double y)
4473 {
4474         pending_visual_change.add (VisualChange::YOrigin);
4475         pending_visual_change.y_origin = y;
4476
4477         ensure_visual_change_idle_handler ();
4478 }
4479
4480 void
4481 Editor::ensure_visual_change_idle_handler ()
4482 {
4483         if (pending_visual_change.idle_handler_id < 0) {
4484                 pending_visual_change.idle_handler_id = g_idle_add (_idle_visual_changer, this);
4485         }
4486 }
4487
4488 int
4489 Editor::_idle_visual_changer (void* arg)
4490 {
4491         return static_cast<Editor*>(arg)->idle_visual_changer ();
4492 }
4493
4494 int
4495 Editor::idle_visual_changer ()
4496 {
4497         VisualChange::Type p = pending_visual_change.pending;
4498         pending_visual_change.pending = (VisualChange::Type) 0;
4499
4500         double last_time_origin = horizontal_position ();
4501
4502         if (p & VisualChange::ZoomLevel) {
4503                 set_frames_per_unit (pending_visual_change.frames_per_unit);
4504
4505                 compute_fixed_ruler_scale ();
4506                 compute_current_bbt_points(pending_visual_change.time_origin, pending_visual_change.time_origin + current_page_frames());
4507                 compute_bbt_ruler_scale (pending_visual_change.time_origin, pending_visual_change.time_origin + current_page_frames());
4508                 update_tempo_based_rulers ();
4509         }
4510         if (p & VisualChange::TimeOrigin) {
4511                 set_horizontal_position (pending_visual_change.time_origin / frames_per_unit);
4512         }
4513         if (p & VisualChange::YOrigin) {
4514                 vertical_adjustment.set_value (pending_visual_change.y_origin);
4515         }
4516
4517         if (last_time_origin == horizontal_position ()) {
4518                 /* changed signal not emitted */
4519                 update_fixed_rulers ();
4520                 redisplay_tempo (true);
4521         }
4522
4523         _summary->set_overlays_dirty ();
4524
4525         pending_visual_change.idle_handler_id = -1;
4526         return 0; /* this is always a one-shot call */
4527 }
4528
4529 struct EditorOrderTimeAxisSorter {
4530     bool operator() (const TimeAxisView* a, const TimeAxisView* b) const {
4531             return a->order () < b->order ();
4532     }
4533 };
4534
4535 void
4536 Editor::sort_track_selection (TrackViewList* sel)
4537 {
4538         EditorOrderTimeAxisSorter cmp;
4539
4540         if (sel) {
4541                 sel->sort (cmp);
4542         } else {
4543                 selection->tracks.sort (cmp);
4544         }
4545 }
4546
4547 nframes64_t
4548 Editor::get_preferred_edit_position (bool ignore_playhead)
4549 {
4550         bool ignored;
4551         nframes64_t where = 0;
4552         EditPoint ep = _edit_point;
4553
4554         if (entered_marker) {
4555                 return entered_marker->position();
4556         }
4557
4558         if (ignore_playhead && ep == EditAtPlayhead) {
4559                 ep = EditAtSelectedMarker;
4560         }
4561
4562         switch (ep) {
4563         case EditAtPlayhead:
4564                 where = _session->audible_frame();
4565                 break;
4566
4567         case EditAtSelectedMarker:
4568                 if (!selection->markers.empty()) {
4569                         bool is_start;
4570                         Location* loc = find_location_from_marker (selection->markers.front(), is_start);
4571                         if (loc) {
4572                                 if (is_start) {
4573                                         where =  loc->start();
4574                                 } else {
4575                                         where = loc->end();
4576                                 }
4577                                 break;
4578                         }
4579                 }
4580                 /* fallthru */
4581
4582         default:
4583         case EditAtMouse:
4584                 if (!mouse_frame (where, ignored)) {
4585                         /* XXX not right but what can we do ? */
4586                         return 0;
4587                 }
4588                 snap_to (where);
4589                 break;
4590         }
4591
4592         return where;
4593 }
4594
4595 void
4596 Editor::set_loop_range (nframes64_t start, nframes64_t end, string cmd)
4597 {
4598         if (!_session) return;
4599
4600         begin_reversible_command (cmd);
4601
4602         Location* tll;
4603
4604         if ((tll = transport_loop_location()) == 0) {
4605                 Location* loc = new Location (*_session, start, end, _("Loop"),  Location::IsAutoLoop);
4606                 XMLNode &before = _session->locations()->get_state();
4607                 _session->locations()->add (loc, true);
4608                 _session->set_auto_loop_location (loc);
4609                 XMLNode &after = _session->locations()->get_state();
4610                 _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
4611         } else {
4612                 XMLNode &before = tll->get_state();
4613                 tll->set_hidden (false, this);
4614                 tll->set (start, end);
4615                 XMLNode &after = tll->get_state();
4616                 _session->add_command (new MementoCommand<Location>(*tll, &before, &after));
4617         }
4618
4619         commit_reversible_command ();
4620 }
4621
4622 void
4623 Editor::set_punch_range (nframes64_t start, nframes64_t end, string cmd)
4624 {
4625         if (!_session) return;
4626
4627         begin_reversible_command (cmd);
4628
4629         Location* tpl;
4630
4631         if ((tpl = transport_punch_location()) == 0) {
4632                 Location* loc = new Location (*_session, start, end, _("Loop"),  Location::IsAutoPunch);
4633                 XMLNode &before = _session->locations()->get_state();
4634                 _session->locations()->add (loc, true);
4635                 _session->set_auto_loop_location (loc);
4636                 XMLNode &after = _session->locations()->get_state();
4637                 _session->add_command (new MementoCommand<Locations>(*(_session->locations()), &before, &after));
4638         }
4639         else {
4640                 XMLNode &before = tpl->get_state();
4641                 tpl->set_hidden (false, this);
4642                 tpl->set (start, end);
4643                 XMLNode &after = tpl->get_state();
4644                 _session->add_command (new MementoCommand<Location>(*tpl, &before, &after));
4645         }
4646
4647         commit_reversible_command ();
4648 }
4649
4650 /** Find regions which exist at a given time, and optionally on a given list of tracks.
4651  *  @param rs List to which found regions are added.
4652  *  @param where Time to look at.
4653  *  @param ts Tracks to look on; if this is empty, all tracks are examined.
4654  */
4655 void
4656 Editor::get_regions_at (RegionSelection& rs, nframes64_t where, const TrackViewList& ts) const
4657 {
4658         const TrackViewList* tracks;
4659
4660         if (ts.empty()) {
4661                 tracks = &track_views;
4662         } else {
4663                 tracks = &ts;
4664         }
4665
4666         for (TrackViewList::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
4667                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*t);
4668                 if (rtv) {
4669                         boost::shared_ptr<Track> tr;
4670                         boost::shared_ptr<Playlist> pl;
4671
4672                         if ((tr = rtv->track()) && ((pl = tr->playlist()))) {
4673
4674                                 Playlist::RegionList* regions = pl->regions_at (
4675                                                 (nframes64_t) floor ( (double)where * tr->speed()));
4676
4677                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
4678                                         RegionView* rv = rtv->view()->find_view (*i);
4679                                         if (rv) {
4680                                                 rs.add (rv);
4681                                         }
4682                                 }
4683
4684                                 delete regions;
4685                         }
4686                 }
4687         }
4688 }
4689
4690 void
4691 Editor::get_regions_after (RegionSelection& rs, nframes64_t where, const TrackViewList& ts) const
4692 {
4693         const TrackViewList* tracks;
4694
4695         if (ts.empty()) {
4696                 tracks = &track_views;
4697         } else {
4698                 tracks = &ts;
4699         }
4700
4701         for (TrackViewList::const_iterator t = tracks->begin(); t != tracks->end(); ++t) {
4702                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(*t);
4703                 if (rtv) {
4704                         boost::shared_ptr<Track> tr;
4705                         boost::shared_ptr<Playlist> pl;
4706
4707                         if ((tr = rtv->track()) && ((pl = tr->playlist()))) {
4708
4709                                 Playlist::RegionList* regions = pl->regions_touched (
4710                                                 (nframes64_t) floor ( (double)where * tr->speed()), max_frames);
4711
4712                                 for (Playlist::RegionList::iterator i = regions->begin(); i != regions->end(); ++i) {
4713
4714                                         RegionView* rv = rtv->view()->find_view (*i);
4715
4716                                         if (rv) {
4717                                                 rs.push_back (rv);
4718                                         }
4719                                 }
4720
4721                                 delete regions;
4722                         }
4723                 }
4724         }
4725 }
4726
4727 /** Find all regions which are either:
4728  *      - selected or
4729  *      - the entered_regionview (if allow_entered == true) or
4730  *      - under the preferred edit position AND on a selected track, or on a track
4731  *        which is in the same active edit-enable route group as a selected region (if allow_edit_position == true)
4732  *  @param rs Returned region list.
4733  *  @param allow_entered true to include the entered_regionview in the list.
4734  */
4735 void
4736 Editor::get_regions_for_action (RegionSelection& rs, bool allow_entered, bool allow_edit_position)
4737 {
4738         /* Start with selected regions */
4739         rs = selection->regions;
4740
4741         /* Add the entered_regionview, if requested */
4742         if (allow_entered && entered_regionview) {
4743                 rs.add (entered_regionview);
4744         }
4745
4746         if (allow_edit_position) {
4747
4748                 TrackViewList tracks = selection->tracks;
4749
4750                 /* tracks is currently the set of selected tracks; add any other tracks that
4751                  * have regions that are in the same edit-activated route group as one of
4752                  * our regions */
4753                 for (RegionSelection::iterator i = rs.begin (); i != rs.end(); ++i) {
4754
4755                         RouteGroup* g = (*i)->get_time_axis_view().route_group ();
4756                         if (g && g->is_active() && g->is_edit()) {
4757                                 tracks.add (axis_views_from_routes (g->route_list()));
4758                         }
4759                         
4760                 }
4761
4762                 if (!tracks.empty()) {
4763                         /* now find regions that are at the edit position on those tracks */
4764                         nframes64_t const where = get_preferred_edit_position ();
4765                         get_regions_at (rs, where, tracks);
4766                 }
4767         }
4768 }
4769
4770 void
4771 Editor::get_regions_corresponding_to (boost::shared_ptr<Region> region, vector<RegionView*>& regions)
4772 {
4773         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
4774
4775                 RouteTimeAxisView* tatv;
4776
4777                 if ((tatv = dynamic_cast<RouteTimeAxisView*> (*i)) != 0) {
4778
4779                         boost::shared_ptr<Playlist> pl;
4780                         vector<boost::shared_ptr<Region> > results;
4781                         RegionView* marv;
4782                         boost::shared_ptr<Track> tr;
4783
4784                         if ((tr = tatv->track()) == 0) {
4785                                 /* bus */
4786                                 continue;
4787                         }
4788
4789                         if ((pl = (tr->playlist())) != 0) {
4790                                 pl->get_region_list_equivalent_regions (region, results);
4791                         }
4792
4793                         for (vector<boost::shared_ptr<Region> >::iterator ir = results.begin(); ir != results.end(); ++ir) {
4794                                 if ((marv = tatv->view()->find_view (*ir)) != 0) {
4795                                         regions.push_back (marv);
4796                                 }
4797                         }
4798
4799                 }
4800         }
4801 }
4802
4803 void
4804 Editor::show_rhythm_ferret ()
4805 {
4806         if (rhythm_ferret == 0) {
4807                 rhythm_ferret = new RhythmFerret(*this);
4808         }
4809
4810         rhythm_ferret->set_session (_session);
4811         rhythm_ferret->show ();
4812         rhythm_ferret->present ();
4813 }
4814
4815 void
4816 Editor::show_global_port_matrix (ARDOUR::DataType t)
4817 {
4818         if (_global_port_matrix[t] == 0) {
4819                 _global_port_matrix[t] = new GlobalPortMatrixWindow (_session, t);
4820         }
4821
4822         _global_port_matrix[t]->show ();
4823 }
4824
4825 void
4826 Editor::first_idle ()
4827 {
4828         MessageDialog* dialog = 0;
4829
4830         if (track_views.size() > 1) {
4831                 dialog = new MessageDialog (*this,
4832                                             string_compose (_("Please wait while %1 loads visual data"), PROGRAM_NAME),
4833                                             true,
4834                                             Gtk::MESSAGE_INFO,
4835                                             Gtk::BUTTONS_NONE);
4836                 dialog->present ();
4837                 ARDOUR_UI::instance()->flush_pending ();
4838         }
4839
4840         for (TrackViewList::iterator t = track_views.begin(); t != track_views.end(); ++t) {
4841                 (*t)->first_idle();
4842         }
4843
4844         // first idle adds route children (automation tracks), so we need to redisplay here
4845         _routes->redisplay ();
4846
4847         delete dialog;
4848
4849         _have_idled = true;
4850 }
4851
4852 gboolean
4853 Editor::_idle_resize (gpointer arg)
4854 {
4855         return ((Editor*)arg)->idle_resize ();
4856 }
4857
4858 void
4859 Editor::add_to_idle_resize (TimeAxisView* view, int32_t h)
4860 {
4861         if (resize_idle_id < 0) {
4862                 resize_idle_id = g_idle_add (_idle_resize, this);
4863                 _pending_resize_amount = 0;
4864         }
4865
4866         /* make a note of the smallest resulting height, so that we can clamp the
4867            lower limit at TimeAxisView::hSmall */
4868
4869         int32_t min_resulting = INT32_MAX;
4870
4871         _pending_resize_amount += h;
4872         _pending_resize_view = view;
4873
4874         min_resulting = min (min_resulting, int32_t (_pending_resize_view->current_height()) + _pending_resize_amount);
4875
4876         if (selection->tracks.contains (_pending_resize_view)) {
4877                 for (TrackViewList::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4878                         min_resulting = min (min_resulting, int32_t ((*i)->current_height()) + _pending_resize_amount);
4879                 }
4880         }
4881
4882         if (min_resulting < 0) {
4883                 min_resulting = 0;
4884         }
4885
4886         /* clamp */
4887         if (uint32_t (min_resulting) < TimeAxisView::preset_height (HeightSmall)) {
4888                 _pending_resize_amount += TimeAxisView::preset_height (HeightSmall) - min_resulting;
4889         }
4890 }
4891
4892 /** Handle pending resizing of tracks */
4893 bool
4894 Editor::idle_resize ()
4895 {
4896         _pending_resize_view->idle_resize (_pending_resize_view->current_height() + _pending_resize_amount);
4897
4898         if (dynamic_cast<AutomationTimeAxisView*> (_pending_resize_view) == 0 &&
4899             selection->tracks.contains (_pending_resize_view)) {
4900
4901                 for (TrackViewList::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
4902                         if (*i != _pending_resize_view) {
4903                                 (*i)->idle_resize ((*i)->current_height() + _pending_resize_amount);
4904                         }
4905                 }
4906         }
4907
4908         _pending_resize_amount = 0;
4909         flush_canvas ();
4910         _group_tabs->set_dirty ();
4911         resize_idle_id = -1;
4912
4913         return false;
4914 }
4915
4916 void
4917 Editor::located ()
4918 {
4919         ENSURE_GUI_THREAD (*this, &Editor::located);
4920
4921         playhead_cursor->set_position (_session->audible_frame ());
4922         if (_follow_playhead && !_pending_initial_locate) {
4923                 reset_x_origin_to_follow_playhead ();
4924         }
4925
4926         _pending_locate_request = false;
4927         _pending_initial_locate = false;
4928 }
4929
4930 void
4931 Editor::region_view_added (RegionView *)
4932 {
4933         _summary->set_dirty ();
4934 }
4935
4936 TimeAxisView*
4937 Editor::axis_view_from_route (boost::shared_ptr<Route> r) const
4938 {
4939         TrackViewList::const_iterator j = track_views.begin ();
4940         while (j != track_views.end()) {
4941                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (*j);
4942                 if (rtv && rtv->route() == r) {
4943                         return rtv;
4944                 }
4945                 ++j;
4946         }
4947
4948         return 0;
4949 }
4950
4951
4952 TrackViewList
4953 Editor::axis_views_from_routes (boost::shared_ptr<RouteList> r) const
4954 {
4955         TrackViewList t;
4956
4957         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4958                 TimeAxisView* tv = axis_view_from_route (*i);
4959                 if (tv) {
4960                         t.push_back (tv);
4961                 }
4962         }
4963
4964         return t;
4965 }
4966
4967
4968 void
4969 Editor::handle_new_route (RouteList& routes)
4970 {
4971         ENSURE_GUI_THREAD (*this, &Editor::handle_new_route, routes)
4972
4973         RouteTimeAxisView *rtv;
4974         list<RouteTimeAxisView*> new_views;
4975
4976         for (RouteList::iterator x = routes.begin(); x != routes.end(); ++x) {
4977                 boost::shared_ptr<Route> route = (*x);
4978
4979                 if (route->is_hidden() || route->is_monitor()) {
4980                         continue;
4981                 }
4982
4983                 DataType dt = route->input()->default_type();
4984
4985                 if (dt == ARDOUR::DataType::AUDIO) {
4986                         rtv = new AudioTimeAxisView (*this, _session, route, *track_canvas);
4987                 } else if (dt == ARDOUR::DataType::MIDI) {
4988                         rtv = new MidiTimeAxisView (*this, _session, route, *track_canvas);
4989                 } else {
4990                         throw unknown_type();
4991                 }
4992
4993                 new_views.push_back (rtv);
4994                 track_views.push_back (rtv);
4995
4996                 rtv->effective_gain_display ();
4997
4998                 rtv->view()->RegionViewAdded.connect (sigc::mem_fun (*this, &Editor::region_view_added));
4999         }
5000
5001         _routes->routes_added (new_views);
5002
5003         if (show_editor_mixer_when_tracks_arrive) {
5004                 show_editor_mixer (true);
5005         }
5006
5007         editor_list_button.set_sensitive (true);
5008
5009         _summary->set_dirty ();
5010 }
5011
5012 void
5013 Editor::timeaxisview_deleted (TimeAxisView *tv)
5014 {
5015         if (_session && _session->deletion_in_progress()) {
5016                 /* the situation is under control */
5017                 return;
5018         }
5019
5020         ENSURE_GUI_THREAD (*this, &Editor::timeaxisview_deleted, tv);
5021
5022         RouteTimeAxisView* rtav = dynamic_cast<RouteTimeAxisView*> (tv);
5023         
5024         _routes->route_removed (tv);
5025
5026         if (tv == entered_track) {
5027                 entered_track = 0;
5028         }
5029
5030         if (rtav) {
5031                 TimeAxisView::Children c = rtav->get_child_list ();
5032                 for (TimeAxisView::Children::const_iterator i = c.begin(); i != c.end(); ++i) {
5033                         if (entered_track == i->get()) {
5034                                 entered_track = 0;
5035                         }
5036                 }
5037         }
5038
5039         /* remove it from the list of track views */
5040
5041         TrackViewList::iterator i;
5042
5043         if ((i = find (track_views.begin(), track_views.end(), tv)) != track_views.end()) {
5044                 i = track_views.erase (i);
5045         }
5046
5047         /* update whatever the current mixer strip is displaying, if revelant */
5048
5049         boost::shared_ptr<Route> route;
5050
5051         if (rtav) {
5052                 route = rtav->route ();
5053         } 
5054
5055         if (current_mixer_strip && current_mixer_strip->route() == route) {
5056
5057                 TimeAxisView* next_tv;
5058
5059                 if (track_views.empty()) {
5060                         next_tv = 0;
5061                 } else if (i == track_views.end()) {
5062                         next_tv = track_views.front();
5063                 } else {
5064                         next_tv = (*i);
5065                 }
5066                 
5067                 
5068                 if (next_tv) {
5069                         set_selected_mixer_strip (*next_tv);
5070                 } else {
5071                         /* make the editor mixer strip go away setting the
5072                          * button to inactive (which also unticks the menu option)
5073                          */
5074                         
5075                         ActionManager::uncheck_toggleaction ("<Actions>/Editor/show-editor-mixer");
5076                 }
5077         } 
5078 }
5079
5080 void
5081 Editor::hide_track_in_display (TimeAxisView* tv, bool /*temponly*/)
5082 {
5083         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (tv);
5084
5085         if (rtv && current_mixer_strip && (rtv->route() == current_mixer_strip->route())) {
5086                 // this will hide the mixer strip
5087                 set_selected_mixer_strip (*tv);
5088         }
5089
5090         _routes->hide_track_in_display (*tv);
5091 }
5092
5093 bool
5094 Editor::sync_track_view_list_and_routes ()
5095 {
5096         track_views = TrackViewList (_routes->views ());
5097
5098         _summary->set_dirty ();
5099         _group_tabs->set_dirty ();
5100
5101         return false; // do not call again (until needed)
5102 }
5103
5104 void
5105 Editor::foreach_time_axis_view (sigc::slot<void,TimeAxisView&> theslot)
5106 {
5107         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5108                 theslot (**i);
5109         }
5110 }
5111
5112 RouteTimeAxisView*
5113 Editor::get_route_view_by_id (PBD::ID& id)
5114 {
5115         RouteTimeAxisView* v;
5116
5117         for(TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5118                 if((v = dynamic_cast<RouteTimeAxisView*>(*i)) != 0) {
5119                         if(v->route()->id() == id) {
5120                                 return v;
5121                         }
5122                 }
5123         }
5124
5125         return 0;
5126 }
5127
5128 void
5129 Editor::fit_route_group (RouteGroup *g)
5130 {
5131         TrackViewList ts = axis_views_from_routes (g->route_list ());
5132         fit_tracks (ts);
5133 }
5134
5135 void
5136 Editor::consider_auditioning (boost::shared_ptr<Region> region)
5137 {
5138         boost::shared_ptr<AudioRegion> r = boost::dynamic_pointer_cast<AudioRegion> (region);
5139
5140         if (r == 0) {
5141                 _session->cancel_audition ();
5142                 return;
5143         }
5144
5145         if (_session->is_auditioning()) {
5146                 _session->cancel_audition ();
5147                 if (r == last_audition_region) {
5148                         return;
5149                 }
5150         }
5151
5152         _session->audition_region (r);
5153         last_audition_region = r;
5154 }
5155
5156
5157 void
5158 Editor::hide_a_region (boost::shared_ptr<Region> r)
5159 {
5160         r->set_hidden (true);
5161 }
5162
5163 void
5164 Editor::show_a_region (boost::shared_ptr<Region> r)
5165 {
5166         r->set_hidden (false);
5167 }
5168
5169 void
5170 Editor::audition_region_from_region_list ()
5171 {
5172         _regions->selection_mapover (sigc::mem_fun (*this, &Editor::consider_auditioning));
5173 }
5174
5175 void
5176 Editor::hide_region_from_region_list ()
5177 {
5178         _regions->selection_mapover (sigc::mem_fun (*this, &Editor::hide_a_region));
5179 }
5180
5181 void
5182 Editor::show_region_in_region_list ()
5183 {
5184         _regions->selection_mapover (sigc::mem_fun (*this, &Editor::show_a_region));
5185 }
5186
5187 void
5188 Editor::step_edit_status_change (bool yn)
5189 {
5190         if (yn) {
5191                 start_step_editing ();
5192         } else {
5193                 stop_step_editing ();
5194         }
5195 }
5196
5197 void
5198 Editor::start_step_editing ()
5199 {
5200         step_edit_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &Editor::check_step_edit), 20);
5201 }
5202
5203 void
5204 Editor::stop_step_editing ()
5205 {
5206         step_edit_connection.disconnect ();
5207 }
5208
5209 bool
5210 Editor::check_step_edit ()
5211 {
5212         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5213                 MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*> (*i);
5214                 if (mtv) {
5215                         mtv->check_step_edit ();
5216                 }
5217         }
5218
5219         return true; // do it again, till we stop
5220 }
5221
5222 bool
5223 Editor::horizontal_scroll_left_press ()
5224 {
5225         ++_scroll_callbacks;
5226         
5227         if (_scroll_connection.connected() && _scroll_callbacks < 5) {
5228                 /* delay the first auto-repeat */
5229                 return true;
5230         }
5231                 
5232         double x = leftmost_position() - current_page_frames() / 5;
5233         if (x < 0) {
5234                 x = 0;
5235         }
5236         
5237         reset_x_origin (x);
5238
5239         /* do hacky auto-repeat */
5240         if (!_scroll_connection.connected ()) {
5241                 _scroll_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_left_press), 100);
5242                 _scroll_callbacks = 0;
5243         }
5244
5245         return true;
5246 }
5247
5248 void
5249 Editor::horizontal_scroll_left_release ()
5250 {
5251         _scroll_connection.disconnect ();
5252 }
5253
5254 bool
5255 Editor::horizontal_scroll_right_press ()
5256 {
5257         ++_scroll_callbacks;
5258         
5259         if (_scroll_connection.connected() && _scroll_callbacks < 5) {
5260                 /* delay the first auto-repeat */
5261                 return true;
5262         }
5263
5264         reset_x_origin (leftmost_position() + current_page_frames() / 5);
5265
5266         /* do hacky auto-repeat */
5267         if (!_scroll_connection.connected ()) {
5268                 _scroll_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &Editor::horizontal_scroll_right_press), 100);
5269                 _scroll_callbacks = 0;
5270         }
5271
5272         return true;
5273 }
5274
5275 void
5276 Editor::horizontal_scroll_right_release ()
5277 {
5278         _scroll_connection.disconnect ();
5279 }
5280
5281 /** Queue a change for the Editor viewport x origin to follow the playhead */
5282 void
5283 Editor::reset_x_origin_to_follow_playhead ()
5284 {
5285         nframes64_t const frame = playhead_cursor->current_frame;
5286
5287         if (frame < leftmost_frame || frame > leftmost_frame + current_page_frames()) {
5288
5289                 if (_session->transport_speed() < 0) {
5290                         
5291                         if (frame > (current_page_frames() / 2)) {
5292                                 center_screen (frame-(current_page_frames()/2));
5293                         } else {
5294                                 center_screen (current_page_frames()/2);
5295                         }
5296                         
5297                 } else {
5298                                                 
5299                         if (frame < leftmost_frame) {
5300                                 /* moving left */
5301                                 nframes64_t l = 0;
5302                                 if (_session->transport_rolling()) {
5303                                         /* rolling; end up with the playhead at the right of the page */
5304                                         l = frame - current_page_frames ();
5305                                 } else {
5306                                         /* not rolling: end up with the playhead 3/4 of the way along the page */
5307                                         l = frame - (3 * current_page_frames() / 4);
5308                                 }
5309                                 
5310                                 if (l < 0) {
5311                                         l = 0;
5312                                 }
5313                                 
5314                                 center_screen_internal (l + (current_page_frames() / 2), current_page_frames ());
5315                         } else {
5316                                 /* moving right */
5317                                 if (_session->transport_rolling()) {
5318                                         /* rolling: end up with the playhead on the left of the page */
5319                                         center_screen_internal (frame + (current_page_frames() / 2), current_page_frames ());
5320                                 } else {
5321                                         /* not rolling: end up with the playhead 1/4 of the way along the page */
5322                                         center_screen_internal (frame + (current_page_frames() / 4), current_page_frames ());
5323                                 }
5324                         }
5325                 }
5326         }
5327 }
5328
5329 void
5330 Editor::super_rapid_screen_update ()
5331 {
5332         if (!_session || !_session->engine().running()) {
5333                 return;
5334         }
5335
5336         /* METERING / MIXER STRIPS */
5337
5338         /* update track meters, if required */
5339         if (is_mapped() && meters_running) {
5340                 RouteTimeAxisView* rtv;
5341                 for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5342                         if ((rtv = dynamic_cast<RouteTimeAxisView*>(*i)) != 0) {
5343                                 rtv->fast_update ();
5344                         }
5345                 }
5346         }
5347
5348         /* and any current mixer strip */
5349         if (current_mixer_strip) {
5350                 current_mixer_strip->fast_update ();
5351         }
5352
5353         /* PLAYHEAD AND VIEWPORT */
5354
5355         nframes64_t const frame = _session->audible_frame();
5356
5357         /* There are a few reasons why we might not update the playhead / viewport stuff:
5358          *
5359          * 1.  we don't update things when there's a pending locate request, otherwise
5360          *     when the editor requests a locate there is a chance that this method
5361          *     will move the playhead before the locate request is processed, causing
5362          *     a visual glitch.
5363          * 2.  if we're not rolling, there's nothing to do here (locates are handled elsewhere).
5364          * 3.  if we're still at the same frame that we were last time, there's nothing to do.
5365          */
5366
5367         if (!_pending_locate_request && _session->transport_speed() != 0 && frame != last_update_frame) {
5368
5369                 last_update_frame = frame;
5370
5371                 if (!_dragging_playhead) {
5372                         playhead_cursor->set_position (frame);
5373                 }
5374
5375                 if (!_stationary_playhead) {
5376
5377                         if (!_dragging_playhead && _follow_playhead && _session->requested_return_frame() < 0) {
5378                                 reset_x_origin_to_follow_playhead ();
5379                         }
5380
5381                 } else {
5382                         
5383                         /* don't do continuous scroll till the new position is in the rightmost quarter of the
5384                            editor canvas
5385                         */
5386 #if 0                        
5387                         // FIXME DO SOMETHING THAT WORKS HERE - this is 2.X code                         
5388                         double target = ((double)frame - (double)current_page_frames()/2.0) / frames_per_unit;
5389                         if (target <= 0.0) {
5390                                 target = 0.0;
5391                         }
5392                         if (fabs(target - current) < current_page_frames() / frames_per_unit) {
5393                                 target = (target * 0.15) + (current * 0.85);
5394                         } else {
5395                                 /* relax */
5396                         }
5397                         
5398                         current = target;
5399                         set_horizontal_position (current);
5400 #endif
5401                 }
5402                 
5403         }
5404 }
5405
5406
5407 void
5408 Editor::session_going_away ()
5409 {
5410         _have_idled = false;
5411
5412         _session_connections.drop_connections ();
5413
5414         super_rapid_screen_update_connection.disconnect ();
5415         
5416         selection->clear ();
5417         cut_buffer->clear ();
5418
5419         clicked_regionview = 0;
5420         clicked_axisview = 0;
5421         clicked_routeview = 0;
5422         clicked_crossfadeview = 0;
5423         entered_regionview = 0;
5424         entered_track = 0;
5425         last_update_frame = 0;
5426         _drags->abort ();
5427
5428         playhead_cursor->canvas_item.hide ();
5429
5430         /* rip everything out of the list displays */
5431
5432         _regions->clear ();
5433         _routes->clear ();
5434         _route_groups->clear ();
5435
5436         /* do this first so that deleting a track doesn't reset cms to null
5437            and thus cause a leak.
5438         */
5439
5440         if (current_mixer_strip) {
5441                 if (current_mixer_strip->get_parent() != 0) {
5442                         global_hpacker.remove (*current_mixer_strip);
5443                 }
5444                 delete current_mixer_strip;
5445                 current_mixer_strip = 0;
5446         }
5447
5448         /* delete all trackviews */
5449
5450         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
5451                 delete *i;
5452         }
5453         track_views.clear ();
5454
5455         zoom_range_clock.set_session (0);
5456         nudge_clock.set_session (0);
5457
5458         editor_list_button.set_active(false);
5459         editor_list_button.set_sensitive(false);
5460
5461         /* clear tempo/meter rulers */
5462         remove_metric_marks ();
5463         hide_measures ();
5464         clear_marker_display ();
5465
5466         delete current_bbt_points;
5467         current_bbt_points = 0;
5468
5469         /* get rid of any existing editor mixer strip */
5470
5471         WindowTitle title(Glib::get_application_name());
5472         title += _("Editor");
5473
5474         set_title (title.get_string());
5475
5476         SessionHandlePtr::session_going_away ();
5477 }
5478
5479
5480 void
5481 Editor::show_editor_list (bool yn)
5482 {
5483         if (yn) {
5484                 the_notebook.show();
5485         } else {
5486                 the_notebook.hide();
5487         }
5488 }
5489