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