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