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