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