keep velocity value visible in verbose cursor until we leave a note (fixes #5085)
[ardour.git] / gtk2_ardour / ardour_ui.cc
1 /*
2     Copyright (C) 1999-2007 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 #ifdef WAF_BUILD
21 #include "gtk2ardour-config.h"
22 #endif
23
24 #include <stdint.h>
25
26 #include <algorithm>
27 #include <cmath>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <unistd.h>
31 #include <time.h>
32 #include <cerrno>
33 #include <fstream>
34
35 #include <iostream>
36
37 #include <sys/resource.h>
38
39 #include <gtkmm/messagedialog.h>
40 #include <gtkmm/accelmap.h>
41
42 #include "pbd/error.h"
43 #include "pbd/basename.h"
44 #include "pbd/compose.h"
45 #include "pbd/failed_constructor.h"
46 #include "pbd/enumwriter.h"
47 #include "pbd/memento_command.h"
48 #include "pbd/openuri.h"
49 #include "pbd/file_utils.h"
50
51 #include "gtkmm2ext/application.h"
52 #include "gtkmm2ext/bindings.h"
53 #include "gtkmm2ext/gtk_ui.h"
54 #include "gtkmm2ext/utils.h"
55 #include "gtkmm2ext/click_box.h"
56 #include "gtkmm2ext/fastmeter.h"
57 #include "gtkmm2ext/popup.h"
58 #include "gtkmm2ext/window_title.h"
59
60 #include "midi++/manager.h"
61
62 #include "ardour/ardour.h"
63 #include "ardour/audioengine.h"
64 #include "ardour/audiofilesource.h"
65 #include "ardour/automation_watch.h"
66 #include "ardour/diskstream.h"
67 #include "ardour/filename_extensions.h"
68 #include "ardour/port.h"
69 #include "ardour/process_thread.h"
70 #include "ardour/profile.h"
71 #include "ardour/recent_sessions.h"
72 #include "ardour/session_directory.h"
73 #include "ardour/session_route.h"
74 #include "ardour/session_state_utils.h"
75 #include "ardour/session_utils.h"
76 #include "ardour/slave.h"
77
78 #include "timecode/time.h"
79
80 typedef uint64_t microseconds_t;
81
82 #include "about.h"
83 #include "actions.h"
84 #include "add_route_dialog.h"
85 #include "ambiguous_file_dialog.h"
86 #include "ardour_ui.h"
87 #include "audio_clock.h"
88 #include "bundle_manager.h"
89 #include "engine_dialog.h"
90 #include "gain_meter.h"
91 #include "global_port_matrix.h"
92 #include "gui_object.h"
93 #include "gui_thread.h"
94 #include "keyboard.h"
95 #include "location_ui.h"
96 #include "main_clock.h"
97 #include "missing_file_dialog.h"
98 #include "missing_plugin_dialog.h"
99 #include "mixer_ui.h"
100 #include "mouse_cursors.h"
101 #include "opts.h"
102 #include "processor_box.h"
103 #include "prompter.h"
104 #include "public_editor.h"
105 #include "route_time_axis.h"
106 #include "session_metadata_dialog.h"
107 #include "shuttle_control.h"
108 #include "speaker_dialog.h"
109 #include "splash.h"
110 #include "startup.h"
111 #include "theme_manager.h"
112 #include "time_axis_view_item.h"
113 #include "utils.h"
114 #include "window_proxy.h"
115
116 #include "i18n.h"
117
118 using namespace ARDOUR;
119 using namespace PBD;
120 using namespace Gtkmm2ext;
121 using namespace Gtk;
122 using namespace std;
123
124 ARDOUR_UI *ARDOUR_UI::theArdourUI = 0;
125 UIConfiguration *ARDOUR_UI::ui_config = 0;
126
127 sigc::signal<void,bool> ARDOUR_UI::Blink;
128 sigc::signal<void>      ARDOUR_UI::RapidScreenUpdate;
129 sigc::signal<void>      ARDOUR_UI::SuperRapidScreenUpdate;
130 sigc::signal<void, framepos_t, bool, framepos_t> ARDOUR_UI::Clock;
131
132 ARDOUR_UI::ARDOUR_UI (int *argcp, char **argvp[])
133
134         : Gtkmm2ext::UI (PROGRAM_NAME, argcp, argvp)
135
136         , gui_object_state (new GUIObjectState)
137         , primary_clock (new MainClock (X_("primary"), false, X_("transport"), true, true, true, false, true))
138         , secondary_clock (new MainClock (X_("secondary"), false, X_("secondary"), true, true, false, false, true))
139
140           /* big clock */
141
142         , big_clock (new AudioClock (X_("bigclock"), false, "big", true, true, false, false))
143
144           /* transport */
145
146         , roll_controllable (new TransportControllable ("transport roll", *this, TransportControllable::Roll))
147         , stop_controllable (new TransportControllable ("transport stop", *this, TransportControllable::Stop))
148         , goto_start_controllable (new TransportControllable ("transport goto start", *this, TransportControllable::GotoStart))
149         , goto_end_controllable (new TransportControllable ("transport goto end", *this, TransportControllable::GotoEnd))
150         , auto_loop_controllable (new TransportControllable ("transport auto loop", *this, TransportControllable::AutoLoop))
151         , play_selection_controllable (new TransportControllable ("transport play selection", *this, TransportControllable::PlaySelection))
152         , rec_controllable (new TransportControllable ("transport rec-enable", *this, TransportControllable::RecordEnable))
153
154         , auto_return_button (ArdourButton::led_default_elements)
155         , follow_edits_button (ArdourButton::led_default_elements)
156         , auto_input_button (ArdourButton::led_default_elements)
157
158         , auditioning_alert_button (_("audition"))
159         , solo_alert_button (_("solo"))
160         , feedback_alert_button (_("feedback"))
161
162         , error_log_button (_("Errors"))
163
164         , _status_bar_visibility (X_("status-bar"))
165         , _feedback_exists (false)
166
167 {
168         Gtkmm2ext::init();
169
170         about = 0;
171         splash = 0;
172         _startup = 0;
173
174         if (theArdourUI == 0) {
175                 theArdourUI = this;
176         }
177
178         ui_config = new UIConfiguration();
179         theme_manager = new ThemeManager();
180
181         key_editor = 0;
182
183         editor = 0;
184         mixer = 0;
185         editor = 0;
186         engine = 0;
187         _session_is_new = false;
188         big_clock_window = 0;
189         big_clock_height = 0;
190         big_clock_resize_in_progress = false;
191         session_selector_window = 0;
192         last_key_press_time = 0;
193         add_route_dialog = 0;
194         route_params = 0;
195         bundle_manager = 0;
196         rc_option_editor = 0;
197         session_option_editor = 0;
198         location_ui = 0;
199         open_session_selector = 0;
200         have_configure_timeout = false;
201         have_disk_speed_dialog_displayed = false;
202         session_loaded = false;
203         ignore_dual_punch = false;
204         original_big_clock_width = -1;
205         original_big_clock_height = -1;
206         original_big_clock_font_size = 0;
207
208         roll_button.set_controllable (roll_controllable);
209         stop_button.set_controllable (stop_controllable);
210         goto_start_button.set_controllable (goto_start_controllable);
211         goto_end_button.set_controllable (goto_end_controllable);
212         auto_loop_button.set_controllable (auto_loop_controllable);
213         play_selection_button.set_controllable (play_selection_controllable);
214         rec_button.set_controllable (rec_controllable);
215
216         roll_button.set_name ("transport button");
217         stop_button.set_name ("transport button");
218         goto_start_button.set_name ("transport button");
219         goto_end_button.set_name ("transport button");
220         auto_loop_button.set_name ("transport button");
221         play_selection_button.set_name ("transport button");
222         rec_button.set_name ("transport recenable button");
223         midi_panic_button.set_name ("transport button");
224
225         goto_start_button.set_tweaks (ArdourButton::ShowClick);
226         goto_end_button.set_tweaks (ArdourButton::ShowClick);
227         midi_panic_button.set_tweaks (ArdourButton::ShowClick);
228         
229         last_configure_time= 0;
230         last_peak_grab = 0;
231
232         ARDOUR::Diskstream::DiskOverrun.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::disk_overrun_handler, this), gui_context());
233         ARDOUR::Diskstream::DiskUnderrun.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::disk_underrun_handler, this), gui_context());
234
235         /* handle dialog requests */
236
237         ARDOUR::Session::Dialog.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::session_dialog, this, _1), gui_context());
238
239         /* handle pending state with a dialog (PROBLEM: needs to return a value and thus cannot be x-thread) */
240
241         ARDOUR::Session::AskAboutPendingState.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::pending_state_dialog, this));
242
243         /* handle sr mismatch with a dialog (PROBLEM: needs to return a value and thus cannot be x-thread) */
244
245         ARDOUR::Session::AskAboutSampleRateMismatch.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::sr_mismatch_dialog, this, _1, _2));
246
247         /* handle requests to quit (coming from JACK session) */
248
249         ARDOUR::Session::Quit.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::finish, this), gui_context ());
250
251         /* tell the user about feedback */
252
253         ARDOUR::Session::FeedbackDetected.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::feedback_detected, this), gui_context ());
254         ARDOUR::Session::SuccessfulGraphSort.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::successful_graph_sort, this), gui_context ());
255
256         /* handle requests to deal with missing files */
257
258         ARDOUR::Session::MissingFile.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::missing_file, this, _1, _2, _3));
259
260         /* and ambiguous files */
261
262         ARDOUR::FileSource::AmbiguousFileName.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::ambiguous_file, this, _1, _2, _3));
263
264         /* lets get this party started */
265
266         try {
267                 if (ARDOUR::init (ARDOUR_COMMAND_LINE::use_vst, ARDOUR_COMMAND_LINE::try_hw_optimization)) {
268                         throw failed_constructor ();
269                 }
270
271                 setup_gtk_ardour_enums ();
272                 setup_profile ();
273
274                 GainMeter::setup_slider_pix ();
275                 RouteTimeAxisView::setup_slider_pix ();
276                 ProcessorEntry::setup_slider_pix ();
277                 SessionEvent::create_per_thread_pool ("GUI", 512);
278
279         } catch (failed_constructor& err) {
280                 error << string_compose (_("could not initialize %1."), PROGRAM_NAME) << endmsg;
281                 // pass it on up
282                 throw;
283         }
284
285         /* we like keyboards */
286
287         keyboard = new ArdourKeyboard(*this);
288
289         XMLNode* node = ARDOUR_UI::instance()->keyboard_settings();
290         if (node) {
291                 keyboard->set_state (*node, Stateful::loading_state_version);
292         }
293
294         /* we don't like certain modifiers */
295         Bindings::set_ignored_state (GDK_LOCK_MASK|GDK_MOD2_MASK|GDK_MOD3_MASK);
296
297         reset_dpi();
298
299         TimeAxisViewItem::set_constant_heights ();
300
301         /* The following must happen after ARDOUR::init() so that Config is set up */
302
303         location_ui = new ActionWindowProxy<LocationUIWindow> (X_("locations"), Config->extra_xml (X_("UI")), X_("ToggleLocations"));
304         big_clock_window = new ActionWindowProxy<Gtk::Window> (X_("bigclock"), Config->extra_xml (X_("UI")), X_("ToggleBigClock"));
305         speaker_config_window = new ActionWindowProxy<SpeakerDialog> (X_("speakerconf"), Config->extra_xml (X_("UI")), X_("toggle-speaker-config"));
306
307         for (ARDOUR::DataType::iterator i = ARDOUR::DataType::begin(); i != ARDOUR::DataType::end(); ++i) {
308                 _global_port_matrix[*i] = new ActionWindowProxy<GlobalPortMatrixWindow> (
309                         string_compose ("GlobalPortMatrix-%1", (*i).to_string()),
310                         Config->extra_xml (X_("UI")),
311                         string_compose ("toggle-%1-connection-manager", (*i).to_string())
312                         );
313         }
314
315         setup_clock ();
316
317         SpeakerDialog* s = new SpeakerDialog ();
318         s->signal_unmap().connect (sigc::bind (sigc::ptr_fun (&ActionManager::uncheck_toggleaction), X_("<Actions>/Common/toggle-speaker-config")));
319         speaker_config_window->set (s);
320
321         starting.connect (sigc::mem_fun(*this, &ARDOUR_UI::startup));
322         stopping.connect (sigc::mem_fun(*this, &ARDOUR_UI::shutdown));
323
324         _process_thread = new ProcessThread ();
325         _process_thread->init ();
326
327         DPIReset.connect (sigc::mem_fun (*this, &ARDOUR_UI::resize_text_widgets));
328 }
329
330
331 int
332 ARDOUR_UI::create_engine ()
333 {
334         // this gets called every time by new_session()
335
336         if (engine) {
337                 return 0;
338         }
339
340         loading_message (_("Starting audio engine"));
341
342         try {
343                 engine = new ARDOUR::AudioEngine (ARDOUR_COMMAND_LINE::jack_client_name, ARDOUR_COMMAND_LINE::jack_session_uuid);
344
345         } catch (...) {
346
347                 return -1;
348         }
349
350         engine->Stopped.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::engine_stopped, this), gui_context());
351         engine->Running.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::engine_running, this), gui_context());
352         engine->SampleRateChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::update_sample_rate, this, _1), gui_context());
353
354         engine->Halted.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::engine_halted, this, _1, false));
355
356         ARDOUR::Port::set_connecting_blocked (ARDOUR_COMMAND_LINE::no_connect_ports);
357
358         post_engine ();
359
360         return 0;
361 }
362
363 void
364 ARDOUR_UI::post_engine ()
365 {
366         /* Things to be done once we create the AudioEngine
367          */
368
369         ARDOUR::init_post_engine ();
370
371         /* load up the UI manager */
372
373         ActionManager::init ();
374
375         _tooltips.enable();
376
377         if (setup_windows ()) {
378                 throw failed_constructor ();
379         }
380
381         /* Do this after setup_windows (), as that's when the _status_bar_visibility is created */
382         XMLNode* n = Config->extra_xml (X_("UI"));
383         if (n) {
384                 _status_bar_visibility.set_state (*n);
385         }
386         
387         check_memory_locking();
388
389         /* this is the first point at which all the keybindings are available */
390
391         if (ARDOUR_COMMAND_LINE::show_key_actions) {
392                 vector<string> names;
393                 vector<string> paths;
394                 vector<string> tooltips;
395                 vector<string> keys;
396                 vector<AccelKey> bindings;
397
398                 ActionManager::get_all_actions (names, paths, tooltips, keys, bindings);
399
400                 vector<string>::iterator n;
401                 vector<string>::iterator k;
402                 for (n = names.begin(), k = keys.begin(); n != names.end(); ++n, ++k) {
403                         cout << "Action: " << (*n) << " bound to " << (*k) << endl;
404                 }
405
406                 exit (0);
407         }
408
409         blink_timeout_tag = -1;
410
411         /* this being a GUI and all, we want peakfiles */
412
413         AudioFileSource::set_build_peakfiles (true);
414         AudioFileSource::set_build_missing_peakfiles (true);
415
416         /* set default clock modes */
417
418         if (Profile->get_sae()) {
419                 primary_clock->set_mode (AudioClock::BBT);
420                 secondary_clock->set_mode (AudioClock::MinSec);
421         }  else {
422                 primary_clock->set_mode (AudioClock::Timecode);
423                 secondary_clock->set_mode (AudioClock::BBT);
424         }
425
426         /* start the time-of-day-clock */
427
428 #ifndef GTKOSX
429         /* OS X provides a nearly-always visible wallclock, so don't be stupid */
430         update_wall_clock ();
431         Glib::signal_timeout().connect (sigc::mem_fun(*this, &ARDOUR_UI::update_wall_clock), 60000);
432 #endif
433
434         update_disk_space ();
435         update_cpu_load ();
436         update_sample_rate (engine->frame_rate());
437         update_timecode_format ();
438
439         Config->ParameterChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::parameter_changed, this, _1), gui_context());
440         boost::function<void (string)> pc (boost::bind (&ARDOUR_UI::parameter_changed, this, _1));
441         Config->map_parameters (pc);
442
443         /* now start and maybe save state */
444
445         if (do_engine_start () == 0) {
446                 if (_session && _session_is_new) {
447                         /* we need to retain initial visual
448                            settings for a new session
449                         */
450                         _session->save_state ("");
451                 }
452         }
453 }
454
455 ARDOUR_UI::~ARDOUR_UI ()
456 {
457         delete keyboard;
458         delete editor;
459         delete mixer;
460         delete add_route_dialog;
461 }
462
463 void
464 ARDOUR_UI::pop_back_splash (Gtk::Window& win)
465 {
466         if (Splash::instance()) {
467                 Splash::instance()->pop_back_for (win);
468         }
469 }
470
471 gint
472 ARDOUR_UI::configure_timeout ()
473 {
474         if (last_configure_time == 0) {
475                 /* no configure events yet */
476                 return true;
477         }
478
479         /* force a gap of 0.5 seconds since the last configure event
480          */
481
482         if (get_microseconds() - last_configure_time < 500000) {
483                 return true;
484         } else {
485                 have_configure_timeout = false;
486                 save_ardour_state ();
487                 return false;
488         }
489 }
490
491 gboolean
492 ARDOUR_UI::configure_handler (GdkEventConfigure* /*conf*/)
493 {
494         if (have_configure_timeout) {
495                 last_configure_time = get_microseconds();
496         } else {
497                 Glib::signal_timeout().connect (sigc::mem_fun(*this, &ARDOUR_UI::configure_timeout), 100);
498                 have_configure_timeout = true;
499         }
500
501         return FALSE;
502 }
503
504 void
505 ARDOUR_UI::set_transport_controllable_state (const XMLNode& node)
506 {
507         const XMLProperty* prop;
508
509         if ((prop = node.property ("roll")) != 0) {
510                 roll_controllable->set_id (prop->value());
511         }
512         if ((prop = node.property ("stop")) != 0) {
513                 stop_controllable->set_id (prop->value());
514         }
515         if ((prop = node.property ("goto-start")) != 0) {
516                 goto_start_controllable->set_id (prop->value());
517         }
518         if ((prop = node.property ("goto-end")) != 0) {
519                 goto_end_controllable->set_id (prop->value());
520         }
521         if ((prop = node.property ("auto-loop")) != 0) {
522                 auto_loop_controllable->set_id (prop->value());
523         }
524         if ((prop = node.property ("play-selection")) != 0) {
525                 play_selection_controllable->set_id (prop->value());
526         }
527         if ((prop = node.property ("rec")) != 0) {
528                 rec_controllable->set_id (prop->value());
529         }
530         if ((prop = node.property ("shuttle")) != 0) {
531                 shuttle_box->controllable()->set_id (prop->value());
532         }
533 }
534
535 XMLNode&
536 ARDOUR_UI::get_transport_controllable_state ()
537 {
538         XMLNode* node = new XMLNode(X_("TransportControllables"));
539         char buf[64];
540
541         roll_controllable->id().print (buf, sizeof (buf));
542         node->add_property (X_("roll"), buf);
543         stop_controllable->id().print (buf, sizeof (buf));
544         node->add_property (X_("stop"), buf);
545         goto_start_controllable->id().print (buf, sizeof (buf));
546         node->add_property (X_("goto_start"), buf);
547         goto_end_controllable->id().print (buf, sizeof (buf));
548         node->add_property (X_("goto_end"), buf);
549         auto_loop_controllable->id().print (buf, sizeof (buf));
550         node->add_property (X_("auto_loop"), buf);
551         play_selection_controllable->id().print (buf, sizeof (buf));
552         node->add_property (X_("play_selection"), buf);
553         rec_controllable->id().print (buf, sizeof (buf));
554         node->add_property (X_("rec"), buf);
555         shuttle_box->controllable()->id().print (buf, sizeof (buf));
556         node->add_property (X_("shuttle"), buf);
557
558         return *node;
559 }
560
561
562 gint
563 ARDOUR_UI::autosave_session ()
564 {
565         if (g_main_depth() > 1) {
566                 /* inside a recursive main loop,
567                    give up because we may not be able to
568                    take a lock.
569                 */
570                 return 1;
571         }
572
573         if (!Config->get_periodic_safety_backups()) {
574                 return 1;
575         }
576
577         if (_session) {
578                 _session->maybe_write_autosave();
579         }
580
581         return 1;
582 }
583
584 void
585 ARDOUR_UI::update_autosave ()
586 {
587         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::update_autosave)
588
589         if (_session && _session->dirty()) {
590                 if (_autosave_connection.connected()) {
591                         _autosave_connection.disconnect();
592                 }
593
594                 _autosave_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &ARDOUR_UI::autosave_session),
595                                 Config->get_periodic_safety_backup_interval() * 1000);
596
597         } else {
598                 if (_autosave_connection.connected()) {
599                         _autosave_connection.disconnect();
600                 }
601         }
602 }
603
604 void
605 ARDOUR_UI::startup ()
606 {
607         Application* app = Application::instance ();
608
609         app->ShouldQuit.connect (sigc::mem_fun (*this, &ARDOUR_UI::queue_finish));
610         app->ShouldLoad.connect (sigc::mem_fun (*this, &ARDOUR_UI::idle_load));
611
612 #ifdef PHONE_HOME
613         call_the_mothership (VERSIONSTRING);
614 #endif
615
616         app->ready ();
617
618         if (get_session_parameters (true, ARDOUR_COMMAND_LINE::new_session, ARDOUR_COMMAND_LINE::load_template)) {
619                 exit (1);
620         }
621
622         use_config ();
623
624         goto_editor_window ();
625
626         /* Add the window proxies here; their addition may cause windows to be opened, and we want them
627            to be opened on top of the editor window that goto_editor_window() just opened.
628         */
629         add_window_proxy (location_ui);
630         add_window_proxy (big_clock_window);
631         for (ARDOUR::DataType::iterator i = ARDOUR::DataType::begin(); i != ARDOUR::DataType::end(); ++i) {
632                 add_window_proxy (_global_port_matrix[*i]);
633         }
634
635         /* We have to do this here since goto_editor_window() ends up calling show_all() on the
636          * editor window, and we may want stuff to be hidden.
637          */
638         _status_bar_visibility.update ();
639
640         BootMessage (string_compose (_("%1 is ready for use"), PROGRAM_NAME));
641 }
642
643 void
644 ARDOUR_UI::no_memory_warning ()
645 {
646         XMLNode node (X_("no-memory-warning"));
647         Config->add_instant_xml (node);
648 }
649
650 void
651 ARDOUR_UI::check_memory_locking ()
652 {
653 #ifdef __APPLE__
654         /* OS X doesn't support mlockall(2), and so testing for memory locking capability there is pointless */
655         return;
656 #else // !__APPLE__
657
658         XMLNode* memory_warning_node = Config->instant_xml (X_("no-memory-warning"));
659
660         if (engine->is_realtime() && memory_warning_node == 0) {
661
662                 struct rlimit limits;
663                 int64_t ram;
664                 long pages, page_size;
665
666                 if ((page_size = sysconf (_SC_PAGESIZE)) < 0 ||(pages = sysconf (_SC_PHYS_PAGES)) < 0) {
667                         ram = 0;
668                 } else {
669                         ram = (int64_t) pages * (int64_t) page_size;
670                 }
671
672                 if (getrlimit (RLIMIT_MEMLOCK, &limits)) {
673                         return;
674                 }
675
676                 if (limits.rlim_cur != RLIM_INFINITY) {
677
678                         if (ram == 0 || ((double) limits.rlim_cur / ram) < 0.75) {
679
680                                 MessageDialog msg (
681                                         string_compose (
682                                                 _("WARNING: Your system has a limit for maximum amount of locked memory. "
683                                                   "This might cause %1 to run out of memory before your system "
684                                                   "runs out of memory. \n\n"
685                                                   "You can view the memory limit with 'ulimit -l', "
686                                                   "and it is normally controlled by /etc/security/limits.conf"),
687                                                 PROGRAM_NAME).c_str());
688
689                                 VBox* vbox = msg.get_vbox();
690                                 HBox hbox;
691                                 CheckButton cb (_("Do not show this window again"));
692
693                                 cb.signal_toggled().connect (sigc::mem_fun (*this, &ARDOUR_UI::no_memory_warning));
694
695                                 hbox.pack_start (cb, true, false);
696                                 vbox->pack_start (hbox);
697                                 cb.show();
698                                 vbox->show();
699                                 hbox.show ();
700
701                                 pop_back_splash (msg);
702
703                                 editor->ensure_float (msg);
704                                 msg.run ();
705                         }
706                 }
707         }
708 #endif // !__APPLE__
709 }
710
711
712 void
713 ARDOUR_UI::queue_finish ()
714 {
715         Glib::signal_idle().connect (mem_fun (*this, &ARDOUR_UI::idle_finish));
716 }
717
718 bool
719 ARDOUR_UI::idle_finish ()
720 {
721         finish ();
722         return false; /* do not call again */
723 }
724
725 void
726 ARDOUR_UI::finish()
727 {
728         if (_session) {
729
730                 if (_session->dirty()) {
731                         vector<string> actions;
732                         actions.push_back (_("Don't quit"));
733                         actions.push_back (_("Just quit"));
734                         actions.push_back (_("Save and quit"));
735                         switch (ask_about_saving_session(actions)) {
736                         case -1:
737                                 return;
738                                 break;
739                         case 1:
740                                 /* use the default name */
741                                 if (save_state_canfail ("")) {
742                                         /* failed - don't quit */
743                                         MessageDialog msg (*editor,
744                                                            string_compose (_("\
745 %1 was unable to save your session.\n\n\
746 If you still wish to quit, please use the\n\n\
747 \"Just quit\" option."), PROGRAM_NAME));
748                                         pop_back_splash(msg);
749                                         msg.run ();
750                                         return;
751                                 }
752                                 break;
753                         case 0:
754                                 break;
755                         }
756                 }
757
758                 second_connection.disconnect ();
759                 point_one_second_connection.disconnect ();
760                 point_oh_five_second_connection.disconnect ();
761                 point_zero_one_second_connection.disconnect();
762         }
763
764         /* Save state before deleting the session, as that causes some
765            windows to be destroyed before their visible state can be
766            saved.
767         */
768         save_ardour_state ();
769
770         loading_message (string_compose (_("Please wait while %1 cleans up..."), PROGRAM_NAME));
771
772         if (_session) {
773                 // _session->set_deletion_in_progress ();
774                 _session->set_clean ();
775                 _session->remove_pending_capture_state ();
776                 delete _session;
777                 _session = 0;
778         }
779
780         ArdourDialog::close_all_dialogs ();
781         engine->stop (true);
782         quit ();
783 }
784
785 int
786 ARDOUR_UI::ask_about_saving_session (const vector<string>& actions)
787 {
788         ArdourDialog window (_("Unsaved Session"));
789         Gtk::HBox dhbox;  // the hbox for the image and text
790         Gtk::Label  prompt_label;
791         Gtk::Image* dimage = manage (new Gtk::Image(Stock::DIALOG_WARNING,  Gtk::ICON_SIZE_DIALOG));
792
793         string msg;
794
795         assert (actions.size() >= 3);
796
797         window.add_button (actions[0], RESPONSE_REJECT);
798         window.add_button (actions[1], RESPONSE_APPLY);
799         window.add_button (actions[2], RESPONSE_ACCEPT);
800
801         window.set_default_response (RESPONSE_ACCEPT);
802
803         Gtk::Button noquit_button (msg);
804         noquit_button.set_name ("EditorGTKButton");
805
806         string prompt;
807
808         if (_session->snap_name() == _session->name()) {
809                 prompt = string_compose(_("The session \"%1\"\nhas not been saved.\n\nAny changes made this time\nwill be lost unless you save it.\n\nWhat do you want to do?"),
810                                         _session->snap_name());
811         } else {
812                 prompt = string_compose(_("The snapshot \"%1\"\nhas not been saved.\n\nAny changes made this time\nwill be lost unless you save it.\n\nWhat do you want to do?"),
813                                         _session->snap_name());
814         }
815
816         prompt_label.set_text (prompt);
817         prompt_label.set_name (X_("PrompterLabel"));
818         prompt_label.set_alignment(ALIGN_LEFT, ALIGN_TOP);
819
820         dimage->set_alignment(ALIGN_CENTER, ALIGN_TOP);
821         dhbox.set_homogeneous (false);
822         dhbox.pack_start (*dimage, false, false, 5);
823         dhbox.pack_start (prompt_label, true, false, 5);
824         window.get_vbox()->pack_start (dhbox);
825
826         window.set_name (_("Prompter"));
827         window.set_position (Gtk::WIN_POS_MOUSE);
828         window.set_modal (true);
829         window.set_resizable (false);
830
831         dhbox.show();
832         prompt_label.show();
833         dimage->show();
834         window.show();
835         window.set_keep_above (true);
836         window.present ();
837
838         ResponseType r = (ResponseType) window.run();
839
840         window.hide ();
841
842         switch (r) {
843         case RESPONSE_ACCEPT: // save and get out of here
844                 return 1;
845         case RESPONSE_APPLY:  // get out of here
846                 return 0;
847         default:
848                 break;
849         }
850
851         return -1;
852 }
853
854
855 gint
856 ARDOUR_UI::every_second ()
857 {
858         update_cpu_load ();
859         update_buffer_load ();
860         update_disk_space ();
861         update_timecode_format ();
862         return TRUE;
863 }
864
865 gint
866 ARDOUR_UI::every_point_one_seconds ()
867 {
868         shuttle_box->update_speed_display ();
869         RapidScreenUpdate(); /* EMIT_SIGNAL */
870         return TRUE;
871 }
872
873 gint
874 ARDOUR_UI::every_point_zero_one_seconds ()
875 {
876         // august 2007: actual update frequency: 40Hz, not 100Hz
877
878         SuperRapidScreenUpdate(); /* EMIT_SIGNAL */
879         return TRUE;
880 }
881
882 void
883 ARDOUR_UI::update_sample_rate (framecnt_t)
884 {
885         char buf[64];
886
887         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::update_sample_rate, ignored)
888
889         if (!engine->connected()) {
890
891                 snprintf (buf, sizeof (buf), "%s", _("disconnected"));
892
893         } else {
894
895                 framecnt_t rate = engine->frame_rate();
896
897                 if (fmod (rate, 1000.0) != 0.0) {
898                         snprintf (buf, sizeof (buf), _("JACK: <span foreground=\"green\">%.1f kHz / %4.1f ms</span>"),
899                                   (float) rate/1000.0f,
900                                   (engine->frames_per_cycle() / (float) rate) * 1000.0f);
901                 } else {
902                         snprintf (buf, sizeof (buf), _("JACK: <span foreground=\"green\">%" PRId64 " kHz / %4.1f ms</span>"),
903                                   rate/1000,
904                                   (engine->frames_per_cycle() / (float) rate) * 1000.0f);
905                 }
906         }
907
908         sample_rate_label.set_markup (buf);
909 }
910
911 void
912 ARDOUR_UI::update_format ()
913 {
914         if (!_session) {
915                 format_label.set_text ("");
916                 return;
917         }
918
919         stringstream s;
920         s << _("File:") << X_(" <span foreground=\"green\">");
921
922         switch (_session->config.get_native_file_header_format ()) {
923         case BWF:
924                 s << _("BWF");
925                 break;
926         case WAVE:
927                 s << _("WAV");
928                 break;
929         case WAVE64:
930                 s << _("WAV64");
931                 break;
932         case CAF:
933                 s << _("CAF");
934                 break;
935         case AIFF:
936                 s << _("AIFF");
937                 break;
938         case iXML:
939                 s << _("iXML");
940                 break;
941         case RF64:
942                 s << _("RF64");
943                 break;
944         }
945
946         s << " ";
947         
948         switch (_session->config.get_native_file_data_format ()) {
949         case FormatFloat:
950                 s << _("32-float");
951                 break;
952         case FormatInt24:
953                 s << _("24-int");
954                 break;
955         case FormatInt16:
956                 s << _("16-int");
957                 break;
958         }
959
960         s << X_("</span>");
961
962         format_label.set_markup (s.str ());
963 }
964
965 void
966 ARDOUR_UI::update_cpu_load ()
967 {
968         char buf[64];
969
970         /* If this text is changed, the set_size_request_to_display_given_text call in ARDOUR_UI::resize_text_widgets
971            should also be changed.
972         */
973
974         float const c = engine->get_cpu_load ();
975         snprintf (buf, sizeof (buf), _("DSP: <span foreground=\"%s\">%5.1f%%</span>"), c >= 90 ? X_("red") : X_("green"), c);
976         cpu_load_label.set_markup (buf);
977 }
978
979 void
980 ARDOUR_UI::update_buffer_load ()
981 {
982         char buf[256];
983
984         uint32_t const playback = _session ? _session->playback_load () : 100;
985         uint32_t const capture = _session ? _session->capture_load () : 100;
986
987         /* If this text is changed, the set_size_request_to_display_given_text call in ARDOUR_UI::resize_text_widgets
988            should also be changed.
989         */
990         
991         if (_session) {
992                 snprintf (
993                         buf, sizeof (buf),
994                         _("Buffers: <span foreground=\"green\">p:</span><span foreground=\"%s\">%" PRIu32 "%%</span> "
995                                    "<span foreground=\"green\">c:</span><span foreground=\"%s\">%" PRIu32 "%%</span>"),
996                         playback <= 5 ? X_("red") : X_("green"),
997                         playback,
998                         capture <= 5 ? X_("red") : X_("green"),
999                         capture
1000                         );
1001
1002                 buffer_load_label.set_markup (buf);
1003         } else {
1004                 buffer_load_label.set_text ("");
1005         }
1006 }
1007
1008 void
1009 ARDOUR_UI::count_recenabled_streams (Route& route)
1010 {
1011         Track* track = dynamic_cast<Track*>(&route);
1012         if (track && track->record_enabled()) {
1013                 rec_enabled_streams += track->n_inputs().n_total();
1014         }
1015 }
1016
1017 void
1018 ARDOUR_UI::update_disk_space()
1019 {
1020         if (_session == 0) {
1021                 return;
1022         }
1023
1024         boost::optional<framecnt_t> opt_frames = _session->available_capture_duration();
1025         char buf[64];
1026         framecnt_t fr = _session->frame_rate();
1027
1028         if (!opt_frames) {
1029                 /* Available space is unknown */
1030                 snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">Unknown</span>"));
1031         } else if (opt_frames.get_value_or (0) == max_framecnt) {
1032                 snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">24hrs+</span>"));
1033         } else {
1034                 rec_enabled_streams = 0;
1035                 _session->foreach_route (this, &ARDOUR_UI::count_recenabled_streams);
1036
1037                 framecnt_t frames = opt_frames.get_value_or (0);
1038
1039                 if (rec_enabled_streams) {
1040                         frames /= rec_enabled_streams;
1041                 }
1042
1043                 int hrs;
1044                 int mins;
1045                 int secs;
1046
1047                 hrs  = frames / (fr * 3600);
1048
1049                 if (hrs > 24) {
1050                         snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">&gt;24 hrs</span>"));
1051                 } else {
1052                         frames -= hrs * fr * 3600;
1053                         mins = frames / (fr * 60);
1054                         frames -= mins * fr * 60;
1055                         secs = frames / fr;
1056                         
1057                         bool const low = (hrs == 0 && mins <= 30);
1058                         
1059                         snprintf (
1060                                 buf, sizeof(buf),
1061                                 _("Disk: <span foreground=\"%s\">%02dh:%02dm:%02ds</span>"),
1062                                 low ? X_("red") : X_("green"),
1063                                 hrs, mins, secs
1064                                 );
1065                 }
1066         }
1067
1068         disk_space_label.set_markup (buf);
1069 }
1070
1071 void
1072 ARDOUR_UI::update_timecode_format ()
1073 {
1074         char buf[64];
1075
1076         if (_session) {
1077                 bool matching;
1078                 TimecodeSlave* tcslave;
1079                 SyncSource sync_src = Config->get_sync_source();
1080
1081                 if ((sync_src == LTC || sync_src == MTC) && (tcslave = dynamic_cast<TimecodeSlave*>(_session->slave())) != 0) {
1082                         matching = (tcslave->apparent_timecode_format() == _session->config.get_timecode_format());
1083                 } else {
1084                         matching = true;
1085                 }
1086                         
1087                 snprintf (buf, sizeof (buf), S_("Timecode|TC: <span foreground=\"%s\">%s</span>"),
1088                           matching ? X_("green") : X_("red"),
1089                           Timecode::timecode_format_name (_session->config.get_timecode_format()).c_str());
1090         } else {
1091                 snprintf (buf, sizeof (buf), "TC: n/a");
1092         }
1093
1094         timecode_format_label.set_markup (buf);
1095 }       
1096
1097 gint
1098 ARDOUR_UI::update_wall_clock ()
1099 {
1100         time_t now;
1101         struct tm *tm_now;
1102         char buf[16];
1103
1104         time (&now);
1105         tm_now = localtime (&now);
1106
1107         sprintf (buf, "%02d:%02d", tm_now->tm_hour, tm_now->tm_min);
1108         wall_clock_label.set_text (buf);
1109
1110         return TRUE;
1111 }
1112
1113 void
1114 ARDOUR_UI::redisplay_recent_sessions ()
1115 {
1116         std::vector<std::string> session_directories;
1117         RecentSessionsSorter cmp;
1118
1119         recent_session_display.set_model (Glib::RefPtr<TreeModel>(0));
1120         recent_session_model->clear ();
1121
1122         ARDOUR::RecentSessions rs;
1123         ARDOUR::read_recent_sessions (rs);
1124
1125         if (rs.empty()) {
1126                 recent_session_display.set_model (recent_session_model);
1127                 return;
1128         }
1129
1130         // sort them alphabetically
1131         sort (rs.begin(), rs.end(), cmp);
1132
1133         for (ARDOUR::RecentSessions::iterator i = rs.begin(); i != rs.end(); ++i) {
1134                 session_directories.push_back ((*i).second);
1135         }
1136
1137         for (vector<std::string>::const_iterator i = session_directories.begin();
1138                         i != session_directories.end(); ++i)
1139         {
1140                 std::vector<std::string> state_file_paths;
1141
1142                 // now get available states for this session
1143
1144                 get_state_files_in_directory (*i, state_file_paths);
1145
1146                 vector<string*>* states;
1147                 vector<const gchar*> item;
1148                 string fullpath = *i;
1149
1150                 /* remove any trailing / */
1151
1152                 if (fullpath[fullpath.length() - 1] == '/') {
1153                         fullpath = fullpath.substr (0, fullpath.length() - 1);
1154                 }
1155
1156                 /* check whether session still exists */
1157                 if (!Glib::file_test(fullpath.c_str(), Glib::FILE_TEST_EXISTS)) {
1158                         /* session doesn't exist */
1159                         continue;
1160                 }
1161
1162                 /* now get available states for this session */
1163
1164                 if ((states = Session::possible_states (fullpath)) == 0) {
1165                         /* no state file? */
1166                         continue;
1167                 }
1168
1169                 std::vector<string> state_file_names(get_file_names_no_extension (state_file_paths));
1170
1171                 Gtk::TreeModel::Row row = *(recent_session_model->append());
1172
1173                 row[recent_session_columns.visible_name] = Glib::path_get_basename (fullpath);
1174                 row[recent_session_columns.fullpath] = fullpath;
1175
1176                 if (state_file_names.size() > 1) {
1177
1178                         // add the children
1179
1180                         for (std::vector<std::string>::iterator i2 = state_file_names.begin();
1181                                         i2 != state_file_names.end(); ++i2)
1182                         {
1183
1184                                 Gtk::TreeModel::Row child_row = *(recent_session_model->append (row.children()));
1185
1186                                 child_row[recent_session_columns.visible_name] = *i2;
1187                                 child_row[recent_session_columns.fullpath] = fullpath;
1188                         }
1189                 }
1190         }
1191
1192         recent_session_display.set_tooltip_column(1); // recent_session_columns.fullpath
1193         recent_session_display.set_model (recent_session_model);
1194 }
1195
1196 void
1197 ARDOUR_UI::build_session_selector ()
1198 {
1199         session_selector_window = new ArdourDialog (_("Recent Sessions"));
1200
1201         Gtk::ScrolledWindow *scroller = manage (new Gtk::ScrolledWindow);
1202
1203         session_selector_window->add_button (Stock::CANCEL, RESPONSE_CANCEL);
1204         session_selector_window->add_button (Stock::OPEN, RESPONSE_ACCEPT);
1205         session_selector_window->set_default_response (RESPONSE_ACCEPT);
1206         recent_session_model = TreeStore::create (recent_session_columns);
1207         recent_session_display.set_model (recent_session_model);
1208         recent_session_display.append_column (_("Recent Sessions"), recent_session_columns.visible_name);
1209         recent_session_display.set_headers_visible (false);
1210         recent_session_display.get_selection()->set_mode (SELECTION_BROWSE);
1211         recent_session_display.signal_row_activated().connect (sigc::mem_fun (*this, &ARDOUR_UI::recent_session_row_activated));
1212
1213         scroller->add (recent_session_display);
1214         scroller->set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
1215
1216         session_selector_window->set_name ("SessionSelectorWindow");
1217         session_selector_window->set_size_request (200, 400);
1218         session_selector_window->get_vbox()->pack_start (*scroller);
1219
1220         recent_session_display.show();
1221         scroller->show();
1222 }
1223
1224 void
1225 ARDOUR_UI::recent_session_row_activated (const TreePath& /*path*/, TreeViewColumn* /*col*/)
1226 {
1227         session_selector_window->response (RESPONSE_ACCEPT);
1228 }
1229
1230 void
1231 ARDOUR_UI::open_recent_session ()
1232 {
1233         bool can_return = (_session != 0);
1234
1235         if (session_selector_window == 0) {
1236                 build_session_selector ();
1237         }
1238
1239         redisplay_recent_sessions ();
1240
1241         while (true) {
1242
1243                 session_selector_window->set_position (WIN_POS_MOUSE);
1244
1245                 ResponseType r = (ResponseType) session_selector_window->run ();
1246
1247                 switch (r) {
1248                 case RESPONSE_ACCEPT:
1249                         break;
1250                 default:
1251                         if (can_return) {
1252                                 session_selector_window->hide();
1253                                 return;
1254                         } else {
1255                                 exit (1);
1256                         }
1257                 }
1258
1259                 if (recent_session_display.get_selection()->count_selected_rows() == 0) {
1260                         continue;
1261                 }
1262
1263                 session_selector_window->hide();
1264
1265                 Gtk::TreeModel::iterator i = recent_session_display.get_selection()->get_selected();
1266
1267                 if (i == recent_session_model->children().end()) {
1268                         return;
1269                 }
1270
1271                 std::string path = (*i)[recent_session_columns.fullpath];
1272                 std::string state = (*i)[recent_session_columns.visible_name];
1273
1274                 _session_is_new = false;
1275
1276                 if (load_session (path, state) == 0) {
1277                         break;
1278                 }
1279
1280                 can_return = false;
1281         }
1282 }
1283
1284 bool
1285 ARDOUR_UI::check_audioengine ()
1286 {
1287         if (engine) {
1288                 if (!engine->connected()) {
1289                         MessageDialog msg (string_compose (
1290                                                    _("%1 is not connected to JACK\n"
1291                                                      "You cannot open or close sessions in this condition"),
1292                                                    PROGRAM_NAME));
1293                         pop_back_splash (msg);
1294                         msg.run ();
1295                         return false;
1296                 }
1297                 return true;
1298         } else {
1299                 return false;
1300         }
1301 }
1302
1303 void
1304 ARDOUR_UI::open_session ()
1305 {
1306         if (!check_audioengine()) {
1307                 return;
1308
1309         }
1310
1311         /* popup selector window */
1312
1313         if (open_session_selector == 0) {
1314
1315                 /* ardour sessions are folders */
1316
1317                 open_session_selector = new Gtk::FileChooserDialog (_("Open Session"), FILE_CHOOSER_ACTION_OPEN);
1318                 open_session_selector->add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1319                 open_session_selector->add_button (Gtk::Stock::OPEN, Gtk::RESPONSE_ACCEPT);
1320                 open_session_selector->set_default_response(Gtk::RESPONSE_ACCEPT);
1321                 
1322                 if (_session) {
1323                         string session_parent_dir = Glib::path_get_dirname(_session->path());
1324                         string::size_type last_dir_sep = session_parent_dir.rfind(G_DIR_SEPARATOR);
1325                         session_parent_dir = session_parent_dir.substr(0, last_dir_sep);
1326                         open_session_selector->set_current_folder(session_parent_dir);
1327                 } else {
1328                         open_session_selector->set_current_folder(Config->get_default_session_parent_dir());
1329                 }
1330
1331                 open_session_selector->add_shortcut_folder (Config->get_default_session_parent_dir());
1332
1333                 FileFilter session_filter;
1334                 session_filter.add_pattern ("*.ardour");
1335                 session_filter.set_name (string_compose (_("%1 sessions"), PROGRAM_NAME));
1336                 open_session_selector->add_filter (session_filter);
1337                 open_session_selector->set_filter (session_filter);
1338         }
1339
1340         int response = open_session_selector->run();
1341         open_session_selector->hide ();
1342
1343         switch (response) {
1344         case RESPONSE_ACCEPT:
1345                 break;
1346         default:
1347                 open_session_selector->hide();
1348                 return;
1349         }
1350
1351         open_session_selector->hide();
1352         string session_path = open_session_selector->get_filename();
1353         string path, name;
1354         bool isnew;
1355
1356         if (session_path.length() > 0) {
1357                 if (ARDOUR::find_session (session_path, path, name, isnew) == 0) {
1358                         _session_is_new = isnew;
1359                         load_session (path, name);
1360                 }
1361         }
1362 }
1363
1364
1365 void
1366 ARDOUR_UI::session_add_mixed_track (const ChanCount& input, const ChanCount& output, RouteGroup* route_group, 
1367                                     uint32_t how_many, const string& name_template, PluginInfoPtr instrument)
1368 {
1369         list<boost::shared_ptr<MidiTrack> > tracks;
1370
1371         if (_session == 0) {
1372                 warning << _("You cannot add a track without a session already loaded.") << endmsg;
1373                 return;
1374         }
1375
1376         try {
1377                 tracks = _session->new_midi_track (input, output, instrument, ARDOUR::Normal, route_group, how_many, name_template);
1378                 
1379                 if (tracks.size() != how_many) {
1380                         if (how_many == 1) {
1381                                 error << _("could not create a new mixed track") << endmsg;
1382                         } else {
1383                                 error << string_compose (_("could not create %1 new mixed tracks"), how_many) << endmsg;
1384                         }
1385                 }
1386         }
1387
1388         catch (...) {
1389                 MessageDialog msg (*editor,
1390                                    string_compose (_("There are insufficient JACK ports available\n\
1391 to create a new track or bus.\n\
1392 You should save %1, exit and\n\
1393 restart JACK with more ports."), PROGRAM_NAME));
1394                 msg.run ();
1395         }
1396 }
1397         
1398
1399 void
1400 ARDOUR_UI::session_add_midi_route (bool disk, RouteGroup* route_group, uint32_t how_many, const string& name_template, PluginInfoPtr instrument)
1401 {
1402         ChanCount one_midi_channel;
1403         one_midi_channel.set (DataType::MIDI, 1);
1404
1405         if (disk) {
1406                 session_add_mixed_track (one_midi_channel, one_midi_channel, route_group, how_many, name_template, instrument);
1407         }
1408 }
1409
1410 void
1411 ARDOUR_UI::session_add_audio_route (
1412         bool track,
1413         int32_t input_channels,
1414         int32_t output_channels,
1415         ARDOUR::TrackMode mode,
1416         RouteGroup* route_group,
1417         uint32_t how_many,
1418         string const & name_template
1419         )
1420 {
1421         list<boost::shared_ptr<AudioTrack> > tracks;
1422         RouteList routes;
1423
1424         if (_session == 0) {
1425                 warning << _("You cannot add a track or bus without a session already loaded.") << endmsg;
1426                 return;
1427         }
1428
1429         try {
1430                 if (track) {
1431                         tracks = _session->new_audio_track (input_channels, output_channels, mode, route_group, how_many, name_template);
1432
1433                         if (tracks.size() != how_many) {
1434                                 if (how_many == 1) {
1435                                         error << _("could not create a new audio track") << endmsg;
1436                                 } else {
1437                                         error << string_compose (_("could only create %1 of %2 new audio %3"),
1438                                                                  tracks.size(), how_many, (track ? _("tracks") : _("busses"))) << endmsg;
1439                                 }
1440                         }
1441
1442                 } else {
1443
1444                         routes = _session->new_audio_route (input_channels, output_channels, route_group, how_many, name_template);
1445
1446                         if (routes.size() != how_many) {
1447                                 if (how_many == 1) {
1448                                         error << _("could not create a new audio bus") << endmsg;
1449                                 } else {
1450                                         error << string_compose (_("could not create %1 new audio busses"), how_many) << endmsg;
1451                                 }
1452                         }
1453                 }
1454         }
1455
1456         catch (...) {
1457                 MessageDialog msg (*editor,
1458                                    string_compose (_("There are insufficient JACK ports available\n\
1459 to create a new track or bus.\n\
1460 You should save %1, exit and\n\
1461 restart JACK with more ports."), PROGRAM_NAME));
1462                 pop_back_splash (msg);
1463                 msg.run ();
1464         }
1465 }
1466
1467 void
1468 ARDOUR_UI::transport_goto_start ()
1469 {
1470         if (_session) {
1471                 _session->goto_start();
1472
1473                 /* force displayed area in editor to start no matter
1474                    what "follow playhead" setting is.
1475                 */
1476
1477                 if (editor) {
1478                         editor->center_screen (_session->current_start_frame ());
1479                 }
1480         }
1481 }
1482
1483 void
1484 ARDOUR_UI::transport_goto_zero ()
1485 {
1486         if (_session) {
1487                 _session->request_locate (0);
1488
1489                 /* force displayed area in editor to start no matter
1490                    what "follow playhead" setting is.
1491                 */
1492
1493                 if (editor) {
1494                         editor->reset_x_origin (0);
1495                 }
1496         }
1497 }
1498
1499 void
1500 ARDOUR_UI::transport_goto_wallclock ()
1501 {
1502         if (_session && editor) {
1503
1504                 time_t now;
1505                 struct tm tmnow;
1506                 framepos_t frames;
1507
1508                 time (&now);
1509                 localtime_r (&now, &tmnow);
1510
1511                 frames = tmnow.tm_hour * (60 * 60 * _session->frame_rate());
1512                 frames += tmnow.tm_min * (60 * _session->frame_rate());
1513                 frames += tmnow.tm_sec * _session->frame_rate();
1514
1515                 _session->request_locate (frames, _session->transport_rolling ());
1516
1517                 /* force displayed area in editor to start no matter
1518                    what "follow playhead" setting is.
1519                 */
1520
1521                 if (editor) {
1522                         editor->center_screen (frames);
1523                 }
1524         }
1525 }
1526
1527 void
1528 ARDOUR_UI::transport_goto_end ()
1529 {
1530         if (_session) {
1531                 framepos_t const frame = _session->current_end_frame();
1532                 _session->request_locate (frame);
1533
1534                 /* force displayed area in editor to start no matter
1535                    what "follow playhead" setting is.
1536                 */
1537
1538                 if (editor) {
1539                         editor->center_screen (frame);
1540                 }
1541         }
1542 }
1543
1544 void
1545 ARDOUR_UI::transport_stop ()
1546 {
1547         if (!_session) {
1548                 return;
1549         }
1550
1551         if (_session->is_auditioning()) {
1552                 _session->cancel_audition ();
1553                 return;
1554         }
1555
1556         _session->request_stop (false, true);
1557 }
1558
1559 void
1560 ARDOUR_UI::transport_record (bool roll)
1561 {
1562
1563         if (_session) {
1564                 switch (_session->record_status()) {
1565                 case Session::Disabled:
1566                         if (_session->ntracks() == 0) {
1567                                 MessageDialog msg (*editor, _("Please create one or more tracks before trying to record.\nYou can do this with the \"Add Track or Bus\" option in the Session menu."));
1568                                 msg.run ();
1569                                 return;
1570                         }
1571                         _session->maybe_enable_record ();
1572                         if (roll) {
1573                                 transport_roll ();
1574                         }
1575                         break;
1576                 case Session::Recording:
1577                         if (roll) {
1578                                 _session->request_stop();
1579                         } else {
1580                                 _session->disable_record (false, true);
1581                         }
1582                         break;
1583
1584                 case Session::Enabled:
1585                         _session->disable_record (false, true);
1586                 }
1587         }
1588 }
1589
1590 void
1591 ARDOUR_UI::transport_roll ()
1592 {
1593         if (!_session) {
1594                 return;
1595         }
1596
1597         if (_session->is_auditioning()) {
1598                 return;
1599         }
1600
1601 #if 0
1602         if (_session->config.get_external_sync()) {
1603                 switch (Config->get_sync_source()) {
1604                 case JACK:
1605                         break;
1606                 default:
1607                         /* transport controlled by the master */
1608                         return;
1609                 }
1610         }
1611 #endif
1612
1613         bool rolling = _session->transport_rolling();
1614
1615         if (_session->get_play_loop()) {
1616                 /* XXX it is not possible to just leave seamless loop and keep
1617                    playing at present (nov 4th 2009)
1618                 */
1619                 if (!Config->get_seamless_loop()) {
1620                         _session->request_play_loop (false, true);
1621                 }
1622         } else if (_session->get_play_range () && !Config->get_always_play_range()) {
1623                 /* stop playing a range if we currently are */
1624                 _session->request_play_range (0, true);
1625         }
1626
1627         if (!rolling) {
1628                 _session->request_transport_speed (1.0f);
1629         }
1630 }
1631
1632 bool
1633 ARDOUR_UI::get_smart_mode() const
1634 {
1635         return ( editor->get_smart_mode() );
1636 }
1637
1638
1639 void
1640 ARDOUR_UI::toggle_roll (bool with_abort, bool roll_out_of_bounded_mode)
1641 {
1642
1643         if (!_session) {
1644                 return;
1645         }
1646
1647         if (_session->is_auditioning()) {
1648                 _session->cancel_audition ();
1649                 return;
1650         }
1651
1652         if (_session->config.get_external_sync()) {
1653                 switch (Config->get_sync_source()) {
1654                 case JACK:
1655                         break;
1656                 default:
1657                         /* transport controlled by the master */
1658                         return;
1659                 }
1660         }
1661
1662         bool rolling = _session->transport_rolling();
1663         bool affect_transport = true;
1664
1665         if (rolling && roll_out_of_bounded_mode) {
1666                 /* drop out of loop/range playback but leave transport rolling */
1667                 if (_session->get_play_loop()) {
1668                         if (Config->get_seamless_loop()) {
1669                                 /* the disk buffers contain copies of the loop - we can't
1670                                    just keep playing, so stop the transport. the user
1671                                    can restart as they wish.
1672                                 */
1673                                 affect_transport = true;
1674                         } else {
1675                                 /* disk buffers are normal, so we can keep playing */
1676                                 affect_transport = false;
1677                         }
1678                         _session->request_play_loop (false, true);
1679                 } else if (_session->get_play_range ()) {
1680                         affect_transport = false;
1681                         _session->request_play_range (0, true);
1682                 }
1683         }
1684
1685         if (affect_transport) {
1686                 if (rolling) {
1687                         _session->request_stop (with_abort, true);
1688                 } else {
1689                         if ( Config->get_always_play_range() ) {
1690                                 _session->request_play_range (&editor->get_selection().time, true);
1691                         }
1692
1693                         _session->request_transport_speed (1.0f);
1694                 }
1695         }
1696 }
1697
1698 void
1699 ARDOUR_UI::toggle_session_auto_loop ()
1700 {
1701         Location * looploc = _session->locations()->auto_loop_location();
1702
1703         if (!_session || !looploc) {
1704                 return;
1705         }
1706
1707         if (_session->get_play_loop()) {
1708
1709                 if (_session->transport_rolling()) {
1710
1711                         _session->request_locate (looploc->start(), true);
1712                         _session->request_play_loop (false);
1713
1714                 } else {
1715                         _session->request_play_loop (false);
1716                 }
1717         } else {
1718                 _session->request_play_loop (true);
1719         }
1720         
1721         //show the loop markers
1722         looploc->set_hidden (false, this);
1723 }
1724
1725 void
1726 ARDOUR_UI::transport_play_selection ()
1727 {
1728         if (!_session) {
1729                 return;
1730         }
1731
1732         editor->play_selection ();
1733 }
1734
1735 void
1736 ARDOUR_UI::transport_play_preroll ()
1737 {
1738         if (!_session) {
1739                 return;
1740         }
1741         editor->play_with_preroll ();
1742 }
1743
1744 void
1745 ARDOUR_UI::transport_rewind (int option)
1746 {
1747         float current_transport_speed;
1748
1749         if (_session) {
1750                 current_transport_speed = _session->transport_speed();
1751
1752                 if (current_transport_speed >= 0.0f) {
1753                         switch (option) {
1754                         case 0:
1755                                 _session->request_transport_speed (-1.0f);
1756                                 break;
1757                         case 1:
1758                                 _session->request_transport_speed (-4.0f);
1759                                 break;
1760                         case -1:
1761                                 _session->request_transport_speed (-0.5f);
1762                                 break;
1763                         }
1764                 } else {
1765                         /* speed up */
1766                         _session->request_transport_speed (current_transport_speed * 1.5f);
1767                 }
1768         }
1769 }
1770
1771 void
1772 ARDOUR_UI::transport_forward (int option)
1773 {
1774         if (!_session) {
1775                 return;
1776         }
1777         
1778         float current_transport_speed = _session->transport_speed();
1779         
1780         if (current_transport_speed <= 0.0f) {
1781                 switch (option) {
1782                 case 0:
1783                         _session->request_transport_speed (1.0f);
1784                         break;
1785                 case 1:
1786                         _session->request_transport_speed (4.0f);
1787                         break;
1788                 case -1:
1789                         _session->request_transport_speed (0.5f);
1790                         break;
1791                 }
1792         } else {
1793                 /* speed up */
1794                 _session->request_transport_speed (current_transport_speed * 1.5f);
1795         }
1796 }
1797
1798 void
1799 ARDOUR_UI::toggle_record_enable (uint32_t rid)
1800 {
1801         if (!_session) {
1802                 return;
1803         }
1804
1805         boost::shared_ptr<Route> r;
1806
1807         if ((r = _session->route_by_remote_id (rid)) != 0) {
1808
1809                 Track* t;
1810
1811                 if ((t = dynamic_cast<Track*>(r.get())) != 0) {
1812                         t->set_record_enabled (!t->record_enabled(), this);
1813                 }
1814         }
1815 }
1816
1817 void
1818 ARDOUR_UI::map_transport_state ()
1819 {
1820         if (!_session) {
1821                 auto_loop_button.unset_active_state ();
1822                 play_selection_button.unset_active_state ();
1823                 roll_button.unset_active_state ();
1824                 stop_button.set_active_state (Gtkmm2ext::ExplicitActive);
1825                 return;
1826         }
1827
1828         shuttle_box->map_transport_state ();
1829
1830         float sp = _session->transport_speed();
1831
1832         if (sp != 0.0f) {
1833
1834                 /* we're rolling */
1835
1836                 if (_session->get_play_range()) {
1837
1838                         play_selection_button.set_active_state (Gtkmm2ext::ExplicitActive);
1839                         roll_button.unset_active_state ();
1840                         auto_loop_button.unset_active_state ();
1841
1842                 } else if (_session->get_play_loop ()) {
1843
1844                         auto_loop_button.set_active (true);
1845                         play_selection_button.set_active (false);
1846                         roll_button.set_active (false);
1847
1848                 } else {
1849
1850                         roll_button.set_active (true);
1851                         play_selection_button.set_active (false);
1852                         auto_loop_button.set_active (false);
1853                 }
1854
1855                 if (Config->get_always_play_range()) {
1856                         /* light up both roll and play-selection if they are joined */
1857                         roll_button.set_active (true);
1858                         play_selection_button.set_active (true);
1859                 }
1860
1861                 stop_button.set_active (false);
1862
1863         } else {
1864
1865                 stop_button.set_active (true);
1866                 roll_button.set_active (false);
1867                 play_selection_button.set_active (false);
1868                 auto_loop_button.set_active (false);
1869                 update_disk_space ();
1870         }
1871 }
1872
1873 void
1874 ARDOUR_UI::engine_stopped ()
1875 {
1876         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::engine_stopped)
1877         ActionManager::set_sensitive (ActionManager::jack_sensitive_actions, false);
1878         ActionManager::set_sensitive (ActionManager::jack_opposite_sensitive_actions, true);
1879 }
1880
1881 void
1882 ARDOUR_UI::engine_running ()
1883 {
1884         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::engine_running)
1885         ActionManager::set_sensitive (ActionManager::jack_sensitive_actions, true);
1886         ActionManager::set_sensitive (ActionManager::jack_opposite_sensitive_actions, false);
1887
1888         Glib::RefPtr<Action> action;
1889         const char* action_name = 0;
1890
1891         switch (engine->frames_per_cycle()) {
1892         case 32:
1893                 action_name = X_("JACKLatency32");
1894                 break;
1895         case 64:
1896                 action_name = X_("JACKLatency64");
1897                 break;
1898         case 128:
1899                 action_name = X_("JACKLatency128");
1900                 break;
1901         case 512:
1902                 action_name = X_("JACKLatency512");
1903                 break;
1904         case 1024:
1905                 action_name = X_("JACKLatency1024");
1906                 break;
1907         case 2048:
1908                 action_name = X_("JACKLatency2048");
1909                 break;
1910         case 4096:
1911                 action_name = X_("JACKLatency4096");
1912                 break;
1913         case 8192:
1914                 action_name = X_("JACKLatency8192");
1915                 break;
1916         default:
1917                 /* XXX can we do anything useful ? */
1918                 break;
1919         }
1920
1921         if (action_name) {
1922
1923                 action = ActionManager::get_action (X_("JACK"), action_name);
1924
1925                 if (action) {
1926                         Glib::RefPtr<RadioAction> ract = Glib::RefPtr<RadioAction>::cast_dynamic (action);
1927                         ract->set_active ();
1928                 }
1929         }
1930 }
1931
1932 void
1933 ARDOUR_UI::engine_halted (const char* reason, bool free_reason)
1934 {
1935         if (!Gtkmm2ext::UI::instance()->caller_is_ui_thread()) {
1936                 /* we can't rely on the original string continuing to exist when we are called
1937                    again in the GUI thread, so make a copy and note that we need to
1938                    free it later.
1939                 */
1940                 char *copy = strdup (reason);
1941                 Gtkmm2ext::UI::instance()->call_slot (invalidator (*this), boost::bind (&ARDOUR_UI::engine_halted, this, copy, true));
1942                 return;
1943         }
1944
1945         ActionManager::set_sensitive (ActionManager::jack_sensitive_actions, false);
1946         ActionManager::set_sensitive (ActionManager::jack_opposite_sensitive_actions, true);
1947
1948         update_sample_rate (0);
1949
1950         string msgstr;
1951
1952         /* if the reason is a non-empty string, it means that the backend was shutdown
1953            rather than just Ardour.
1954         */
1955
1956         if (strlen (reason)) {
1957                 msgstr = string_compose (_("The audio backend (JACK) was shutdown because:\n\n%1"), reason);
1958         } else {
1959                 msgstr = string_compose (_("\
1960 JACK has either been shutdown or it\n\
1961 disconnected %1 because %1\n\
1962 was not fast enough. Try to restart\n\
1963 JACK, reconnect and save the session."), PROGRAM_NAME);
1964         }
1965
1966         MessageDialog msg (*editor, msgstr);
1967         pop_back_splash (msg);
1968         msg.run ();
1969
1970         if (free_reason) {
1971                 free (const_cast<char*> (reason));
1972         }
1973 }
1974
1975 int32_t
1976 ARDOUR_UI::do_engine_start ()
1977 {
1978         try {
1979                 engine->start();
1980         }
1981
1982         catch (...) {
1983                 engine->stop ();
1984                 error << _("Unable to start the session running")
1985                       << endmsg;
1986                 unload_session ();
1987                 return -2;
1988         }
1989
1990         return 0;
1991 }
1992
1993 void
1994 ARDOUR_UI::update_clocks ()
1995 {
1996         if (!editor || !editor->dragging_playhead()) {
1997                 Clock (_session->audible_frame(), false, editor->get_preferred_edit_position()); /* EMIT_SIGNAL */
1998         }
1999 }
2000
2001 void
2002 ARDOUR_UI::start_clocking ()
2003 {
2004         clock_signal_connection = RapidScreenUpdate.connect (sigc::mem_fun(*this, &ARDOUR_UI::update_clocks));
2005 }
2006
2007 void
2008 ARDOUR_UI::stop_clocking ()
2009 {
2010         clock_signal_connection.disconnect ();
2011 }
2012
2013 gint
2014 ARDOUR_UI::_blink (void *arg)
2015 {
2016         ((ARDOUR_UI *) arg)->blink ();
2017         return TRUE;
2018 }
2019
2020 void
2021 ARDOUR_UI::blink ()
2022 {
2023         Blink (blink_on = !blink_on); /* EMIT_SIGNAL */
2024 }
2025
2026 void
2027 ARDOUR_UI::start_blinking ()
2028 {
2029         /* Start the blink signal. Everybody with a blinking widget
2030            uses Blink to drive the widget's state.
2031         */
2032
2033         if (blink_timeout_tag < 0) {
2034                 blink_on = false;
2035                 blink_timeout_tag = g_timeout_add (240, _blink, this);
2036         }
2037 }
2038
2039 void
2040 ARDOUR_UI::stop_blinking ()
2041 {
2042         if (blink_timeout_tag >= 0) {
2043                 g_source_remove (blink_timeout_tag);
2044                 blink_timeout_tag = -1;
2045         }
2046 }
2047
2048
2049 /** Ask the user for the name of a new snapshot and then take it.
2050  */
2051
2052 void
2053 ARDOUR_UI::snapshot_session (bool switch_to_it)
2054 {
2055         ArdourPrompter prompter (true);
2056         string snapname;
2057
2058         prompter.set_name ("Prompter");
2059         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2060         prompter.set_title (_("Take Snapshot"));
2061         prompter.set_prompt (_("Name of new snapshot"));
2062
2063         if (!switch_to_it) {
2064                 char timebuf[128];
2065                 time_t n;
2066                 struct tm local_time;
2067
2068                 time (&n);
2069                 localtime_r (&n, &local_time);
2070                 strftime (timebuf, sizeof(timebuf), "%FT%H.%M.%S", &local_time);
2071                 prompter.set_initial_text (timebuf);
2072         }
2073
2074   again:
2075         switch (prompter.run()) {
2076         case RESPONSE_ACCEPT:
2077         {
2078                 prompter.get_result (snapname);
2079
2080                 bool do_save = (snapname.length() != 0);
2081
2082                 if (do_save) {
2083                         char illegal = Session::session_name_is_legal(snapname);
2084                         if (illegal) {
2085                                 MessageDialog msg (string_compose (_("To ensure compatibility with various systems\n"
2086                                                      "snapshot names may not contain a '%1' character"), illegal));
2087                                 msg.run ();
2088                                 goto again;
2089                         }
2090                 }
2091
2092                 vector<std::string> p;
2093                 get_state_files_in_directory (_session->session_directory().root_path(), p);
2094                 vector<string> n = get_file_names_no_extension (p);
2095                 if (find (n.begin(), n.end(), snapname) != n.end()) {
2096
2097                         ArdourDialog confirm (_("Confirm Snapshot Overwrite"), true);
2098                         Label m (_("A snapshot already exists with that name.  Do you want to overwrite it?"));
2099                         confirm.get_vbox()->pack_start (m, true, true);
2100                         confirm.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2101                         confirm.add_button (_("Overwrite"), Gtk::RESPONSE_ACCEPT);
2102                         confirm.show_all ();
2103                         switch (confirm.run()) {
2104                         case RESPONSE_CANCEL:
2105                                 do_save = false;
2106                         }
2107                 }
2108
2109                 if (do_save) {
2110                         save_state (snapname, switch_to_it);
2111                 }
2112                 break;
2113         }
2114
2115         default:
2116                 break;
2117         }
2118 }
2119
2120 /** Ask the user for a new session name and then rename the session to it.
2121  */
2122
2123 void
2124 ARDOUR_UI::rename_session ()
2125 {
2126         if (!_session) {
2127                 return;
2128         }
2129
2130         ArdourPrompter prompter (true);
2131         string name;
2132
2133         prompter.set_name ("Prompter");
2134         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2135         prompter.set_title (_("Rename Session"));
2136         prompter.set_prompt (_("New session name"));
2137
2138   again:
2139         switch (prompter.run()) {
2140         case RESPONSE_ACCEPT:
2141         {
2142                 prompter.get_result (name);
2143
2144                 bool do_rename = (name.length() != 0);
2145
2146                 if (do_rename) {
2147                         char illegal = Session::session_name_is_legal (name);
2148
2149                         if (illegal) {
2150                                 MessageDialog msg (string_compose (_("To ensure compatibility with various systems\n"
2151                                                                      "session names may not contain a '%1' character"), illegal));
2152                                 msg.run ();
2153                                 goto again;
2154                         }
2155
2156                         switch (_session->rename (name)) {
2157                         case -1: {
2158                                 MessageDialog msg (_("That name is already in use by another directory/folder. Please try again."));
2159                                 msg.set_position (WIN_POS_MOUSE);
2160                                 msg.run ();
2161                                 goto again;
2162                                 break;
2163                         }
2164                         case 0:
2165                                 break;
2166                         default: {
2167                                 MessageDialog msg (_("Renaming this session failed.\nThings could be seriously messed up at this point"));
2168                                 msg.set_position (WIN_POS_MOUSE);
2169                                 msg.run ();
2170                                 break;
2171                         }
2172                         }
2173                 }
2174                 
2175                 break;
2176         }
2177
2178         default:
2179                 break;
2180         }
2181 }
2182
2183 void
2184 ARDOUR_UI::save_state (const string & name, bool switch_to_it)
2185 {
2186         XMLNode* node = new XMLNode (X_("UI"));
2187
2188         for (list<WindowProxyBase*>::iterator i = _window_proxies.begin(); i != _window_proxies.end(); ++i) {
2189                 if (!(*i)->rc_configured()) {
2190                         node->add_child_nocopy (*((*i)->get_state ()));
2191                 }
2192         }
2193
2194         node->add_child_nocopy (gui_object_state->get_state());
2195
2196         _session->add_extra_xml (*node);
2197
2198         save_state_canfail (name, switch_to_it);
2199 }
2200
2201 int
2202 ARDOUR_UI::save_state_canfail (string name, bool switch_to_it)
2203 {
2204         if (_session) {
2205                 int ret;
2206
2207                 if (name.length() == 0) {
2208                         name = _session->snap_name();
2209                 }
2210
2211                 if ((ret = _session->save_state (name, false, switch_to_it)) != 0) {
2212                         return ret;
2213                 }
2214         }
2215
2216         save_ardour_state (); /* XXX cannot fail? yeah, right ... */
2217         return 0;
2218 }
2219
2220 void
2221 ARDOUR_UI::primary_clock_value_changed ()
2222 {
2223         if (_session) {
2224                 _session->request_locate (primary_clock->current_time ());
2225         }
2226 }
2227
2228 void
2229 ARDOUR_UI::big_clock_value_changed ()
2230 {
2231         if (_session) {
2232                 _session->request_locate (big_clock->current_time ());
2233         }
2234 }
2235
2236 void
2237 ARDOUR_UI::secondary_clock_value_changed ()
2238 {
2239         if (_session) {
2240                 _session->request_locate (secondary_clock->current_time ());
2241         }
2242 }
2243
2244 void
2245 ARDOUR_UI::transport_rec_enable_blink (bool onoff)
2246 {
2247         if (_session == 0) {
2248                 return;
2249         }
2250
2251         if (_session->step_editing()) {
2252                 return;
2253         }
2254
2255         Session::RecordState const r = _session->record_status ();
2256         bool const h = _session->have_rec_enabled_track ();
2257
2258         if (r == Session::Enabled || (r == Session::Recording && !h)) {
2259                 if (onoff) {
2260                         rec_button.set_active_state (Gtkmm2ext::ExplicitActive);
2261                 } else {
2262                         rec_button.set_active_state (Gtkmm2ext::ImplicitActive);
2263                 }
2264         } else if (r == Session::Recording && h) {
2265                 rec_button.set_active_state (Gtkmm2ext::ExplicitActive);
2266         } else {
2267                 rec_button.unset_active_state ();
2268         }
2269 }
2270
2271 void
2272 ARDOUR_UI::save_template ()
2273 {
2274         ArdourPrompter prompter (true);
2275         string name;
2276
2277         if (!check_audioengine()) {
2278                 return;
2279         }
2280
2281         prompter.set_name (X_("Prompter"));
2282         prompter.set_title (_("Save Template"));
2283         prompter.set_prompt (_("Name for template:"));
2284         prompter.set_initial_text(_session->name() + _("-template"));
2285         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2286
2287         switch (prompter.run()) {
2288         case RESPONSE_ACCEPT:
2289                 prompter.get_result (name);
2290
2291                 if (name.length()) {
2292                         _session->save_template (name);
2293                 }
2294                 break;
2295
2296         default:
2297                 break;
2298         }
2299 }
2300
2301 void
2302 ARDOUR_UI::edit_metadata ()
2303 {
2304         SessionMetadataEditor dialog;
2305         dialog.set_session (_session);
2306         editor->ensure_float (dialog);
2307         dialog.run ();
2308 }
2309
2310 void
2311 ARDOUR_UI::import_metadata ()
2312 {
2313         SessionMetadataImporter dialog;
2314         dialog.set_session (_session);
2315         editor->ensure_float (dialog);
2316         dialog.run ();
2317 }
2318
2319 bool
2320 ARDOUR_UI::ask_about_loading_existing_session (const std::string& session_path)
2321 {
2322         std::string str = string_compose (_("This session\n%1\nalready exists. Do you want to open it?"), session_path);
2323
2324         MessageDialog msg (str,
2325                            false,
2326                            Gtk::MESSAGE_WARNING,
2327                            Gtk::BUTTONS_YES_NO,
2328                            true);
2329
2330
2331         msg.set_name (X_("OpenExistingDialog"));
2332         msg.set_title (_("Open Existing Session"));
2333         msg.set_wmclass (X_("existing_session"), PROGRAM_NAME);
2334         msg.set_position (Gtk::WIN_POS_MOUSE);
2335         pop_back_splash (msg);
2336
2337         switch (msg.run()) {
2338         case RESPONSE_YES:
2339                 return true;
2340                 break;
2341         }
2342         return false;
2343 }
2344
2345 int
2346 ARDOUR_UI::build_session_from_nsd (const std::string& session_path, const std::string& session_name)
2347 {
2348         BusProfile bus_profile;
2349
2350         if (Profile->get_sae()) {
2351
2352                 bus_profile.master_out_channels = 2;
2353                 bus_profile.input_ac = AutoConnectPhysical;
2354                 bus_profile.output_ac = AutoConnectMaster;
2355                 bus_profile.requested_physical_in = 0; // use all available
2356                 bus_profile.requested_physical_out = 0; // use all available
2357
2358         } else {
2359
2360                 /* get settings from advanced section of NSD */
2361
2362                 if (_startup->create_master_bus()) {
2363                         bus_profile.master_out_channels = (uint32_t) _startup->master_channel_count();
2364                 } else {
2365                         bus_profile.master_out_channels = 0;
2366                 }
2367
2368                 if (_startup->connect_inputs()) {
2369                         bus_profile.input_ac = AutoConnectPhysical;
2370                 } else {
2371                         bus_profile.input_ac = AutoConnectOption (0);
2372                 }
2373
2374                 bus_profile.output_ac = AutoConnectOption (0);
2375
2376                 if (_startup->connect_outputs ()) {
2377                         if (_startup->connect_outs_to_master()) {
2378                                 bus_profile.output_ac = AutoConnectMaster;
2379                         } else if (_startup->connect_outs_to_physical()) {
2380                                 bus_profile.output_ac = AutoConnectPhysical;
2381                         }
2382                 }
2383
2384                 bus_profile.requested_physical_in = (uint32_t) _startup->input_limit_count();
2385                 bus_profile.requested_physical_out = (uint32_t) _startup->output_limit_count();
2386         }
2387
2388         if (build_session (session_path, session_name, bus_profile)) {
2389                 return -1;
2390         }
2391
2392         return 0;
2393 }
2394
2395 void
2396 ARDOUR_UI::idle_load (const std::string& path)
2397 {
2398         if (_session) {
2399                 if (Glib::file_test (path, Glib::FILE_TEST_IS_DIR)) {
2400                         /* /path/to/foo => /path/to/foo, foo */
2401                         load_session (path, basename_nosuffix (path));
2402                 } else {
2403                         /* /path/to/foo/foo.ardour => /path/to/foo, foo */
2404                         load_session (Glib::path_get_dirname (path), basename_nosuffix (path));
2405                 }
2406
2407         } else {
2408                 ARDOUR_COMMAND_LINE::session_name = path;
2409         }
2410 }
2411
2412 /** @param quit_on_cancel true if exit() should be called if the user clicks `cancel' in the new session dialog */
2413 int
2414 ARDOUR_UI::get_session_parameters (bool quit_on_cancel, bool should_be_new, string load_template)
2415 {
2416         string session_name;
2417         string session_path;
2418         string template_name;
2419         int ret = -1;
2420         bool likely_new = false;
2421
2422         /* deal with any existing DIRTY session now, rather than later. don't
2423          * treat a non-dirty session this way, so that it stays visible 
2424          * as we bring up the new session dialog.
2425          */
2426
2427         if (_session && _session->dirty()) {
2428                 if (unload_session (false)) {
2429                         /* unload cancelled by user */
2430                         return 0;
2431                 }
2432                 ARDOUR_COMMAND_LINE::session_name = "";
2433         }
2434
2435         if (!load_template.empty()) {
2436                 should_be_new = true;
2437                 template_name = load_template;
2438         }
2439
2440         while (ret != 0) {
2441
2442                 if (!ARDOUR_COMMAND_LINE::session_name.empty()) {
2443
2444                         /* if they named a specific statefile, use it, otherwise they are
2445                            just giving a session folder, and we want to use it as is
2446                            to find the session.
2447                         */
2448
2449                         string::size_type suffix = ARDOUR_COMMAND_LINE::session_name.find (statefile_suffix);
2450
2451                         if (suffix != string::npos) {
2452                                 session_path = Glib::path_get_dirname (ARDOUR_COMMAND_LINE::session_name);
2453                                 session_name = ARDOUR_COMMAND_LINE::session_name.substr (0, suffix);
2454                                 session_name = Glib::path_get_basename (session_name);
2455                         } else {
2456                                 session_path = ARDOUR_COMMAND_LINE::session_name;
2457                                 session_name = Glib::path_get_basename (ARDOUR_COMMAND_LINE::session_name);
2458                         }
2459                 } else {
2460                         session_path = "";
2461                         session_name = "";
2462                 }
2463
2464                 delete _startup;
2465                 _startup = new ArdourStartup (should_be_new, session_name, session_path, load_template);
2466                 
2467                 if (!_startup->ready_without_display()) {
2468                         _startup->present ();
2469                         main().run();
2470                         _startup->hide ();
2471                 }
2472                 
2473                 switch (_startup->response()) {
2474                 case RESPONSE_OK:
2475                         break;
2476                 default:
2477                         if (quit_on_cancel) {
2478                                 exit (1);
2479                         } else {
2480                                 return ret;
2481                         }
2482                 }
2483
2484                 /* if we run the startup dialog again, offer more than just "new session" */
2485                 
2486                 should_be_new = false;
2487                 
2488                 session_name = _startup->session_name (likely_new);
2489                 
2490                 string::size_type suffix = session_name.find (statefile_suffix);
2491                 
2492                 if (suffix != string::npos) {
2493                         session_name = session_name.substr (0, suffix);
2494                 }
2495                 
2496                 /* this shouldn't happen, but we catch it just in case it does */
2497                 
2498                 if (session_name.empty()) {
2499                         continue;
2500                 }
2501                 
2502                 if (_startup->use_session_template()) {
2503                         template_name = _startup->session_template_name();
2504                         _session_is_new = true;
2505                 }
2506                 
2507                 if (session_name[0] == G_DIR_SEPARATOR ||
2508                     (session_name.length() > 2 && session_name[0] == '.' && session_name[1] == G_DIR_SEPARATOR) ||
2509                     (session_name.length() > 3 && session_name[0] == '.' && session_name[1] == '.' && session_name[2] == G_DIR_SEPARATOR)) {
2510                         
2511                         /* absolute path or cwd-relative path specified for session name: infer session folder
2512                            from what was given.
2513                         */
2514                         
2515                         session_path = Glib::path_get_dirname (session_name);
2516                         session_name = Glib::path_get_basename (session_name);
2517                         
2518                 } else {
2519
2520                         session_path = _startup->session_folder();
2521                         
2522                         char illegal = Session::session_name_is_legal (session_name);
2523                         
2524                         if (illegal) {
2525                                 MessageDialog msg (*_startup,
2526                                                    string_compose (_("To ensure compatibility with various systems\n"
2527                                                                      "session names may not contain a '%1' character"),
2528                                                                    illegal));
2529                                 msg.run ();
2530                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2531                                 continue;
2532                         }
2533                 }
2534         
2535                 if (create_engine ()) {
2536                         break;
2537                 }
2538
2539                 if (Glib::file_test (session_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
2540
2541                         if (likely_new) {
2542
2543                                 std::string existing = Glib::build_filename (session_path, session_name);
2544
2545                                 if (!ask_about_loading_existing_session (existing)) {
2546                                         ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2547                                         continue;
2548                                 }
2549                         }
2550
2551                         _session_is_new = false;
2552
2553                 } else {
2554
2555                         if (!likely_new) {
2556                                 if (_startup) {
2557                                         pop_back_splash (*_startup);
2558                                 } else {
2559                                         hide_splash ();
2560                                 }
2561
2562                                 MessageDialog msg (string_compose (_("There is no existing session at \"%1\""), session_path));
2563                                 msg.run ();
2564                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2565                                 continue;
2566                         }
2567
2568                         char illegal = Session::session_name_is_legal(session_name);
2569                         if (illegal) {
2570                                 pop_back_splash (*_startup);
2571                                 MessageDialog msg (*_startup, string_compose(_("To ensure compatibility with various systems\n"
2572                                                      "session names may not contain a '%1' character"), illegal));
2573                                 msg.run ();
2574                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2575                                 continue;
2576                         }
2577
2578                         _session_is_new = true;
2579                 }
2580
2581                 if (likely_new && template_name.empty()) {
2582
2583                         ret = build_session_from_nsd (session_path, session_name);
2584
2585                 } else {
2586
2587                         ret = load_session (session_path, session_name, template_name);
2588
2589                         if (ret == -2) {
2590                                 /* not connected to the AudioEngine, so quit to avoid an infinite loop */
2591                                 exit (1);
2592                         }
2593
2594                         if (!ARDOUR_COMMAND_LINE::immediate_save.empty()) {
2595                                 _session->save_state (ARDOUR_COMMAND_LINE::immediate_save, false);
2596                                 exit (1);
2597                         }
2598                 }
2599         }
2600
2601         return ret;
2602 }
2603
2604 void
2605 ARDOUR_UI::close_session()
2606 {
2607         if (!check_audioengine()) {
2608                 return;
2609         }
2610
2611         if (unload_session (true)) {
2612                 return;
2613         }
2614
2615         ARDOUR_COMMAND_LINE::session_name = "";
2616
2617         if (get_session_parameters (true, false)) {
2618                 exit (1);
2619         }
2620
2621         goto_editor_window ();
2622 }
2623
2624 /** @param snap_name Snapshot name (without .ardour suffix).
2625  *  @return -2 if the load failed because we are not connected to the AudioEngine.
2626  */
2627 int
2628 ARDOUR_UI::load_session (const std::string& path, const std::string& snap_name, std::string mix_template)
2629 {
2630         Session *new_session;
2631         int unload_status;
2632         int retval = -1;
2633
2634         session_loaded = false;
2635
2636         if (!check_audioengine()) {
2637                 return -2;
2638         }
2639
2640         unload_status = unload_session ();
2641
2642         if (unload_status < 0) {
2643                 goto out;
2644         } else if (unload_status > 0) {
2645                 retval = 0;
2646                 goto out;
2647         }
2648
2649         loading_message (string_compose (_("Please wait while %1 loads your session"), PROGRAM_NAME));
2650
2651         try {
2652                 new_session = new Session (*engine, path, snap_name, 0, mix_template);
2653         }
2654
2655         /* this one is special */
2656
2657         catch (AudioEngine::PortRegistrationFailure& err) {
2658
2659                 MessageDialog msg (err.what(),
2660                                    true,
2661                                    Gtk::MESSAGE_INFO,
2662                                    Gtk::BUTTONS_CLOSE);
2663
2664                 msg.set_title (_("Port Registration Error"));
2665                 msg.set_secondary_text (_("Click the Close button to try again."));
2666                 msg.set_position (Gtk::WIN_POS_CENTER);
2667                 pop_back_splash (msg);
2668                 msg.present ();
2669
2670                 int response = msg.run ();
2671
2672                 msg.hide ();
2673
2674                 switch (response) {
2675                 case RESPONSE_CANCEL:
2676                         exit (1);
2677                 default:
2678                         break;
2679                 }
2680                 goto out;
2681         }
2682
2683         catch (...) {
2684
2685                 MessageDialog msg (string_compose(
2686                                            _("Session \"%1 (snapshot %2)\" did not load successfully"),
2687                                            path, snap_name),
2688                                    true,
2689                                    Gtk::MESSAGE_INFO,
2690                                    BUTTONS_OK);
2691
2692                 msg.set_title (_("Loading Error"));
2693                 msg.set_secondary_text (_("Click the Refresh button to try again."));
2694                 msg.add_button (Stock::REFRESH, 1);
2695                 msg.set_position (Gtk::WIN_POS_CENTER);
2696                 pop_back_splash (msg);
2697                 msg.present ();
2698
2699                 int response = msg.run ();
2700
2701                 switch (response) {
2702                 case 1:
2703                         break;
2704                 default:
2705                         exit (1);
2706                 }
2707
2708                 msg.hide ();
2709
2710                 goto out;
2711         }
2712
2713         {
2714                 list<string> const u = new_session->unknown_processors ();
2715                 if (!u.empty()) {
2716                         MissingPluginDialog d (_session, u);
2717                         d.run ();
2718                 }
2719         }
2720
2721         /* Now the session been created, add the transport controls */
2722         new_session->add_controllable(roll_controllable);
2723         new_session->add_controllable(stop_controllable);
2724         new_session->add_controllable(goto_start_controllable);
2725         new_session->add_controllable(goto_end_controllable);
2726         new_session->add_controllable(auto_loop_controllable);
2727         new_session->add_controllable(play_selection_controllable);
2728         new_session->add_controllable(rec_controllable);
2729
2730         set_session (new_session);
2731
2732         session_loaded = true;
2733
2734         goto_editor_window ();
2735
2736         if (_session) {
2737                 _session->set_clean ();
2738         }
2739
2740         flush_pending ();
2741         retval = 0;
2742
2743   out:
2744         return retval;
2745 }
2746
2747 int
2748 ARDOUR_UI::build_session (const std::string& path, const std::string& snap_name, BusProfile& bus_profile)
2749 {
2750         Session *new_session;
2751         int x;
2752
2753         if (!check_audioengine()) {
2754                 return -1;
2755         }
2756
2757         session_loaded = false;
2758
2759         x = unload_session ();
2760
2761         if (x < 0) {
2762                 return -1;
2763         } else if (x > 0) {
2764                 return 0;
2765         }
2766
2767         _session_is_new = true;
2768
2769         try {
2770                 new_session = new Session (*engine, path, snap_name, &bus_profile);
2771         }
2772
2773         catch (...) {
2774
2775                 MessageDialog msg (string_compose(_("Could not create session in \"%1\""), path));
2776                 pop_back_splash (msg);
2777                 msg.run ();
2778                 return -1;
2779         }
2780
2781         /* Give the new session the default GUI state, if such things exist */
2782
2783         XMLNode* n;
2784         n = Config->instant_xml (X_("Editor"));
2785         if (n) {
2786                 new_session->add_instant_xml (*n, false);
2787         }
2788         n = Config->instant_xml (X_("Mixer"));
2789         if (n) {
2790                 new_session->add_instant_xml (*n, false);
2791         }
2792
2793         /* Put the playhead at 0 and scroll fully left */
2794         n = new_session->instant_xml (X_("Editor"));
2795         if (n) {
2796                 n->add_property (X_("playhead"), X_("0"));
2797                 n->add_property (X_("left-frame"), X_("0"));
2798         }
2799
2800         set_session (new_session);
2801
2802         session_loaded = true;
2803
2804         new_session->save_state(new_session->name());
2805
2806         return 0;
2807 }
2808
2809 void
2810 ARDOUR_UI::launch_chat ()
2811 {
2812 #ifdef __APPLE__
2813         open_uri("http://webchat.freenode.net/?channels=ardour-osx");
2814 #else
2815         open_uri("http://webchat.freenode.net/?channels=ardour");
2816 #endif
2817 }
2818
2819 void
2820 ARDOUR_UI::show_about ()
2821 {
2822         if (about == 0) {
2823                 about = new About;
2824                 about->signal_response().connect (sigc::mem_fun (*this, &ARDOUR_UI::about_signal_response));
2825         }
2826
2827         about->set_transient_for(*editor);
2828         about->show_all ();
2829 }
2830
2831 void
2832 ARDOUR_UI::launch_manual ()
2833 {
2834         PBD::open_uri("http://ardour.org/flossmanual");
2835 }
2836
2837 void
2838 ARDOUR_UI::launch_reference ()
2839 {
2840         PBD::open_uri ("http://ardour.org/refmanual");
2841 }
2842
2843 void
2844 ARDOUR_UI::hide_about ()
2845 {
2846         if (about) {
2847                 about->get_window()->set_cursor ();
2848                 about->hide ();
2849         }
2850 }
2851
2852 void
2853 ARDOUR_UI::about_signal_response (int /*response*/)
2854 {
2855         hide_about();
2856 }
2857
2858 void
2859 ARDOUR_UI::loading_message (const std::string& msg)
2860 {
2861         if (ARDOUR_COMMAND_LINE::no_splash) {
2862                 return;
2863         }
2864
2865         if (!splash) {
2866                 show_splash ();
2867         }
2868
2869         splash->message (msg);
2870 }
2871
2872 void
2873 ARDOUR_UI::show_splash ()
2874 {
2875         if (splash == 0) {
2876                 try {
2877                         splash = new Splash;
2878                 } catch (...) {
2879                         return;
2880                 }
2881         }
2882
2883         splash->display ();
2884 }
2885
2886 void
2887 ARDOUR_UI::hide_splash ()
2888 {
2889         delete splash;
2890         splash = 0;
2891 }
2892
2893 void
2894 ARDOUR_UI::display_cleanup_results (ARDOUR::CleanupReport& rep, const gchar* list_title,
2895                                     const string& plural_msg, const string& singular_msg)
2896 {
2897         size_t removed;
2898
2899         removed = rep.paths.size();
2900
2901         if (removed == 0) {
2902                 MessageDialog msgd (*editor,
2903                                     _("No files were ready for clean-up"),
2904                                     true,
2905                                     Gtk::MESSAGE_INFO,
2906                                     Gtk::BUTTONS_OK);
2907                 msgd.set_title (_("Clean-up"));
2908                 msgd.set_secondary_text (_("If this seems suprising, \n\
2909 check for any existing snapshots.\n\
2910 These may still include regions that\n\
2911 require some unused files to continue to exist."));
2912
2913                 msgd.run ();
2914                 return;
2915         }
2916
2917         ArdourDialog results (_("Clean-up"), true, false);
2918
2919         struct CleanupResultsModelColumns : public Gtk::TreeModel::ColumnRecord {
2920             CleanupResultsModelColumns() {
2921                     add (visible_name);
2922                     add (fullpath);
2923             }
2924             Gtk::TreeModelColumn<std::string> visible_name;
2925             Gtk::TreeModelColumn<std::string> fullpath;
2926         };
2927
2928
2929         CleanupResultsModelColumns results_columns;
2930         Glib::RefPtr<Gtk::ListStore> results_model;
2931         Gtk::TreeView results_display;
2932
2933         results_model = ListStore::create (results_columns);
2934         results_display.set_model (results_model);
2935         results_display.append_column (list_title, results_columns.visible_name);
2936
2937         results_display.set_name ("CleanupResultsList");
2938         results_display.set_headers_visible (true);
2939         results_display.set_headers_clickable (false);
2940         results_display.set_reorderable (false);
2941
2942         Gtk::ScrolledWindow list_scroller;
2943         Gtk::Label txt;
2944         Gtk::VBox dvbox;
2945         Gtk::HBox dhbox;  // the hbox for the image and text
2946         Gtk::HBox ddhbox; // the hbox we eventually pack into the dialog's vbox
2947         Gtk::Image* dimage = manage (new Gtk::Image(Stock::DIALOG_INFO,  Gtk::ICON_SIZE_DIALOG));
2948
2949         dimage->set_alignment(ALIGN_LEFT, ALIGN_TOP);
2950
2951         const string dead_directory = _session->session_directory().dead_path();
2952
2953         /* subst:
2954            %1 - number of files removed
2955            %2 - location of "dead"
2956            %3 - size of files affected
2957            %4 - prefix for "bytes" to produce sensible results (e.g. mega, kilo, giga)
2958         */
2959
2960         const char* bprefix;
2961         double space_adjusted = 0;
2962
2963         if (rep.space < 1000) {
2964                 bprefix = _("");
2965                 space_adjusted = rep.space;
2966         } else if (rep.space < 1000000) {
2967                 bprefix = _("kilo");
2968                 space_adjusted = truncf((float)rep.space / 1000.0);
2969         } else if (rep.space < 1000000 * 1000) {
2970                 bprefix = _("mega");
2971                 space_adjusted = truncf((float)rep.space / (1000.0 * 1000.0));
2972         } else {
2973                 bprefix = _("giga");
2974                 space_adjusted = truncf((float)rep.space / (1000.0 * 1000 * 1000.0));
2975         }
2976
2977         if (removed > 1) {
2978                 txt.set_markup (string_compose (plural_msg, removed, Glib::Markup::escape_text (dead_directory), space_adjusted, bprefix, PROGRAM_NAME));
2979         } else {
2980                 txt.set_markup (string_compose (singular_msg, removed, Glib::Markup::escape_text (dead_directory), space_adjusted, bprefix, PROGRAM_NAME));
2981         }
2982
2983         dhbox.pack_start (*dimage, true, false, 5);
2984         dhbox.pack_start (txt, true, false, 5);
2985
2986         for (vector<string>::iterator i = rep.paths.begin(); i != rep.paths.end(); ++i) {
2987                 TreeModel::Row row = *(results_model->append());
2988                 row[results_columns.visible_name] = *i;
2989                 row[results_columns.fullpath] = *i;
2990         }
2991
2992         list_scroller.add (results_display);
2993         list_scroller.set_size_request (-1, 150);
2994         list_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
2995
2996         dvbox.pack_start (dhbox, true, false, 5);
2997         dvbox.pack_start (list_scroller, true, false, 5);
2998         ddhbox.pack_start (dvbox, true, false, 5);
2999
3000         results.get_vbox()->pack_start (ddhbox, true, false, 5);
3001         results.add_button (Stock::CLOSE, RESPONSE_CLOSE);
3002         results.set_default_response (RESPONSE_CLOSE);
3003         results.set_position (Gtk::WIN_POS_MOUSE);
3004
3005         results_display.show();
3006         list_scroller.show();
3007         txt.show();
3008         dvbox.show();
3009         dhbox.show();
3010         ddhbox.show();
3011         dimage->show();
3012
3013         //results.get_vbox()->show();
3014         results.set_resizable (false);
3015
3016         results.run ();
3017
3018 }
3019
3020 void
3021 ARDOUR_UI::cleanup ()
3022 {
3023         if (_session == 0) {
3024                 /* shouldn't happen: menu item is insensitive */
3025                 return;
3026         }
3027
3028
3029         MessageDialog checker (_("Are you sure you want to clean-up?"),
3030                                 true,
3031                                 Gtk::MESSAGE_QUESTION,
3032                                 Gtk::BUTTONS_NONE);
3033
3034         checker.set_title (_("Clean-up"));
3035
3036         checker.set_secondary_text(_("Clean-up is a destructive operation.\n\
3037 ALL undo/redo information will be lost if you clean-up.\n\
3038 Clean-up will move all unused files to a \"dead\" location."));
3039
3040         checker.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3041         checker.add_button (_("Clean-up"), RESPONSE_ACCEPT);
3042         checker.set_default_response (RESPONSE_CANCEL);
3043
3044         checker.set_name (_("CleanupDialog"));
3045         checker.set_wmclass (X_("ardour_cleanup"), PROGRAM_NAME);
3046         checker.set_position (Gtk::WIN_POS_MOUSE);
3047
3048         switch (checker.run()) {
3049         case RESPONSE_ACCEPT:
3050                 break;
3051         default:
3052                 return;
3053         }
3054
3055         ARDOUR::CleanupReport rep;
3056
3057         editor->prepare_for_cleanup ();
3058
3059         /* do not allow flush until a session is reloaded */
3060
3061         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Main"), X_("FlushWastebasket"));
3062         if (act) {
3063                 act->set_sensitive (false);
3064         }
3065
3066         if (_session->cleanup_sources (rep)) {
3067                 editor->finish_cleanup ();
3068                 return;
3069         }
3070
3071         editor->finish_cleanup ();
3072
3073         checker.hide();
3074         display_cleanup_results (rep,
3075                                  _("Cleaned Files"),
3076                                  _("\
3077 The following %1 files were not in use and \n\
3078 have been moved to: %2\n\n\
3079 After a restart of %5\n\n\
3080 <span face=\"mono\">Session -> Clean-up -> Flush Wastebasket</span>\n\n\
3081 will release an additional %3 %4bytes of disk space.\n"),
3082                                  _("\
3083 The following file was not in use and \n\
3084 has been moved to: %2\n\n\
3085 After a restart of %5\n\n\
3086 <span face=\"mono\">Session -> Clean-up -> Flush Wastebasket</span>\n\n\
3087 will release an additional %3 %4bytes of disk space.\n"
3088                                          ));
3089
3090 }
3091
3092 void
3093 ARDOUR_UI::flush_trash ()
3094 {
3095         if (_session == 0) {
3096                 /* shouldn't happen: menu item is insensitive */
3097                 return;
3098         }
3099
3100         ARDOUR::CleanupReport rep;
3101
3102         if (_session->cleanup_trash_sources (rep)) {
3103                 return;
3104         }
3105
3106         display_cleanup_results (rep,
3107                                  _("deleted file"),
3108                                  _("The following %1 files were deleted from %2,\n\
3109 releasing %3 %4bytes of disk space"),
3110                                  _("The following file was deleted from %2,\n\
3111 releasing %3 %4bytes of disk space"));
3112 }
3113
3114 void
3115 ARDOUR_UI::add_route (Gtk::Window* float_window)
3116 {
3117         int count;
3118
3119         if (!_session) {
3120                 return;
3121         }
3122
3123         if (add_route_dialog == 0) {
3124                 add_route_dialog = new AddRouteDialog (_session);
3125                 add_route_dialog->set_position (WIN_POS_MOUSE);
3126                 if (float_window) {
3127                         add_route_dialog->set_transient_for (*float_window);
3128                 }
3129         }
3130
3131         if (add_route_dialog->is_visible()) {
3132                 /* we're already doing this */
3133                 return;
3134         }
3135
3136         ResponseType r = (ResponseType) add_route_dialog->run ();
3137
3138         add_route_dialog->hide();
3139
3140         switch (r) {
3141                 case RESPONSE_ACCEPT:
3142                         break;
3143                 default:
3144                         return;
3145                         break;
3146         }
3147
3148         if ((count = add_route_dialog->count()) <= 0) {
3149                 return;
3150         }
3151
3152         PBD::ScopedConnection idle_connection;
3153
3154         if (count > 8) {
3155                 ARDOUR::GUIIdle.connect (idle_connection, MISSING_INVALIDATOR, boost::bind (&Gtkmm2ext::UI::flush_pending, this), gui_context());
3156         }
3157
3158         string template_path = add_route_dialog->track_template();
3159
3160         if (!template_path.empty()) {
3161                 _session->new_route_from_template (count, template_path);
3162                 return;
3163         }
3164
3165         ChanCount input_chan= add_route_dialog->channels ();
3166         ChanCount output_chan;
3167         string name_template = add_route_dialog->name_template ();
3168         PluginInfoPtr instrument = add_route_dialog->requested_instrument ();
3169         RouteGroup* route_group = add_route_dialog->route_group ();
3170         AutoConnectOption oac = Config->get_output_auto_connect();
3171
3172         if (oac & AutoConnectMaster) {
3173                 output_chan.set (DataType::AUDIO, (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan.n_audio()));
3174                 output_chan.set (DataType::MIDI, 0);
3175         } else {
3176                 output_chan = input_chan;
3177         }
3178
3179         /* XXX do something with name template */
3180
3181         switch (add_route_dialog->type_wanted()) {
3182         case AddRouteDialog::AudioTrack:
3183                 session_add_audio_track (input_chan.n_audio(), output_chan.n_audio(), add_route_dialog->mode(), route_group, count, name_template);
3184                 break;
3185         case AddRouteDialog::MidiTrack:
3186                 session_add_midi_track (route_group, count, name_template, instrument);
3187                 break;
3188         case AddRouteDialog::MixedTrack:
3189                 session_add_mixed_track (input_chan, output_chan, route_group, count, name_template, instrument);
3190                 break;
3191         case AddRouteDialog::AudioBus:
3192                 session_add_audio_bus (input_chan.n_audio(), output_chan.n_audio(), route_group, count, name_template);
3193                 break;
3194         }
3195
3196         /* idle connection will end at scope end */
3197 }
3198
3199 XMLNode*
3200 ARDOUR_UI::mixer_settings () const
3201 {
3202         XMLNode* node = 0;
3203
3204         if (_session) {
3205                 node = _session->instant_xml(X_("Mixer"));
3206         } else {
3207                 node = Config->instant_xml(X_("Mixer"));
3208         }
3209
3210         if (!node) {
3211                 node = new XMLNode (X_("Mixer"));
3212         }
3213
3214         return node;
3215 }
3216
3217 XMLNode*
3218 ARDOUR_UI::editor_settings () const
3219 {
3220         XMLNode* node = 0;
3221
3222         if (_session) {
3223                 node = _session->instant_xml(X_("Editor"));
3224         } else {
3225                 node = Config->instant_xml(X_("Editor"));
3226         }
3227
3228         if (!node) {
3229                 if (getenv("ARDOUR_INSTANT_XML_PATH")) {
3230                         node = Config->instant_xml(getenv("ARDOUR_INSTANT_XML_PATH"));
3231                 }
3232         }
3233
3234         if (!node) {
3235                 node = new XMLNode (X_("Editor"));
3236         }
3237
3238         return node;
3239 }
3240
3241 XMLNode*
3242 ARDOUR_UI::keyboard_settings () const
3243 {
3244         XMLNode* node = 0;
3245
3246         node = Config->extra_xml(X_("Keyboard"));
3247
3248         if (!node) {
3249                 node = new XMLNode (X_("Keyboard"));
3250         }
3251
3252         return node;
3253 }
3254
3255 void
3256 ARDOUR_UI::create_xrun_marker (framepos_t where)
3257 {
3258         editor->mouse_add_new_marker (where, false, true);
3259 }
3260
3261 void
3262 ARDOUR_UI::halt_on_xrun_message ()
3263 {
3264         MessageDialog msg (*editor,
3265                            _("Recording was stopped because your system could not keep up."));
3266         msg.run ();
3267 }
3268
3269 void
3270 ARDOUR_UI::xrun_handler (framepos_t where)
3271 {
3272         if (!_session) {
3273                 return;
3274         }
3275
3276         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::xrun_handler, where)
3277
3278         if (_session && Config->get_create_xrun_marker() && _session->actively_recording()) {
3279                 create_xrun_marker(where);
3280         }
3281
3282         if (_session && Config->get_stop_recording_on_xrun() && _session->actively_recording()) {
3283                 halt_on_xrun_message ();
3284         }
3285 }
3286
3287 void
3288 ARDOUR_UI::disk_overrun_handler ()
3289 {
3290         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_overrun_handler)
3291
3292         if (!have_disk_speed_dialog_displayed) {
3293                 have_disk_speed_dialog_displayed = true;
3294                 MessageDialog* msg = new MessageDialog (*editor, string_compose (_("\
3295 The disk system on your computer\n\
3296 was not able to keep up with %1.\n\
3297 \n\
3298 Specifically, it failed to write data to disk\n\
3299 quickly enough to keep up with recording.\n"), PROGRAM_NAME));
3300                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
3301                 msg->show ();
3302         }
3303 }
3304
3305 void
3306 ARDOUR_UI::disk_underrun_handler ()
3307 {
3308         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_underrun_handler)
3309
3310         if (!have_disk_speed_dialog_displayed) {
3311                 have_disk_speed_dialog_displayed = true;
3312                 MessageDialog* msg = new MessageDialog (
3313                         *editor, string_compose (_("The disk system on your computer\n\
3314 was not able to keep up with %1.\n\
3315 \n\
3316 Specifically, it failed to read data from disk\n\
3317 quickly enough to keep up with playback.\n"), PROGRAM_NAME));
3318                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
3319                 msg->show ();
3320         }
3321 }
3322
3323 void
3324 ARDOUR_UI::disk_speed_dialog_gone (int /*ignored_response*/, MessageDialog* msg)
3325 {
3326         have_disk_speed_dialog_displayed = false;
3327         delete msg;
3328 }
3329
3330 void
3331 ARDOUR_UI::session_dialog (std::string msg)
3332 {
3333         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::session_dialog, msg)
3334
3335         MessageDialog* d;
3336
3337         if (editor) {
3338                 d = new MessageDialog (*editor, msg, false, MESSAGE_INFO, BUTTONS_OK, true);
3339         } else {
3340                 d = new MessageDialog (msg, false, MESSAGE_INFO, BUTTONS_OK, true);
3341         }
3342
3343         d->show_all ();
3344         d->run ();
3345         delete d;
3346 }
3347
3348 int
3349 ARDOUR_UI::pending_state_dialog ()
3350 {
3351         HBox* hbox = new HBox();
3352         Image* image = new Image (Stock::DIALOG_QUESTION, ICON_SIZE_DIALOG);
3353         ArdourDialog dialog (_("Crash Recovery"), true);
3354         Label  message (string_compose (_("\
3355 This session appears to have been in\n\
3356 middle of recording when ardour or\n\
3357 the computer was shutdown.\n\
3358 \n\
3359 %1 can recover any captured audio for\n\
3360 you, or it can ignore it. Please decide\n\
3361 what you would like to do.\n"), PROGRAM_NAME));
3362         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
3363         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
3364         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
3365         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
3366         dialog.add_button (_("Ignore crash data"), RESPONSE_REJECT);
3367         dialog.add_button (_("Recover from crash"), RESPONSE_ACCEPT);
3368         dialog.set_default_response (RESPONSE_ACCEPT);
3369         dialog.set_position (WIN_POS_CENTER);
3370         message.show();
3371         image->show();
3372         hbox->show();
3373
3374         switch (dialog.run ()) {
3375         case RESPONSE_ACCEPT:
3376                 return 1;
3377         default:
3378                 return 0;
3379         }
3380 }
3381
3382 int
3383 ARDOUR_UI::sr_mismatch_dialog (framecnt_t desired, framecnt_t actual)
3384 {
3385         HBox* hbox = new HBox();
3386         Image* image = new Image (Stock::DIALOG_QUESTION, ICON_SIZE_DIALOG);
3387         ArdourDialog dialog (_("Sample Rate Mismatch"), true);
3388         Label  message (string_compose (_("\
3389 This session was created with a sample rate of %1 Hz, but\n\
3390 %2 is currently running at %3 Hz.  If you load this session,\n\
3391 audio may be played at the wrong sample rate.\n"), desired, PROGRAM_NAME, actual));
3392
3393         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
3394         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
3395         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
3396         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
3397         dialog.add_button (_("Do not load session"), RESPONSE_REJECT);
3398         dialog.add_button (_("Load session anyway"), RESPONSE_ACCEPT);
3399         dialog.set_default_response (RESPONSE_ACCEPT);
3400         dialog.set_position (WIN_POS_CENTER);
3401         message.show();
3402         image->show();
3403         hbox->show();
3404
3405         switch (dialog.run ()) {
3406         case RESPONSE_ACCEPT:
3407                 return 0;
3408         default:
3409                 return 1;
3410         }
3411 }
3412
3413
3414 void
3415 ARDOUR_UI::disconnect_from_jack ()
3416 {
3417         if (engine) {
3418                 if (engine->disconnect_from_jack ()) {
3419                         MessageDialog msg (*editor, _("Could not disconnect from JACK"));
3420                         msg.run ();
3421                 }
3422
3423                 update_sample_rate (0);
3424         }
3425 }
3426
3427 void
3428 ARDOUR_UI::reconnect_to_jack ()
3429 {
3430         if (engine) {
3431                 if (engine->reconnect_to_jack ()) {
3432                         MessageDialog msg (*editor,  _("Could not reconnect to JACK"));
3433                         msg.run ();
3434                 }
3435
3436                 update_sample_rate (0);
3437         }
3438 }
3439
3440 void
3441 ARDOUR_UI::use_config ()
3442 {
3443         XMLNode* node = Config->extra_xml (X_("TransportControllables"));
3444         if (node) {
3445                 set_transport_controllable_state (*node);
3446         }
3447 }
3448
3449 void
3450 ARDOUR_UI::update_transport_clocks (framepos_t pos)
3451 {
3452         if (Config->get_primary_clock_delta_edit_cursor()) {
3453                 primary_clock->set (pos, false, editor->get_preferred_edit_position());
3454         } else {
3455                 primary_clock->set (pos);
3456         }
3457
3458         if (Config->get_secondary_clock_delta_edit_cursor()) {
3459                 secondary_clock->set (pos, false, editor->get_preferred_edit_position());
3460         } else {
3461                 secondary_clock->set (pos);
3462         }
3463
3464         if (big_clock_window->get()) {
3465                 big_clock->set (pos);
3466         }
3467 }
3468
3469
3470 void
3471 ARDOUR_UI::step_edit_status_change (bool yn)
3472 {
3473         // XXX should really store pre-step edit status of things
3474         // we make insensitive
3475
3476         if (yn) {
3477                 rec_button.set_active_state (Gtkmm2ext::ImplicitActive);
3478                 rec_button.set_sensitive (false);
3479         } else {
3480                 rec_button.unset_active_state ();;
3481                 rec_button.set_sensitive (true);
3482         }
3483 }
3484
3485 void
3486 ARDOUR_UI::record_state_changed ()
3487 {
3488         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::record_state_changed);
3489
3490         if (!_session || !big_clock_window->get()) {
3491                 /* why bother - the clock isn't visible */
3492                 return;
3493         }
3494
3495         if (_session->record_status () == Session::Recording && _session->have_rec_enabled_track ()) {
3496                 big_clock->set_active (true);
3497         } else {
3498                 big_clock->set_active (false);
3499         }
3500 }
3501
3502 bool
3503 ARDOUR_UI::first_idle ()
3504 {
3505         if (_session) {
3506                 _session->allow_auto_play (true);
3507         }
3508
3509         if (editor) {
3510                 editor->first_idle();
3511         }
3512
3513         Keyboard::set_can_save_keybindings (true);
3514         return false;
3515 }
3516
3517 void
3518 ARDOUR_UI::store_clock_modes ()
3519 {
3520         XMLNode* node = new XMLNode(X_("ClockModes"));
3521
3522         for (vector<AudioClock*>::iterator x = AudioClock::clocks.begin(); x != AudioClock::clocks.end(); ++x) {
3523                 XMLNode* child = new XMLNode (X_("Clock"));
3524                 
3525                 child->add_property (X_("name"), (*x)->name());
3526                 child->add_property (X_("mode"), enum_2_string ((*x)->mode()));
3527                 child->add_property (X_("on"), ((*x)->off() ? X_("no") : X_("yes")));
3528
3529                 node->add_child_nocopy (*child);
3530         }
3531
3532         _session->add_extra_xml (*node);
3533         _session->set_dirty ();
3534 }
3535
3536 ARDOUR_UI::TransportControllable::TransportControllable (std::string name, ARDOUR_UI& u, ToggleType tp)
3537         : Controllable (name), ui (u), type(tp)
3538 {
3539
3540 }
3541
3542 void
3543 ARDOUR_UI::TransportControllable::set_value (double val)
3544 {
3545         if (val < 0.5) {
3546                 /* do nothing: these are radio-style actions */
3547                 return;
3548         }
3549
3550         const char *action = 0;
3551
3552         switch (type) {
3553         case Roll:
3554                 action = X_("Roll");
3555                 break;
3556         case Stop:
3557                 action = X_("Stop");
3558                 break;
3559         case GotoStart:
3560                 action = X_("GotoStart");
3561                 break;
3562         case GotoEnd:
3563                 action = X_("GotoEnd");
3564                 break;
3565         case AutoLoop:
3566                 action = X_("Loop");
3567                 break;
3568         case PlaySelection:
3569                 action = X_("PlaySelection");
3570                 break;
3571         case RecordEnable:
3572                 action = X_("Record");
3573                 break;
3574         default:
3575                 break;
3576         }
3577
3578         if (action == 0) {
3579                 return;
3580         }
3581
3582         Glib::RefPtr<Action> act = ActionManager::get_action ("Transport", action);
3583
3584         if (act) {
3585                 act->activate ();
3586         }
3587 }
3588
3589 double
3590 ARDOUR_UI::TransportControllable::get_value (void) const
3591 {
3592         float val = 0.0;
3593
3594         switch (type) {
3595         case Roll:
3596                 break;
3597         case Stop:
3598                 break;
3599         case GotoStart:
3600                 break;
3601         case GotoEnd:
3602                 break;
3603         case AutoLoop:
3604                 break;
3605         case PlaySelection:
3606                 break;
3607         case RecordEnable:
3608                 break;
3609         default:
3610                 break;
3611         }
3612
3613         return val;
3614 }
3615
3616 void
3617 ARDOUR_UI::setup_profile ()
3618 {
3619         if (gdk_screen_width() < 1200 || getenv ("ARDOUR_NARROW_SCREEN")) {
3620                 Profile->set_small_screen ();
3621         }
3622
3623         if (getenv ("ARDOUR_SAE")) {
3624                 Profile->set_sae ();
3625                 Profile->set_single_package ();
3626         }
3627 }
3628
3629 void
3630 ARDOUR_UI::toggle_translations ()
3631 {
3632         using namespace Glib;
3633
3634         RefPtr<Action> act = ActionManager::get_action (X_("Main"), X_("EnableTranslation"));
3635         if (act) {
3636                 RefPtr<ToggleAction> ract = RefPtr<ToggleAction>::cast_dynamic (act);
3637                 if (ract) {
3638
3639                         string i18n_killer = ARDOUR::translation_kill_path();
3640
3641                         bool already_enabled = !ARDOUR::translations_are_disabled ();
3642
3643                         if (ract->get_active ()) {
3644                                 /* we don't care about errors */
3645                                 int fd = ::open (i18n_killer.c_str(), O_RDONLY|O_CREAT, 0644);
3646                                 close (fd);
3647                         } else {
3648                                 /* we don't care about errors */
3649                                 unlink (i18n_killer.c_str());
3650                         }
3651
3652                         if (already_enabled != ract->get_active()) {
3653                                 MessageDialog win (already_enabled ? _("Translations disabled") : _("Translations enabled"),
3654                                                    false,
3655                                                    Gtk::MESSAGE_WARNING,
3656                                                    Gtk::BUTTONS_OK);
3657                                 win.set_secondary_text (string_compose (_("You must restart %1 for this to take effect."), PROGRAM_NAME));
3658                                 win.set_position (Gtk::WIN_POS_CENTER);
3659                                 win.present ();
3660                                 win.run ();
3661                         }
3662                 }
3663         }
3664 }
3665
3666 /** Add a window proxy to our list, so that its state will be saved.
3667  *  This call also causes the window to be created and opened if its
3668  *  state was saved as `visible'.
3669  */
3670 void
3671 ARDOUR_UI::add_window_proxy (WindowProxyBase* p)
3672 {
3673         _window_proxies.push_back (p);
3674         p->maybe_show ();
3675 }
3676
3677 /** Remove a window proxy from our list.  Must be called if a WindowProxy
3678  *  is deleted, to prevent hanging pointers.
3679  */
3680 void
3681 ARDOUR_UI::remove_window_proxy (WindowProxyBase* p)
3682 {
3683         _window_proxies.remove (p);
3684 }
3685
3686 int
3687 ARDOUR_UI::missing_file (Session*s, std::string str, DataType type)
3688 {
3689         MissingFileDialog dialog (s, str, type);
3690
3691         dialog.show ();
3692         dialog.present ();
3693
3694         int result = dialog.run ();
3695         dialog.hide ();
3696
3697         switch (result) {
3698         case RESPONSE_OK:
3699                 break;
3700         default:
3701                 return 1; // quit entire session load
3702         }
3703
3704         result = dialog.get_action ();
3705
3706         return result;
3707 }
3708
3709 int
3710 ARDOUR_UI::ambiguous_file (std::string file, std::string /*path*/, std::vector<std::string> hits)
3711 {
3712         AmbiguousFileDialog dialog (file, hits);
3713
3714         dialog.show ();
3715         dialog.present ();
3716
3717         dialog.run ();
3718         return dialog.get_which ();
3719 }
3720
3721 /** Allocate our thread-local buffers */
3722 void
3723 ARDOUR_UI::get_process_buffers ()
3724 {
3725         _process_thread->get_buffers ();
3726 }
3727
3728 /** Drop our thread-local buffers */
3729 void
3730 ARDOUR_UI::drop_process_buffers ()
3731 {
3732         _process_thread->drop_buffers ();
3733 }
3734
3735 void
3736 ARDOUR_UI::feedback_detected ()
3737 {
3738         _feedback_exists = true;
3739 }
3740
3741 void
3742 ARDOUR_UI::successful_graph_sort ()
3743 {
3744         _feedback_exists = false;
3745 }
3746
3747 void
3748 ARDOUR_UI::midi_panic ()
3749 {
3750         if (_session) {
3751                 _session->midi_panic();
3752         }
3753 }