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