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