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