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