destroy splash when hiding it to workaround odd bug on OS X where the window will...
[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         framecnt_t frames = _session->available_capture_duration();
1054         char buf[64];
1055         framecnt_t fr = _session->frame_rate();
1056
1057         if (frames == max_framecnt) {
1058                 snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">24hrs+</span>"));
1059         } else {
1060                 rec_enabled_streams = 0;
1061                 _session->foreach_route (this, &ARDOUR_UI::count_recenabled_streams);
1062
1063                 if (rec_enabled_streams) {
1064                         frames /= rec_enabled_streams;
1065                 }
1066
1067                 int hrs;
1068                 int mins;
1069                 int secs;
1070
1071                 hrs  = frames / (fr * 3600);
1072
1073                 if (hrs > 24) {
1074                         snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">&gt;24 hrs</span>"));
1075                 } else {
1076                         frames -= hrs * fr * 3600;
1077                         mins = frames / (fr * 60);
1078                         frames -= mins * fr * 60;
1079                         secs = frames / fr;
1080                         
1081                         bool const low = (hrs == 0 && mins <= 30);
1082                         
1083                         snprintf (
1084                                 buf, sizeof(buf),
1085                                 _("Disk: <span foreground=\"%s\">%02dh:%02dm:%02ds</span>"),
1086                                 low ? X_("red") : X_("green"),
1087                                 hrs, mins, secs
1088                                 );
1089                 }
1090         }
1091
1092         disk_space_label.set_markup (buf);
1093 }
1094
1095 gint
1096 ARDOUR_UI::update_wall_clock ()
1097 {
1098         time_t now;
1099         struct tm *tm_now;
1100         char buf[16];
1101
1102         time (&now);
1103         tm_now = localtime (&now);
1104
1105         sprintf (buf, "%02d:%02d", tm_now->tm_hour, tm_now->tm_min);
1106         wall_clock_label.set_text (buf);
1107
1108         return TRUE;
1109 }
1110
1111 void
1112 ARDOUR_UI::redisplay_recent_sessions ()
1113 {
1114         std::vector<sys::path> session_directories;
1115         RecentSessionsSorter cmp;
1116
1117         recent_session_display.set_model (Glib::RefPtr<TreeModel>(0));
1118         recent_session_model->clear ();
1119
1120         ARDOUR::RecentSessions rs;
1121         ARDOUR::read_recent_sessions (rs);
1122
1123         if (rs.empty()) {
1124                 recent_session_display.set_model (recent_session_model);
1125                 return;
1126         }
1127
1128         // sort them alphabetically
1129         sort (rs.begin(), rs.end(), cmp);
1130
1131         for (ARDOUR::RecentSessions::iterator i = rs.begin(); i != rs.end(); ++i) {
1132                 session_directories.push_back ((*i).second);
1133         }
1134
1135         for (vector<sys::path>::const_iterator i = session_directories.begin();
1136                         i != session_directories.end(); ++i)
1137         {
1138                 std::vector<sys::path> state_file_paths;
1139
1140                 // now get available states for this session
1141
1142                 get_state_files_in_directory (*i, state_file_paths);
1143
1144                 vector<string*>* states;
1145                 vector<const gchar*> item;
1146                 string fullpath = i->to_string();
1147
1148                 /* remove any trailing / */
1149
1150                 if (fullpath[fullpath.length() - 1] == '/') {
1151                         fullpath = fullpath.substr (0, fullpath.length() - 1);
1152                 }
1153
1154                 /* check whether session still exists */
1155                 if (!Glib::file_test(fullpath.c_str(), Glib::FILE_TEST_EXISTS)) {
1156                         /* session doesn't exist */
1157                         continue;
1158                 }
1159
1160                 /* now get available states for this session */
1161
1162                 if ((states = Session::possible_states (fullpath)) == 0) {
1163                         /* no state file? */
1164                         continue;
1165                 }
1166
1167                 std::vector<string> state_file_names(get_file_names_no_extension (state_file_paths));
1168
1169                 Gtk::TreeModel::Row row = *(recent_session_model->append());
1170
1171                 row[recent_session_columns.visible_name] = Glib::path_get_basename (fullpath);
1172                 row[recent_session_columns.fullpath] = fullpath;
1173
1174                 if (state_file_names.size() > 1) {
1175
1176                         // add the children
1177
1178                         for (std::vector<std::string>::iterator i2 = state_file_names.begin();
1179                                         i2 != state_file_names.end(); ++i2)
1180                         {
1181
1182                                 Gtk::TreeModel::Row child_row = *(recent_session_model->append (row.children()));
1183
1184                                 child_row[recent_session_columns.visible_name] = *i2;
1185                                 child_row[recent_session_columns.fullpath] = fullpath;
1186                         }
1187                 }
1188         }
1189
1190         recent_session_display.set_tooltip_column(1); // recent_session_columns.fullpath
1191         recent_session_display.set_model (recent_session_model);
1192 }
1193
1194 void
1195 ARDOUR_UI::build_session_selector ()
1196 {
1197         session_selector_window = new ArdourDialog (_("Recent Sessions"));
1198
1199         Gtk::ScrolledWindow *scroller = manage (new Gtk::ScrolledWindow);
1200
1201         session_selector_window->add_button (Stock::CANCEL, RESPONSE_CANCEL);
1202         session_selector_window->add_button (Stock::OPEN, RESPONSE_ACCEPT);
1203         session_selector_window->set_default_response (RESPONSE_ACCEPT);
1204         recent_session_model = TreeStore::create (recent_session_columns);
1205         recent_session_display.set_model (recent_session_model);
1206         recent_session_display.append_column (_("Recent Sessions"), recent_session_columns.visible_name);
1207         recent_session_display.set_headers_visible (false);
1208         recent_session_display.get_selection()->set_mode (SELECTION_BROWSE);
1209         recent_session_display.signal_row_activated().connect (sigc::mem_fun (*this, &ARDOUR_UI::recent_session_row_activated));
1210
1211         scroller->add (recent_session_display);
1212         scroller->set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
1213
1214         session_selector_window->set_name ("SessionSelectorWindow");
1215         session_selector_window->set_size_request (200, 400);
1216         session_selector_window->get_vbox()->pack_start (*scroller);
1217
1218         recent_session_display.show();
1219         scroller->show();
1220 }
1221
1222 void
1223 ARDOUR_UI::recent_session_row_activated (const TreePath& /*path*/, TreeViewColumn* /*col*/)
1224 {
1225         session_selector_window->response (RESPONSE_ACCEPT);
1226 }
1227
1228 void
1229 ARDOUR_UI::open_recent_session ()
1230 {
1231         bool can_return = (_session != 0);
1232
1233         if (session_selector_window == 0) {
1234                 build_session_selector ();
1235         }
1236
1237         redisplay_recent_sessions ();
1238
1239         while (true) {
1240
1241                 session_selector_window->set_position (WIN_POS_MOUSE);
1242
1243                 ResponseType r = (ResponseType) session_selector_window->run ();
1244
1245                 switch (r) {
1246                 case RESPONSE_ACCEPT:
1247                         break;
1248                 default:
1249                         if (can_return) {
1250                                 session_selector_window->hide();
1251                                 return;
1252                         } else {
1253                                 exit (1);
1254                         }
1255                 }
1256
1257                 if (recent_session_display.get_selection()->count_selected_rows() == 0) {
1258                         continue;
1259                 }
1260
1261                 session_selector_window->hide();
1262
1263                 Gtk::TreeModel::iterator i = recent_session_display.get_selection()->get_selected();
1264
1265                 if (i == recent_session_model->children().end()) {
1266                         return;
1267                 }
1268
1269                 std::string path = (*i)[recent_session_columns.fullpath];
1270                 std::string state = (*i)[recent_session_columns.visible_name];
1271
1272                 _session_is_new = false;
1273
1274                 if (load_session (path, state) == 0) {
1275                         break;
1276                 }
1277
1278                 can_return = false;
1279         }
1280 }
1281
1282 bool
1283 ARDOUR_UI::check_audioengine ()
1284 {
1285         if (engine) {
1286                 if (!engine->connected()) {
1287                         MessageDialog msg (string_compose (
1288                                                    _("%1 is not connected to JACK\n"
1289                                                      "You cannot open or close sessions in this condition"),
1290                                                    PROGRAM_NAME));
1291                         pop_back_splash (msg);
1292                         msg.run ();
1293                         return false;
1294                 }
1295                 return true;
1296         } else {
1297                 return false;
1298         }
1299 }
1300
1301 void
1302 ARDOUR_UI::open_session ()
1303 {
1304         if (!check_audioengine()) {
1305                 return;
1306
1307         }
1308
1309         /* popup selector window */
1310
1311         if (open_session_selector == 0) {
1312
1313                 /* ardour sessions are folders */
1314
1315                 open_session_selector = new Gtk::FileChooserDialog (_("Open Session"), FILE_CHOOSER_ACTION_OPEN);
1316                 open_session_selector->add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1317                 open_session_selector->add_button (Gtk::Stock::OPEN, Gtk::RESPONSE_ACCEPT);
1318                 open_session_selector->set_default_response(Gtk::RESPONSE_ACCEPT);
1319                 
1320                 if (_session) {
1321                         string session_parent_dir = Glib::path_get_dirname(_session->path());
1322                         string::size_type last_dir_sep = session_parent_dir.rfind(G_DIR_SEPARATOR);
1323                         session_parent_dir = session_parent_dir.substr(0, last_dir_sep);
1324                         open_session_selector->set_current_folder(session_parent_dir);
1325                 } else {
1326                         open_session_selector->set_current_folder(Config->get_default_session_parent_dir());
1327                 }
1328
1329                 open_session_selector->add_shortcut_folder (Config->get_default_session_parent_dir());
1330
1331                 FileFilter session_filter;
1332                 session_filter.add_pattern ("*.ardour");
1333                 session_filter.set_name (string_compose (_("%1 sessions"), PROGRAM_NAME));
1334                 open_session_selector->add_filter (session_filter);
1335                 open_session_selector->set_filter (session_filter);
1336         }
1337
1338         int response = open_session_selector->run();
1339         open_session_selector->hide ();
1340
1341         switch (response) {
1342         case RESPONSE_ACCEPT:
1343                 break;
1344         default:
1345                 open_session_selector->hide();
1346                 return;
1347         }
1348
1349         open_session_selector->hide();
1350         string session_path = open_session_selector->get_filename();
1351         string path, name;
1352         bool isnew;
1353
1354         if (session_path.length() > 0) {
1355                 if (ARDOUR::find_session (session_path, path, name, isnew) == 0) {
1356                         _session_is_new = isnew;
1357                         load_session (path, name);
1358                 }
1359         }
1360 }
1361
1362
1363 void
1364 ARDOUR_UI::session_add_midi_route (bool disk, RouteGroup* route_group, uint32_t how_many, const string& name_template, PluginInfoPtr instrument)
1365 {
1366         list<boost::shared_ptr<MidiTrack> > tracks;
1367
1368         if (_session == 0) {
1369                 warning << _("You cannot add a track without a session already loaded.") << endmsg;
1370                 return;
1371         }
1372
1373         try {
1374                 if (disk) {
1375
1376                         tracks = _session->new_midi_track (instrument, ARDOUR::Normal, route_group, how_many, name_template);
1377
1378                         if (tracks.size() != how_many) {
1379                                 if (how_many == 1) {
1380                                         error << _("could not create a new midi track") << endmsg;
1381                                 } else {
1382                                         error << string_compose (_("could not create %1 new midi tracks"), how_many) << endmsg;
1383                                 }
1384                         }
1385                         
1386                 }
1387         }
1388
1389         catch (...) {
1390                 MessageDialog msg (*editor,
1391                                    string_compose (_("There are insufficient JACK ports available\n\
1392 to create a new track or bus.\n\
1393 You should save %1, exit and\n\
1394 restart JACK with more ports."), PROGRAM_NAME));
1395                 msg.run ();
1396         }
1397 }
1398
1399
1400 void
1401 ARDOUR_UI::session_add_audio_route (
1402         bool track,
1403         int32_t input_channels,
1404         int32_t output_channels,
1405         ARDOUR::TrackMode mode,
1406         RouteGroup* route_group,
1407         uint32_t how_many,
1408         string const & name_template
1409         )
1410 {
1411         list<boost::shared_ptr<AudioTrack> > tracks;
1412         RouteList routes;
1413
1414         if (_session == 0) {
1415                 warning << _("You cannot add a track or bus without a session already loaded.") << endmsg;
1416                 return;
1417         }
1418
1419         try {
1420                 if (track) {
1421                         tracks = _session->new_audio_track (input_channels, output_channels, mode, route_group, how_many, name_template);
1422
1423                         if (tracks.size() != how_many) {
1424                                 if (how_many == 1) {
1425                                         error << _("could not create a new audio track") << endmsg;
1426                                 } else {
1427                                         error << string_compose (_("could only create %1 of %2 new audio %3"),
1428                                                                  tracks.size(), how_many, (track ? _("tracks") : _("busses"))) << endmsg;
1429                                 }
1430                         }
1431
1432                 } else {
1433
1434                         routes = _session->new_audio_route (input_channels, output_channels, route_group, how_many, name_template);
1435
1436                         if (routes.size() != how_many) {
1437                                 if (how_many == 1) {
1438                                         error << _("could not create a new audio bus") << endmsg;
1439                                 } else {
1440                                         error << string_compose (_("could not create %1 new audio busses"), how_many) << endmsg;
1441                                 }
1442                         }
1443                 }
1444         }
1445
1446         catch (...) {
1447                 MessageDialog msg (*editor,
1448                                    string_compose (_("There are insufficient JACK ports available\n\
1449 to create a new track or bus.\n\
1450 You should save %1, exit and\n\
1451 restart JACK with more ports."), PROGRAM_NAME));
1452                 pop_back_splash (msg);
1453                 msg.run ();
1454         }
1455 }
1456
1457 void
1458 ARDOUR_UI::transport_goto_start ()
1459 {
1460         if (_session) {
1461                 _session->goto_start();
1462
1463                 /* force displayed area in editor to start no matter
1464                    what "follow playhead" setting is.
1465                 */
1466
1467                 if (editor) {
1468                         editor->center_screen (_session->current_start_frame ());
1469                 }
1470         }
1471 }
1472
1473 void
1474 ARDOUR_UI::transport_goto_zero ()
1475 {
1476         if (_session) {
1477                 _session->request_locate (0);
1478
1479                 /* force displayed area in editor to start no matter
1480                    what "follow playhead" setting is.
1481                 */
1482
1483                 if (editor) {
1484                         editor->reset_x_origin (0);
1485                 }
1486         }
1487 }
1488
1489 void
1490 ARDOUR_UI::transport_goto_wallclock ()
1491 {
1492         if (_session && editor) {
1493
1494                 time_t now;
1495                 struct tm tmnow;
1496                 framepos_t frames;
1497
1498                 time (&now);
1499                 localtime_r (&now, &tmnow);
1500
1501                 frames = tmnow.tm_hour * (60 * 60 * _session->frame_rate());
1502                 frames += tmnow.tm_min * (60 * _session->frame_rate());
1503                 frames += tmnow.tm_sec * _session->frame_rate();
1504
1505                 _session->request_locate (frames, _session->transport_rolling ());
1506
1507                 /* force displayed area in editor to start no matter
1508                    what "follow playhead" setting is.
1509                 */
1510
1511                 if (editor) {
1512                         editor->center_screen (frames);
1513                 }
1514         }
1515 }
1516
1517 void
1518 ARDOUR_UI::transport_goto_end ()
1519 {
1520         if (_session) {
1521                 framepos_t const frame = _session->current_end_frame();
1522                 _session->request_locate (frame);
1523
1524                 /* force displayed area in editor to start no matter
1525                    what "follow playhead" setting is.
1526                 */
1527
1528                 if (editor) {
1529                         editor->center_screen (frame);
1530                 }
1531         }
1532 }
1533
1534 void
1535 ARDOUR_UI::transport_stop ()
1536 {
1537         if (!_session) {
1538                 return;
1539         }
1540
1541         if (_session->is_auditioning()) {
1542                 _session->cancel_audition ();
1543                 return;
1544         }
1545
1546         _session->request_stop (false, true);
1547 }
1548
1549 void
1550 ARDOUR_UI::transport_record (bool roll)
1551 {
1552
1553         if (_session) {
1554                 switch (_session->record_status()) {
1555                 case Session::Disabled:
1556                         if (_session->ntracks() == 0) {
1557                                 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."));
1558                                 msg.run ();
1559                                 return;
1560                         }
1561                         _session->maybe_enable_record ();
1562                         if (roll) {
1563                                 transport_roll ();
1564                         }
1565                         break;
1566                 case Session::Recording:
1567                         if (roll) {
1568                                 _session->request_stop();
1569                         } else {
1570                                 _session->disable_record (false, true);
1571                         }
1572                         break;
1573
1574                 case Session::Enabled:
1575                         _session->disable_record (false, true);
1576                 }
1577         }
1578 }
1579
1580 void
1581 ARDOUR_UI::transport_roll ()
1582 {
1583         if (!_session) {
1584                 return;
1585         }
1586
1587         if (_session->is_auditioning()) {
1588                 return;
1589         }
1590
1591 #if 0
1592         if (_session->config.get_external_sync()) {
1593                 switch (_session->config.get_sync_source()) {
1594                 case JACK:
1595                         break;
1596                 default:
1597                         /* transport controlled by the master */
1598                         return;
1599                 }
1600         }
1601 #endif
1602
1603         bool rolling = _session->transport_rolling();
1604
1605         if (_session->get_play_loop()) {
1606                 /* XXX it is not possible to just leave seamless loop and keep
1607                    playing at present (nov 4th 2009)
1608                 */
1609                 if (!Config->get_seamless_loop()) {
1610                         _session->request_play_loop (false, true);
1611                 }
1612         } else if (_session->get_play_range () && !Config->get_always_play_range()) {
1613                 /* stop playing a range if we currently are */
1614                 _session->request_play_range (0, true);
1615         }
1616
1617         if (Config->get_always_play_range()) {
1618                 _session->request_play_range (&editor->get_selection().time, true);
1619         }
1620
1621         if (!rolling) {
1622                 _session->request_transport_speed (1.0f);
1623         }
1624 }
1625
1626 void
1627 ARDOUR_UI::toggle_roll (bool with_abort, bool roll_out_of_bounded_mode)
1628 {
1629
1630         if (!_session) {
1631                 return;
1632         }
1633
1634         if (_session->is_auditioning()) {
1635                 _session->cancel_audition ();
1636                 return;
1637         }
1638
1639         if (_session->config.get_external_sync()) {
1640                 switch (_session->config.get_sync_source()) {
1641                 case JACK:
1642                         break;
1643                 default:
1644                         /* transport controlled by the master */
1645                         return;
1646                 }
1647         }
1648
1649         bool rolling = _session->transport_rolling();
1650         bool affect_transport = true;
1651
1652         if (rolling && roll_out_of_bounded_mode) {
1653                 /* drop out of loop/range playback but leave transport rolling */
1654                 if (_session->get_play_loop()) {
1655                         if (Config->get_seamless_loop()) {
1656                                 /* the disk buffers contain copies of the loop - we can't
1657                                    just keep playing, so stop the transport. the user
1658                                    can restart as they wish.
1659                                 */
1660                                 affect_transport = true;
1661                         } else {
1662                                 /* disk buffers are normal, so we can keep playing */
1663                                 affect_transport = false;
1664                         }
1665                         _session->request_play_loop (false, true);
1666                 } else if (_session->get_play_range ()) {
1667                         affect_transport = false;
1668                         _session->request_play_range (0, true);
1669                 }
1670         }
1671
1672         if (affect_transport) {
1673                 if (rolling) {
1674                         _session->request_stop (with_abort, true);
1675                 } else {
1676                         if (Config->get_always_play_range ()) {
1677                                 _session->request_play_range (&editor->get_selection().time, true);
1678                         }
1679
1680                         _session->request_transport_speed (1.0f);
1681                 }
1682         }
1683 }
1684
1685 void
1686 ARDOUR_UI::toggle_session_auto_loop ()
1687 {
1688         Location * looploc = _session->locations()->auto_loop_location();
1689
1690         if (!_session || !looploc) {
1691                 return;
1692         }
1693
1694         if (_session->get_play_loop()) {
1695
1696                 if (_session->transport_rolling()) {
1697
1698                         _session->request_locate (looploc->start(), true);
1699                         _session->request_play_loop (false);
1700
1701                 } else {
1702                         _session->request_play_loop (false);
1703                 }
1704         } else {
1705                 _session->request_play_loop (true);
1706         }
1707         
1708         //show the loop markers
1709         looploc->set_hidden (false, this);
1710 }
1711
1712 void
1713 ARDOUR_UI::transport_play_selection ()
1714 {
1715         if (!_session) {
1716                 return;
1717         }
1718
1719         editor->play_selection ();
1720 }
1721
1722 void
1723 ARDOUR_UI::transport_rewind (int option)
1724 {
1725         float current_transport_speed;
1726
1727         if (_session) {
1728                 current_transport_speed = _session->transport_speed();
1729
1730                 if (current_transport_speed >= 0.0f) {
1731                         switch (option) {
1732                         case 0:
1733                                 _session->request_transport_speed (-1.0f);
1734                                 break;
1735                         case 1:
1736                                 _session->request_transport_speed (-4.0f);
1737                                 break;
1738                         case -1:
1739                                 _session->request_transport_speed (-0.5f);
1740                                 break;
1741                         }
1742                 } else {
1743                         /* speed up */
1744                         _session->request_transport_speed (current_transport_speed * 1.5f);
1745                 }
1746         }
1747 }
1748
1749 void
1750 ARDOUR_UI::transport_forward (int option)
1751 {
1752         if (!_session) {
1753                 return;
1754         }
1755         
1756         float current_transport_speed = _session->transport_speed();
1757         
1758         if (current_transport_speed <= 0.0f) {
1759                 switch (option) {
1760                 case 0:
1761                         _session->request_transport_speed (1.0f);
1762                         break;
1763                 case 1:
1764                         _session->request_transport_speed (4.0f);
1765                         break;
1766                 case -1:
1767                         _session->request_transport_speed (0.5f);
1768                         break;
1769                 }
1770         } else {
1771                 /* speed up */
1772                 _session->request_transport_speed (current_transport_speed * 1.5f);
1773         }
1774 }
1775
1776 void
1777 ARDOUR_UI::toggle_record_enable (uint32_t rid)
1778 {
1779         if (!_session) {
1780                 return;
1781         }
1782
1783         boost::shared_ptr<Route> r;
1784
1785         if ((r = _session->route_by_remote_id (rid)) != 0) {
1786
1787                 Track* t;
1788
1789                 if ((t = dynamic_cast<Track*>(r.get())) != 0) {
1790                         t->set_record_enabled (!t->record_enabled(), this);
1791                 }
1792         }
1793 }
1794
1795 void
1796 ARDOUR_UI::map_transport_state ()
1797 {
1798         if (!_session) {
1799                 auto_loop_button.unset_active_state ();
1800                 play_selection_button.unset_active_state ();
1801                 roll_button.unset_active_state ();
1802                 stop_button.set_active_state (Gtkmm2ext::ExplicitActive);
1803                 return;
1804         }
1805
1806         shuttle_box->map_transport_state ();
1807
1808         float sp = _session->transport_speed();
1809
1810         if (sp != 0.0f) {
1811
1812                 /* we're rolling */
1813
1814                 if (_session->get_play_range()) {
1815
1816                         play_selection_button.set_active_state (Gtkmm2ext::ExplicitActive);
1817                         roll_button.unset_active_state ();
1818                         auto_loop_button.unset_active_state ();
1819
1820                 } else if (_session->get_play_loop ()) {
1821
1822                         auto_loop_button.set_active (true);
1823                         play_selection_button.set_active (false);
1824                         roll_button.set_active (false);
1825
1826                 } else {
1827
1828                         roll_button.set_active (true);
1829                         play_selection_button.set_active (false);
1830                         auto_loop_button.set_active (false);
1831                 }
1832
1833                 if (Config->get_always_play_range()) {
1834                         /* light up both roll and play-selection if they are joined */
1835                         roll_button.set_active (true);
1836                         play_selection_button.set_active (true);
1837                 }
1838
1839                 stop_button.set_active (false);
1840
1841         } else {
1842
1843                 stop_button.set_active (true);
1844                 roll_button.set_active (false);
1845                 play_selection_button.set_active (false);
1846                 auto_loop_button.set_active (false);
1847                 update_disk_space ();
1848         }
1849 }
1850
1851 void
1852 ARDOUR_UI::engine_stopped ()
1853 {
1854         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::engine_stopped)
1855         ActionManager::set_sensitive (ActionManager::jack_sensitive_actions, false);
1856         ActionManager::set_sensitive (ActionManager::jack_opposite_sensitive_actions, true);
1857 }
1858
1859 void
1860 ARDOUR_UI::engine_running ()
1861 {
1862         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::engine_running)
1863         ActionManager::set_sensitive (ActionManager::jack_sensitive_actions, true);
1864         ActionManager::set_sensitive (ActionManager::jack_opposite_sensitive_actions, false);
1865
1866         Glib::RefPtr<Action> action;
1867         const char* action_name = 0;
1868
1869         switch (engine->frames_per_cycle()) {
1870         case 32:
1871                 action_name = X_("JACKLatency32");
1872                 break;
1873         case 64:
1874                 action_name = X_("JACKLatency64");
1875                 break;
1876         case 128:
1877                 action_name = X_("JACKLatency128");
1878                 break;
1879         case 512:
1880                 action_name = X_("JACKLatency512");
1881                 break;
1882         case 1024:
1883                 action_name = X_("JACKLatency1024");
1884                 break;
1885         case 2048:
1886                 action_name = X_("JACKLatency2048");
1887                 break;
1888         case 4096:
1889                 action_name = X_("JACKLatency4096");
1890                 break;
1891         case 8192:
1892                 action_name = X_("JACKLatency8192");
1893                 break;
1894         default:
1895                 /* XXX can we do anything useful ? */
1896                 break;
1897         }
1898
1899         if (action_name) {
1900
1901                 action = ActionManager::get_action (X_("JACK"), action_name);
1902
1903                 if (action) {
1904                         Glib::RefPtr<RadioAction> ract = Glib::RefPtr<RadioAction>::cast_dynamic (action);
1905                         ract->set_active ();
1906                 }
1907         }
1908 }
1909
1910 void
1911 ARDOUR_UI::engine_halted (const char* reason, bool free_reason)
1912 {
1913         if (!Gtkmm2ext::UI::instance()->caller_is_ui_thread()) {
1914                 /* we can't rely on the original string continuing to exist when we are called
1915                    again in the GUI thread, so make a copy and note that we need to
1916                    free it later.
1917                 */
1918                 char *copy = strdup (reason);
1919                 Gtkmm2ext::UI::instance()->call_slot (invalidator (*this), boost::bind (&ARDOUR_UI::engine_halted, this, copy, true));
1920                 return;
1921         }
1922
1923         ActionManager::set_sensitive (ActionManager::jack_sensitive_actions, false);
1924         ActionManager::set_sensitive (ActionManager::jack_opposite_sensitive_actions, true);
1925
1926         update_sample_rate (0);
1927
1928         string msgstr;
1929
1930         /* if the reason is a non-empty string, it means that the backend was shutdown
1931            rather than just Ardour.
1932         */
1933
1934         if (strlen (reason)) {
1935                 msgstr = string_compose (_("The audio backend (JACK) was shutdown because:\n\n%1"), reason);
1936         } else {
1937                 msgstr = string_compose (_("\
1938 JACK has either been shutdown or it\n\
1939 disconnected %1 because %1\n\
1940 was not fast enough. Try to restart\n\
1941 JACK, reconnect and save the session."), PROGRAM_NAME);
1942         }
1943
1944         MessageDialog msg (*editor, msgstr);
1945         pop_back_splash (msg);
1946         msg.run ();
1947
1948         if (free_reason) {
1949                 free ((char*) reason);
1950         }
1951 }
1952
1953 int32_t
1954 ARDOUR_UI::do_engine_start ()
1955 {
1956         try {
1957                 engine->start();
1958         }
1959
1960         catch (...) {
1961                 engine->stop ();
1962                 error << _("Unable to start the session running")
1963                       << endmsg;
1964                 unload_session ();
1965                 return -2;
1966         }
1967
1968         return 0;
1969 }
1970
1971 void
1972 ARDOUR_UI::update_clocks ()
1973 {
1974         if (!editor || !editor->dragging_playhead()) {
1975                 Clock (_session->audible_frame(), false, editor->get_preferred_edit_position()); /* EMIT_SIGNAL */
1976         }
1977 }
1978
1979 void
1980 ARDOUR_UI::start_clocking ()
1981 {
1982         clock_signal_connection = RapidScreenUpdate.connect (sigc::mem_fun(*this, &ARDOUR_UI::update_clocks));
1983 }
1984
1985 void
1986 ARDOUR_UI::stop_clocking ()
1987 {
1988         clock_signal_connection.disconnect ();
1989 }
1990
1991 gint
1992 ARDOUR_UI::_blink (void *arg)
1993 {
1994         ((ARDOUR_UI *) arg)->blink ();
1995         return TRUE;
1996 }
1997
1998 void
1999 ARDOUR_UI::blink ()
2000 {
2001         Blink (blink_on = !blink_on); /* EMIT_SIGNAL */
2002 }
2003
2004 void
2005 ARDOUR_UI::start_blinking ()
2006 {
2007         /* Start the blink signal. Everybody with a blinking widget
2008            uses Blink to drive the widget's state.
2009         */
2010
2011         if (blink_timeout_tag < 0) {
2012                 blink_on = false;
2013                 blink_timeout_tag = g_timeout_add (240, _blink, this);
2014         }
2015 }
2016
2017 void
2018 ARDOUR_UI::stop_blinking ()
2019 {
2020         if (blink_timeout_tag >= 0) {
2021                 g_source_remove (blink_timeout_tag);
2022                 blink_timeout_tag = -1;
2023         }
2024 }
2025
2026
2027 /** Ask the user for the name of a new snapshot and then take it.
2028  */
2029
2030 void
2031 ARDOUR_UI::snapshot_session (bool switch_to_it)
2032 {
2033         ArdourPrompter prompter (true);
2034         string snapname;
2035
2036         prompter.set_name ("Prompter");
2037         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2038         prompter.set_title (_("Take Snapshot"));
2039         prompter.set_prompt (_("Name of new snapshot"));
2040
2041         if (!switch_to_it) {
2042                 char timebuf[128];
2043                 time_t n;
2044                 struct tm local_time;
2045
2046                 time (&n);
2047                 localtime_r (&n, &local_time);
2048                 strftime (timebuf, sizeof(timebuf), "%FT%H.%M.%S", &local_time);
2049                 prompter.set_initial_text (timebuf);
2050         }
2051
2052   again:
2053         switch (prompter.run()) {
2054         case RESPONSE_ACCEPT:
2055         {
2056                 prompter.get_result (snapname);
2057
2058                 bool do_save = (snapname.length() != 0);
2059
2060                 if (do_save) {
2061                         char illegal = Session::session_name_is_legal(snapname);
2062                         if (illegal) {
2063                                 MessageDialog msg (string_compose (_("To ensure compatibility with various systems\n"
2064                                                      "snapshot names may not contain a '%1' character"), illegal));
2065                                 msg.run ();
2066                                 goto again;
2067                         }
2068                 }
2069
2070                 vector<sys::path> p;
2071                 get_state_files_in_directory (_session->session_directory().root_path(), p);
2072                 vector<string> n = get_file_names_no_extension (p);
2073                 if (find (n.begin(), n.end(), snapname) != n.end()) {
2074
2075                         ArdourDialog confirm (_("Confirm Snapshot Overwrite"), true);
2076                         Label m (_("A snapshot already exists with that name.  Do you want to overwrite it?"));
2077                         confirm.get_vbox()->pack_start (m, true, true);
2078                         confirm.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2079                         confirm.add_button (_("Overwrite"), Gtk::RESPONSE_ACCEPT);
2080                         confirm.show_all ();
2081                         switch (confirm.run()) {
2082                         case RESPONSE_CANCEL:
2083                                 do_save = false;
2084                         }
2085                 }
2086
2087                 if (do_save) {
2088                         save_state (snapname, switch_to_it);
2089                 }
2090                 break;
2091         }
2092
2093         default:
2094                 break;
2095         }
2096 }
2097
2098 /** Ask the user for a new session name and then rename the session to it.
2099  */
2100
2101 void
2102 ARDOUR_UI::rename_session ()
2103 {
2104         if (!_session) {
2105                 return;
2106         }
2107
2108         ArdourPrompter prompter (true);
2109         string name;
2110
2111         prompter.set_name ("Prompter");
2112         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2113         prompter.set_title (_("Rename Session"));
2114         prompter.set_prompt (_("New session name"));
2115
2116   again:
2117         switch (prompter.run()) {
2118         case RESPONSE_ACCEPT:
2119         {
2120                 prompter.get_result (name);
2121
2122                 bool do_rename = (name.length() != 0);
2123
2124                 if (do_rename) {
2125                         char illegal = Session::session_name_is_legal (name);
2126
2127                         if (illegal) {
2128                                 MessageDialog msg (string_compose (_("To ensure compatibility with various systems\n"
2129                                                                      "session names may not contain a '%1' character"), illegal));
2130                                 msg.run ();
2131                                 goto again;
2132                         }
2133
2134                         switch (_session->rename (name)) {
2135                         case -1: {
2136                                 MessageDialog msg (_("That name is already in use by another directory/folder. Please try again."));
2137                                 msg.set_position (WIN_POS_MOUSE);
2138                                 msg.run ();
2139                                 goto again;
2140                                 break;
2141                         }
2142                         case 0:
2143                                 break;
2144                         default: {
2145                                 MessageDialog msg (_("Renaming this session failed.\nThings could be seriously messed up at this point"));
2146                                 msg.set_position (WIN_POS_MOUSE);
2147                                 msg.run ();
2148                                 break;
2149                         }
2150                         }
2151                 }
2152                 
2153                 break;
2154         }
2155
2156         default:
2157                 break;
2158         }
2159 }
2160
2161 void
2162 ARDOUR_UI::save_state (const string & name, bool switch_to_it)
2163 {
2164         XMLNode* node = new XMLNode (X_("UI"));
2165
2166         for (list<WindowProxyBase*>::iterator i = _window_proxies.begin(); i != _window_proxies.end(); ++i) {
2167                 if (!(*i)->rc_configured()) {
2168                         node->add_child_nocopy (*((*i)->get_state ()));
2169                 }
2170         }
2171
2172         node->add_child_nocopy (gui_object_state->get_state());
2173
2174         _session->add_extra_xml (*node);
2175
2176         save_state_canfail (name, switch_to_it);
2177 }
2178
2179 int
2180 ARDOUR_UI::save_state_canfail (string name, bool switch_to_it)
2181 {
2182         if (_session) {
2183                 int ret;
2184
2185                 if (name.length() == 0) {
2186                         name = _session->snap_name();
2187                 }
2188
2189                 if ((ret = _session->save_state (name, false, switch_to_it)) != 0) {
2190                         return ret;
2191                 }
2192         }
2193
2194         save_ardour_state (); /* XXX cannot fail? yeah, right ... */
2195         return 0;
2196 }
2197
2198 void
2199 ARDOUR_UI::primary_clock_value_changed ()
2200 {
2201         if (_session) {
2202                 _session->request_locate (primary_clock->current_time ());
2203         }
2204 }
2205
2206 void
2207 ARDOUR_UI::big_clock_value_changed ()
2208 {
2209         if (_session) {
2210                 _session->request_locate (big_clock->current_time ());
2211         }
2212 }
2213
2214 void
2215 ARDOUR_UI::secondary_clock_value_changed ()
2216 {
2217         if (_session) {
2218                 _session->request_locate (secondary_clock->current_time ());
2219         }
2220 }
2221
2222 void
2223 ARDOUR_UI::transport_rec_enable_blink (bool onoff)
2224 {
2225         if (_session == 0) {
2226                 return;
2227         }
2228
2229         if (_session->step_editing()) {
2230                 return;
2231         }
2232
2233         Session::RecordState const r = _session->record_status ();
2234         bool const h = _session->have_rec_enabled_track ();
2235
2236         if (r == Session::Enabled || (r == Session::Recording && !h)) {
2237                 if (onoff) {
2238                         rec_button.set_active_state (Gtkmm2ext::ExplicitActive);
2239                 } else {
2240                         rec_button.set_active_state (Gtkmm2ext::ImplicitActive);
2241                 }
2242         } else if (r == Session::Recording && h) {
2243                 rec_button.set_active_state (Gtkmm2ext::ExplicitActive);
2244         } else {
2245                 rec_button.unset_active_state ();
2246         }
2247 }
2248
2249 void
2250 ARDOUR_UI::save_template ()
2251 {
2252         ArdourPrompter prompter (true);
2253         string name;
2254
2255         if (!check_audioengine()) {
2256                 return;
2257         }
2258
2259         prompter.set_name (X_("Prompter"));
2260         prompter.set_title (_("Save Template"));
2261         prompter.set_prompt (_("Name for template:"));
2262         prompter.set_initial_text(_session->name() + _("-template"));
2263         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2264
2265         switch (prompter.run()) {
2266         case RESPONSE_ACCEPT:
2267                 prompter.get_result (name);
2268
2269                 if (name.length()) {
2270                         _session->save_template (name);
2271                 }
2272                 break;
2273
2274         default:
2275                 break;
2276         }
2277 }
2278
2279 void
2280 ARDOUR_UI::edit_metadata ()
2281 {
2282         SessionMetadataEditor dialog;
2283         dialog.set_session (_session);
2284         editor->ensure_float (dialog);
2285         dialog.run ();
2286 }
2287
2288 void
2289 ARDOUR_UI::import_metadata ()
2290 {
2291         SessionMetadataImporter dialog;
2292         dialog.set_session (_session);
2293         editor->ensure_float (dialog);
2294         dialog.run ();
2295 }
2296
2297 bool
2298 ARDOUR_UI::ask_about_loading_existing_session (const std::string& session_path)
2299 {
2300         std::string str = string_compose (_("This session\n%1\nalready exists. Do you want to open it?"), session_path);
2301
2302         MessageDialog msg (str,
2303                            false,
2304                            Gtk::MESSAGE_WARNING,
2305                            Gtk::BUTTONS_YES_NO,
2306                            true);
2307
2308
2309         msg.set_name (X_("OpenExistingDialog"));
2310         msg.set_title (_("Open Existing Session"));
2311         msg.set_wmclass (X_("existing_session"), PROGRAM_NAME);
2312         msg.set_position (Gtk::WIN_POS_MOUSE);
2313         pop_back_splash (msg);
2314
2315         switch (msg.run()) {
2316         case RESPONSE_YES:
2317                 return true;
2318                 break;
2319         }
2320         return false;
2321 }
2322
2323 int
2324 ARDOUR_UI::build_session_from_nsd (const std::string& session_path, const std::string& session_name)
2325 {
2326         BusProfile bus_profile;
2327
2328         if (Profile->get_sae()) {
2329
2330                 bus_profile.master_out_channels = 2;
2331                 bus_profile.input_ac = AutoConnectPhysical;
2332                 bus_profile.output_ac = AutoConnectMaster;
2333                 bus_profile.requested_physical_in = 0; // use all available
2334                 bus_profile.requested_physical_out = 0; // use all available
2335
2336         } else {
2337
2338                 /* get settings from advanced section of NSD */
2339
2340                 if (_startup->create_master_bus()) {
2341                         bus_profile.master_out_channels = (uint32_t) _startup->master_channel_count();
2342                 } else {
2343                         bus_profile.master_out_channels = 0;
2344                 }
2345
2346                 if (_startup->connect_inputs()) {
2347                         bus_profile.input_ac = AutoConnectPhysical;
2348                 } else {
2349                         bus_profile.input_ac = AutoConnectOption (0);
2350                 }
2351
2352                 bus_profile.output_ac = AutoConnectOption (0);
2353
2354                 if (_startup->connect_outputs ()) {
2355                         if (_startup->connect_outs_to_master()) {
2356                                 bus_profile.output_ac = AutoConnectMaster;
2357                         } else if (_startup->connect_outs_to_physical()) {
2358                                 bus_profile.output_ac = AutoConnectPhysical;
2359                         }
2360                 }
2361
2362                 bus_profile.requested_physical_in = (uint32_t) _startup->input_limit_count();
2363                 bus_profile.requested_physical_out = (uint32_t) _startup->output_limit_count();
2364         }
2365
2366         if (build_session (session_path, session_name, bus_profile)) {
2367                 return -1;
2368         }
2369
2370         return 0;
2371 }
2372
2373 void
2374 ARDOUR_UI::idle_load (const std::string& path)
2375 {
2376         if (_session) {
2377                 if (Glib::file_test (path, Glib::FILE_TEST_IS_DIR)) {
2378                         /* /path/to/foo => /path/to/foo, foo */
2379                         load_session (path, basename_nosuffix (path));
2380                 } else {
2381                         /* /path/to/foo/foo.ardour => /path/to/foo, foo */
2382                         load_session (Glib::path_get_dirname (path), basename_nosuffix (path));
2383                 }
2384
2385         } else {
2386                 ARDOUR_COMMAND_LINE::session_name = path;
2387         }
2388 }
2389
2390 void
2391 ARDOUR_UI::loading_message (const std::string& msg)
2392 {
2393         if (ARDOUR_COMMAND_LINE::no_splash) {
2394                 return;
2395         }
2396
2397         show_splash ();
2398         if (splash) {
2399                 splash->message (msg);
2400                 flush_pending ();
2401         }
2402 }
2403
2404 /** @param quit_on_cancel true if exit() should be called if the user clicks `cancel' in the new session dialog */
2405 int
2406 ARDOUR_UI::get_session_parameters (bool quit_on_cancel, bool should_be_new, string load_template)
2407 {
2408         string session_name;
2409         string session_path;
2410         string template_name;
2411         int ret = -1;
2412         bool likely_new = false;
2413
2414         if (!load_template.empty()) {
2415                 should_be_new = true;
2416                 template_name = load_template;
2417         }
2418
2419         while (ret != 0) {
2420
2421                 if (!should_be_new && !ARDOUR_COMMAND_LINE::session_name.empty()) {
2422
2423                         /* if they named a specific statefile, use it, otherwise they are
2424                            just giving a session folder, and we want to use it as is
2425                            to find the session.
2426                         */
2427
2428                         string::size_type suffix = ARDOUR_COMMAND_LINE::session_name.find (statefile_suffix);
2429
2430                         if (suffix != string::npos) {
2431                                 session_path = Glib::path_get_dirname (ARDOUR_COMMAND_LINE::session_name);
2432                                 session_name = ARDOUR_COMMAND_LINE::session_name.substr (0, suffix);
2433                                 session_name = Glib::path_get_basename (session_name);
2434                         } else {
2435                                 session_path = ARDOUR_COMMAND_LINE::session_name;
2436                                 session_name = Glib::path_get_basename (ARDOUR_COMMAND_LINE::session_name);
2437                         }
2438
2439                 } else {
2440
2441                         bool const apply = run_startup (should_be_new, load_template);
2442
2443                         if (!apply) {
2444                                 if (quit_on_cancel) {
2445                                         exit (1);
2446                                 } else {
2447                                         return ret;
2448                                 }
2449                         }
2450
2451                         /* if we run the startup dialog again, offer more than just "new session" */
2452
2453                         should_be_new = false;
2454
2455                         session_name = _startup->session_name (likely_new);
2456
2457                         string::size_type suffix = session_name.find (statefile_suffix);
2458
2459                         if (suffix != string::npos) {
2460                                 session_name = session_name.substr (0, suffix);
2461                         }
2462
2463                         /* this shouldn't happen, but we catch it just in case it does */
2464
2465                         if (session_name.empty()) {
2466                                 continue;
2467                         }
2468
2469                         if (_startup->use_session_template()) {
2470                                 template_name = _startup->session_template_name();
2471                                 _session_is_new = true;
2472                         }
2473
2474                         if (session_name[0] == G_DIR_SEPARATOR ||
2475                             (session_name.length() > 2 && session_name[0] == '.' && session_name[1] == G_DIR_SEPARATOR) ||
2476                             (session_name.length() > 3 && session_name[0] == '.' && session_name[1] == '.' && session_name[2] == G_DIR_SEPARATOR)) {
2477
2478                                 /* absolute path or cwd-relative path specified for session name: infer session folder
2479                                    from what was given.
2480                                 */
2481
2482                                 session_path = Glib::path_get_dirname (session_name);
2483                                 session_name = Glib::path_get_basename (session_name);
2484
2485                         } else {
2486
2487                                 session_path = _startup->session_folder();
2488
2489                                 char illegal = Session::session_name_is_legal (session_name);
2490
2491                                 if (illegal) {
2492                                         MessageDialog msg (*_startup,
2493                                                            string_compose (_("To ensure compatibility with various systems\n"
2494                                                                              "session names may not contain a '%1' character"),
2495                                                                            illegal));
2496                                         msg.run ();
2497                                         ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2498                                         continue;
2499                                 }
2500                         }
2501                 }
2502
2503                 if (create_engine ()) {
2504                         break;
2505                 }
2506
2507                 if (Glib::file_test (session_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
2508
2509                         if (likely_new) {
2510
2511                                 std::string existing = Glib::build_filename (session_path, session_name);
2512
2513                                 if (!ask_about_loading_existing_session (existing)) {
2514                                         ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2515                                         continue;
2516                                 }
2517                         }
2518
2519                         _session_is_new = false;
2520
2521                 } else {
2522
2523                         if (!likely_new) {
2524                                 if (_startup) {
2525                                         pop_back_splash (*_startup);
2526                                 } else {
2527                                         hide_splash ();
2528                                 }
2529
2530                                 MessageDialog msg (string_compose (_("There is no existing session at \"%1\""), session_path));
2531                                 msg.run ();
2532                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2533                                 continue;
2534                         }
2535
2536                         char illegal = Session::session_name_is_legal(session_name);
2537                         if (illegal) {
2538                                 pop_back_splash (*_startup);
2539                                 MessageDialog msg (*_startup, string_compose(_("To ensure compatibility with various systems\n"
2540                                                      "session names may not contain a '%1' character"), illegal));
2541                                 msg.run ();
2542                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
2543                                 continue;
2544                         }
2545
2546                         _session_is_new = true;
2547                 }
2548
2549                 if (likely_new && template_name.empty()) {
2550
2551                         ret = build_session_from_nsd (session_path, session_name);
2552
2553                 } else {
2554
2555                         ret = load_session (session_path, session_name, template_name);
2556
2557                         if (ret == -2) {
2558                                 /* not connected to the AudioEngine, so quit to avoid an infinite loop */
2559                                 exit (1);
2560                         }
2561
2562                         if (!ARDOUR_COMMAND_LINE::immediate_save.empty()) {
2563                                 _session->save_state (ARDOUR_COMMAND_LINE::immediate_save, false);
2564                                 exit (1);
2565                         }
2566                 }
2567         }
2568
2569         return ret;
2570 }
2571
2572 void
2573 ARDOUR_UI::close_session()
2574 {
2575         if (!check_audioengine()) {
2576                 return;
2577         }
2578
2579         if (unload_session (true)) {
2580                 return;
2581         }
2582
2583         ARDOUR_COMMAND_LINE::session_name = "";
2584
2585         if (get_session_parameters (true, false)) {
2586                 exit (1);
2587         }
2588
2589         goto_editor_window ();
2590 }
2591
2592 /** @param snap_name Snapshot name (without .ardour suffix).
2593  *  @return -2 if the load failed because we are not connected to the AudioEngine.
2594  */
2595 int
2596 ARDOUR_UI::load_session (const std::string& path, const std::string& snap_name, std::string mix_template)
2597 {
2598         Session *new_session;
2599         int unload_status;
2600         int retval = -1;
2601
2602         session_loaded = false;
2603
2604         if (!check_audioengine()) {
2605                 return -2;
2606         }
2607
2608         unload_status = unload_session ();
2609
2610         if (unload_status < 0) {
2611                 goto out;
2612         } else if (unload_status > 0) {
2613                 retval = 0;
2614                 goto out;
2615         }
2616
2617         loading_message (string_compose (_("Please wait while %1 loads your session"), PROGRAM_NAME));
2618
2619         try {
2620                 new_session = new Session (*engine, path, snap_name, 0, mix_template);
2621         }
2622
2623         /* this one is special */
2624
2625         catch (AudioEngine::PortRegistrationFailure& err) {
2626
2627                 MessageDialog msg (err.what(),
2628                                    true,
2629                                    Gtk::MESSAGE_INFO,
2630                                    Gtk::BUTTONS_CLOSE);
2631
2632                 msg.set_title (_("Port Registration Error"));
2633                 msg.set_secondary_text (_("Click the Close button to try again."));
2634                 msg.set_position (Gtk::WIN_POS_CENTER);
2635                 pop_back_splash (msg);
2636                 msg.present ();
2637
2638                 int response = msg.run ();
2639
2640                 msg.hide ();
2641
2642                 switch (response) {
2643                 case RESPONSE_CANCEL:
2644                         exit (1);
2645                 default:
2646                         break;
2647                 }
2648                 goto out;
2649         }
2650
2651         catch (...) {
2652
2653                 MessageDialog msg (string_compose(
2654                                            _("Session \"%1 (snapshot %2)\" did not load successfully"),
2655                                            path, snap_name),
2656                                    true,
2657                                    Gtk::MESSAGE_INFO,
2658                                    BUTTONS_OK);
2659
2660                 msg.set_title (_("Loading Error"));
2661                 msg.set_secondary_text (_("Click the Refresh button to try again."));
2662                 msg.add_button (Stock::REFRESH, 1);
2663                 msg.set_position (Gtk::WIN_POS_CENTER);
2664                 pop_back_splash (msg);
2665                 msg.present ();
2666
2667                 int response = msg.run ();
2668
2669                 switch (response) {
2670                 case 1:
2671                         break;
2672                 default:
2673                         exit (1);
2674                 }
2675
2676                 msg.hide ();
2677
2678                 goto out;
2679         }
2680
2681         {
2682                 list<string> const u = new_session->unknown_processors ();
2683                 if (!u.empty()) {
2684                         MissingPluginDialog d (_session, u);
2685                         d.run ();
2686                 }
2687         }
2688
2689         /* Now the session been created, add the transport controls */
2690         new_session->add_controllable(roll_controllable);
2691         new_session->add_controllable(stop_controllable);
2692         new_session->add_controllable(goto_start_controllable);
2693         new_session->add_controllable(goto_end_controllable);
2694         new_session->add_controllable(auto_loop_controllable);
2695         new_session->add_controllable(play_selection_controllable);
2696         new_session->add_controllable(rec_controllable);
2697
2698         set_session (new_session);
2699
2700         session_loaded = true;
2701
2702         goto_editor_window ();
2703
2704         if (_session) {
2705                 _session->set_clean ();
2706         }
2707
2708         flush_pending ();
2709         retval = 0;
2710
2711   out:
2712         return retval;
2713 }
2714
2715 int
2716 ARDOUR_UI::build_session (const std::string& path, const std::string& snap_name, BusProfile& bus_profile)
2717 {
2718         Session *new_session;
2719         int x;
2720
2721         if (!check_audioengine()) {
2722                 return -1;
2723         }
2724
2725         session_loaded = false;
2726
2727         x = unload_session ();
2728
2729         if (x < 0) {
2730                 return -1;
2731         } else if (x > 0) {
2732                 return 0;
2733         }
2734
2735         _session_is_new = true;
2736
2737         try {
2738                 new_session = new Session (*engine, path, snap_name, &bus_profile);
2739         }
2740
2741         catch (...) {
2742
2743                 MessageDialog msg (string_compose(_("Could not create session in \"%1\""), path));
2744                 pop_back_splash (msg);
2745                 msg.run ();
2746                 return -1;
2747         }
2748
2749         /* Give the new session the default GUI state, if such things exist */
2750
2751         XMLNode* n;
2752         n = Config->instant_xml (X_("Editor"));
2753         if (n) {
2754                 new_session->add_instant_xml (*n, false);
2755         }
2756         n = Config->instant_xml (X_("Mixer"));
2757         if (n) {
2758                 new_session->add_instant_xml (*n, false);
2759         }
2760
2761         /* Put the playhead at 0 and scroll fully left */
2762         n = new_session->instant_xml (X_("Editor"));
2763         if (n) {
2764                 n->add_property (X_("playhead"), X_("0"));
2765                 n->add_property (X_("left-frame"), X_("0"));
2766         }
2767
2768         set_session (new_session);
2769
2770         session_loaded = true;
2771
2772         new_session->save_state(new_session->name());
2773
2774         return 0;
2775 }
2776
2777 void
2778 ARDOUR_UI::launch_chat ()
2779 {
2780 #ifdef __APPLE__
2781         open_uri("http://webchat.freenode.net/?channels=ardour-osx");
2782 #else
2783         open_uri("http://webchat.freenode.net/?channels=ardour");
2784 #endif
2785 }
2786
2787 void
2788 ARDOUR_UI::show_about ()
2789 {
2790         if (about == 0) {
2791                 about = new About;
2792                 about->signal_response().connect (sigc::mem_fun (*this, &ARDOUR_UI::about_signal_response));
2793         }
2794
2795         about->set_transient_for(*editor);
2796         about->show_all ();
2797 }
2798
2799 void
2800 ARDOUR_UI::launch_manual ()
2801 {
2802         PBD::open_uri("http://ardour.org/flossmanual");
2803 }
2804
2805 void
2806 ARDOUR_UI::launch_reference ()
2807 {
2808         PBD::open_uri("http://ardour.org/refmanual");
2809 }
2810
2811 void
2812 ARDOUR_UI::hide_about ()
2813 {
2814         if (about) {
2815                 about->get_window()->set_cursor ();
2816                 about->hide ();
2817         }
2818 }
2819
2820 void
2821 ARDOUR_UI::about_signal_response (int /*response*/)
2822 {
2823         hide_about();
2824 }
2825
2826 void
2827 ARDOUR_UI::show_splash ()
2828 {
2829         if (splash == 0) {
2830                 try {
2831                         splash = new Splash;
2832                 } catch (...) {
2833                         return;
2834                 }
2835         }
2836
2837         splash->present ();
2838         splash->pop_front ();
2839         splash->queue_draw ();
2840         splash->get_window()->process_updates (true);
2841         flush_pending ();
2842 }
2843
2844 void
2845 ARDOUR_UI::hide_splash ()
2846 {
2847         if (splash) {
2848                 delete splash;
2849                 splash = 0;
2850         }
2851 }
2852
2853 void
2854 ARDOUR_UI::display_cleanup_results (ARDOUR::CleanupReport& rep, const gchar* list_title,
2855                                     const string& plural_msg, const string& singular_msg)
2856 {
2857         size_t removed;
2858
2859         removed = rep.paths.size();
2860
2861         if (removed == 0) {
2862                 MessageDialog msgd (*editor,
2863                                     _("No files were ready for clean-up"),
2864                                     true,
2865                                     Gtk::MESSAGE_INFO,
2866                                     Gtk::BUTTONS_OK);
2867                 msgd.set_title (_("Clean-up"));
2868                 msgd.set_secondary_text (_("If this seems suprising, \n\
2869 check for any existing snapshots.\n\
2870 These may still include regions that\n\
2871 require some unused files to continue to exist."));
2872
2873                 msgd.run ();
2874                 return;
2875         }
2876
2877         ArdourDialog results (_("Clean-up"), true, false);
2878
2879         struct CleanupResultsModelColumns : public Gtk::TreeModel::ColumnRecord {
2880             CleanupResultsModelColumns() {
2881                     add (visible_name);
2882                     add (fullpath);
2883             }
2884             Gtk::TreeModelColumn<std::string> visible_name;
2885             Gtk::TreeModelColumn<std::string> fullpath;
2886         };
2887
2888
2889         CleanupResultsModelColumns results_columns;
2890         Glib::RefPtr<Gtk::ListStore> results_model;
2891         Gtk::TreeView results_display;
2892
2893         results_model = ListStore::create (results_columns);
2894         results_display.set_model (results_model);
2895         results_display.append_column (list_title, results_columns.visible_name);
2896
2897         results_display.set_name ("CleanupResultsList");
2898         results_display.set_headers_visible (true);
2899         results_display.set_headers_clickable (false);
2900         results_display.set_reorderable (false);
2901
2902         Gtk::ScrolledWindow list_scroller;
2903         Gtk::Label txt;
2904         Gtk::VBox dvbox;
2905         Gtk::HBox dhbox;  // the hbox for the image and text
2906         Gtk::HBox ddhbox; // the hbox we eventually pack into the dialog's vbox
2907         Gtk::Image* dimage = manage (new Gtk::Image(Stock::DIALOG_INFO,  Gtk::ICON_SIZE_DIALOG));
2908
2909         dimage->set_alignment(ALIGN_LEFT, ALIGN_TOP);
2910
2911         const string dead_directory = _session->session_directory().dead_path().to_string();
2912
2913         /* subst:
2914            %1 - number of files removed
2915            %2 - location of "dead"
2916            %3 - size of files affected
2917            %4 - prefix for "bytes" to produce sensible results (e.g. mega, kilo, giga)
2918         */
2919
2920         const char* bprefix;
2921         double space_adjusted = 0;
2922
2923         if (rep.space < 1000) {
2924                 bprefix = X_("");
2925                 space_adjusted = rep.space;
2926         } else if (rep.space < 1000000) {
2927                 bprefix = X_("kilo");
2928                 space_adjusted = truncf((float)rep.space / 1000.0);
2929         } else if (rep.space < 1000000 * 1000) {
2930                 bprefix = X_("mega");
2931                 space_adjusted = truncf((float)rep.space / (1000.0 * 1000.0));
2932         } else {
2933                 bprefix = X_("giga");
2934                 space_adjusted = truncf((float)rep.space / (1000.0 * 1000 * 1000.0));
2935         }
2936
2937         if (removed > 1) {
2938                 txt.set_text (string_compose (plural_msg, removed, dead_directory, space_adjusted, bprefix, PROGRAM_NAME));
2939         } else {
2940                 txt.set_text (string_compose (singular_msg, removed, dead_directory, space_adjusted, bprefix, PROGRAM_NAME));
2941         }
2942
2943         dhbox.pack_start (*dimage, true, false, 5);
2944         dhbox.pack_start (txt, true, false, 5);
2945
2946         for (vector<string>::iterator i = rep.paths.begin(); i != rep.paths.end(); ++i) {
2947                 TreeModel::Row row = *(results_model->append());
2948                 row[results_columns.visible_name] = *i;
2949                 row[results_columns.fullpath] = *i;
2950         }
2951
2952         list_scroller.add (results_display);
2953         list_scroller.set_size_request (-1, 150);
2954         list_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
2955
2956         dvbox.pack_start (dhbox, true, false, 5);
2957         dvbox.pack_start (list_scroller, true, false, 5);
2958         ddhbox.pack_start (dvbox, true, false, 5);
2959
2960         results.get_vbox()->pack_start (ddhbox, true, false, 5);
2961         results.add_button (Stock::CLOSE, RESPONSE_CLOSE);
2962         results.set_default_response (RESPONSE_CLOSE);
2963         results.set_position (Gtk::WIN_POS_MOUSE);
2964
2965         results_display.show();
2966         list_scroller.show();
2967         txt.show();
2968         dvbox.show();
2969         dhbox.show();
2970         ddhbox.show();
2971         dimage->show();
2972
2973         //results.get_vbox()->show();
2974         results.set_resizable (false);
2975
2976         results.run ();
2977
2978 }
2979
2980 void
2981 ARDOUR_UI::cleanup ()
2982 {
2983         if (_session == 0) {
2984                 /* shouldn't happen: menu item is insensitive */
2985                 return;
2986         }
2987
2988
2989         MessageDialog checker (_("Are you sure you want to clean-up?"),
2990                                 true,
2991                                 Gtk::MESSAGE_QUESTION,
2992                                 Gtk::BUTTONS_NONE);
2993
2994         checker.set_title (_("Clean-up"));
2995
2996         checker.set_secondary_text(_("Clean-up is a destructive operation.\n\
2997 ALL undo/redo information will be lost if you clean-up.\n\
2998 Clean-up will move all unused files to a \"dead\" location."));
2999
3000         checker.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3001         checker.add_button (_("Clean-up"), RESPONSE_ACCEPT);
3002         checker.set_default_response (RESPONSE_CANCEL);
3003
3004         checker.set_name (_("CleanupDialog"));
3005         checker.set_wmclass (X_("ardour_cleanup"), PROGRAM_NAME);
3006         checker.set_position (Gtk::WIN_POS_MOUSE);
3007
3008         switch (checker.run()) {
3009         case RESPONSE_ACCEPT:
3010                 break;
3011         default:
3012                 return;
3013         }
3014
3015         ARDOUR::CleanupReport rep;
3016
3017         editor->prepare_for_cleanup ();
3018
3019         /* do not allow flush until a session is reloaded */
3020
3021         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Main"), X_("FlushWastebasket"));
3022         if (act) {
3023                 act->set_sensitive (false);
3024         }
3025
3026         if (_session->cleanup_sources (rep)) {
3027                 editor->finish_cleanup ();
3028                 return;
3029         }
3030
3031         editor->finish_cleanup ();
3032
3033         checker.hide();
3034         display_cleanup_results (rep,
3035                                  _("Cleaned Files"),
3036                                  _("\
3037 The following %1 files were not in use and \n\
3038 have been moved to:\n\n\
3039 %2\n\n\
3040 After a restart of %5,\n\n\
3041 Session -> Clean-up -> Flush Wastebasket\n\n\
3042 will release an additional\n\
3043 %3 %4bytes of disk space.\n"),
3044                                  _("\
3045 The following file was not in use and \n\
3046 has been moved to:\n                            \
3047 %2\n\n\
3048 After a restart of %5,\n\n\
3049 Session -> Clean-up -> Flush Wastebasket\n\n\
3050 will release an additional\n\
3051 %3 %4bytes of disk space.\n"
3052                                          ));
3053
3054 }
3055
3056 void
3057 ARDOUR_UI::flush_trash ()
3058 {
3059         if (_session == 0) {
3060                 /* shouldn't happen: menu item is insensitive */
3061                 return;
3062         }
3063
3064         ARDOUR::CleanupReport rep;
3065
3066         if (_session->cleanup_trash_sources (rep)) {
3067                 return;
3068         }
3069
3070         display_cleanup_results (rep,
3071                                  _("deleted file"),
3072                                  _("The following %1 files were deleted from\n\
3073 %2,\n\
3074 releasing %3 %4bytes of disk space"),
3075                                  _("The following file was deleted from\n\
3076 %2,\n\
3077 releasing %3 %4bytes of disk space"));
3078 }
3079
3080 void
3081 ARDOUR_UI::add_route (Gtk::Window* float_window)
3082 {
3083         int count;
3084
3085         if (!_session) {
3086                 return;
3087         }
3088
3089         if (add_route_dialog == 0) {
3090                 add_route_dialog = new AddRouteDialog (_session);
3091                 add_route_dialog->set_position (WIN_POS_MOUSE);
3092                 if (float_window) {
3093                         add_route_dialog->set_transient_for (*float_window);
3094                 }
3095         }
3096
3097         if (add_route_dialog->is_visible()) {
3098                 /* we're already doing this */
3099                 return;
3100         }
3101
3102         ResponseType r = (ResponseType) add_route_dialog->run ();
3103
3104         add_route_dialog->hide();
3105
3106         switch (r) {
3107                 case RESPONSE_ACCEPT:
3108                         break;
3109                 default:
3110                         return;
3111                         break;
3112         }
3113
3114         if ((count = add_route_dialog->count()) <= 0) {
3115                 return;
3116         }
3117
3118         string template_path = add_route_dialog->track_template();
3119
3120         if (!template_path.empty()) {
3121                 _session->new_route_from_template (count, template_path);
3122                 return;
3123         }
3124
3125         uint32_t input_chan = add_route_dialog->channels ();
3126         uint32_t output_chan;
3127         string name_template = add_route_dialog->name_template ();
3128         PluginInfoPtr instrument = add_route_dialog->requested_instrument ();
3129         RouteGroup* route_group = add_route_dialog->route_group ();
3130
3131         AutoConnectOption oac = Config->get_output_auto_connect();
3132
3133         if (oac & AutoConnectMaster) {
3134                 output_chan = (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan);
3135         } else {
3136                 output_chan = input_chan;
3137         }
3138
3139         /* XXX do something with name template */
3140
3141         if (add_route_dialog->midi_tracks_wanted()) {
3142                 session_add_midi_track (route_group, count, name_template, instrument);
3143         } else if (add_route_dialog->audio_tracks_wanted()) {
3144                 session_add_audio_track (input_chan, output_chan, add_route_dialog->mode(), route_group, count, name_template);
3145         } else {
3146                 session_add_audio_bus (input_chan, output_chan, route_group, count, name_template);
3147         }
3148 }
3149
3150 XMLNode*
3151 ARDOUR_UI::mixer_settings () const
3152 {
3153         XMLNode* node = 0;
3154
3155         if (_session) {
3156                 node = _session->instant_xml(X_("Mixer"));
3157         } else {
3158                 node = Config->instant_xml(X_("Mixer"));
3159         }
3160
3161         if (!node) {
3162                 node = new XMLNode (X_("Mixer"));
3163         }
3164
3165         return node;
3166 }
3167
3168 XMLNode*
3169 ARDOUR_UI::editor_settings () const
3170 {
3171         XMLNode* node = 0;
3172
3173         if (_session) {
3174                 node = _session->instant_xml(X_("Editor"));
3175         } else {
3176                 node = Config->instant_xml(X_("Editor"));
3177         }
3178
3179         if (!node) {
3180                 if (getenv("ARDOUR_INSTANT_XML_PATH")) {
3181                         node = Config->instant_xml(getenv("ARDOUR_INSTANT_XML_PATH"));
3182                 }
3183         }
3184
3185         if (!node) {
3186                 node = new XMLNode (X_("Editor"));
3187         }
3188
3189         return node;
3190 }
3191
3192 XMLNode*
3193 ARDOUR_UI::keyboard_settings () const
3194 {
3195         XMLNode* node = 0;
3196
3197         node = Config->extra_xml(X_("Keyboard"));
3198
3199         if (!node) {
3200                 node = new XMLNode (X_("Keyboard"));
3201         }
3202
3203         return node;
3204 }
3205
3206 void
3207 ARDOUR_UI::create_xrun_marker (framepos_t where)
3208 {
3209         editor->mouse_add_new_marker (where, false, true);
3210 }
3211
3212 void
3213 ARDOUR_UI::halt_on_xrun_message ()
3214 {
3215         MessageDialog msg (*editor,
3216                            _("Recording was stopped because your system could not keep up."));
3217         msg.run ();
3218 }
3219
3220 void
3221 ARDOUR_UI::xrun_handler (framepos_t where)
3222 {
3223         if (!_session) {
3224                 return;
3225         }
3226
3227         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::xrun_handler, where)
3228
3229         if (_session && Config->get_create_xrun_marker() && _session->actively_recording()) {
3230                 create_xrun_marker(where);
3231         }
3232
3233         if (_session && Config->get_stop_recording_on_xrun() && _session->actively_recording()) {
3234                 halt_on_xrun_message ();
3235         }
3236 }
3237
3238 void
3239 ARDOUR_UI::disk_overrun_handler ()
3240 {
3241         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_overrun_handler)
3242
3243         if (!have_disk_speed_dialog_displayed) {
3244                 have_disk_speed_dialog_displayed = true;
3245                 MessageDialog* msg = new MessageDialog (*editor, string_compose (_("\
3246 The disk system on your computer\n\
3247 was not able to keep up with %1.\n\
3248 \n\
3249 Specifically, it failed to write data to disk\n\
3250 quickly enough to keep up with recording.\n"), PROGRAM_NAME));
3251                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
3252                 msg->show ();
3253         }
3254 }
3255
3256 void
3257 ARDOUR_UI::disk_underrun_handler ()
3258 {
3259         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_underrun_handler)
3260
3261         if (!have_disk_speed_dialog_displayed) {
3262                 have_disk_speed_dialog_displayed = true;
3263                 MessageDialog* msg = new MessageDialog (
3264                         *editor, string_compose (_("The disk system on your computer\n\
3265 was not able to keep up with %1.\n\
3266 \n\
3267 Specifically, it failed to read data from disk\n\
3268 quickly enough to keep up with playback.\n"), PROGRAM_NAME));
3269                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
3270                 msg->show ();
3271         }
3272 }
3273
3274 void
3275 ARDOUR_UI::disk_speed_dialog_gone (int /*ignored_response*/, MessageDialog* msg)
3276 {
3277         have_disk_speed_dialog_displayed = false;
3278         delete msg;
3279 }
3280
3281 void
3282 ARDOUR_UI::session_dialog (std::string msg)
3283 {
3284         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::session_dialog, msg)
3285
3286         MessageDialog* d;
3287
3288         if (editor) {
3289                 d = new MessageDialog (*editor, msg, false, MESSAGE_INFO, BUTTONS_OK, true);
3290         } else {
3291                 d = new MessageDialog (msg, false, MESSAGE_INFO, BUTTONS_OK, true);
3292         }
3293
3294         d->show_all ();
3295         d->run ();
3296         delete d;
3297 }
3298
3299 int
3300 ARDOUR_UI::pending_state_dialog ()
3301 {
3302         HBox* hbox = new HBox();
3303         Image* image = new Image (Stock::DIALOG_QUESTION, ICON_SIZE_DIALOG);
3304         ArdourDialog dialog (_("Crash Recovery"), true);
3305         Label  message (string_compose (_("\
3306 This session appears to have been in\n\
3307 middle of recording when ardour or\n\
3308 the computer was shutdown.\n\
3309 \n\
3310 %1 can recover any captured audio for\n\
3311 you, or it can ignore it. Please decide\n\
3312 what you would like to do.\n"), PROGRAM_NAME));
3313         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
3314         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
3315         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
3316         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
3317         dialog.add_button (_("Ignore crash data"), RESPONSE_REJECT);
3318         dialog.add_button (_("Recover from crash"), RESPONSE_ACCEPT);
3319         dialog.set_default_response (RESPONSE_ACCEPT);
3320         dialog.set_position (WIN_POS_CENTER);
3321         message.show();
3322         image->show();
3323         hbox->show();
3324
3325         switch (dialog.run ()) {
3326         case RESPONSE_ACCEPT:
3327                 return 1;
3328         default:
3329                 return 0;
3330         }
3331 }
3332
3333 int
3334 ARDOUR_UI::sr_mismatch_dialog (framecnt_t desired, framecnt_t actual)
3335 {
3336         HBox* hbox = new HBox();
3337         Image* image = new Image (Stock::DIALOG_QUESTION, ICON_SIZE_DIALOG);
3338         ArdourDialog dialog (_("Sample Rate Mismatch"), true);
3339         Label  message (string_compose (_("\
3340 This session was created with a sample rate of %1 Hz, but\n\
3341 %2 is currently running at %3 Hz.  If you load this session,\n\
3342 audio may be played at the wrong sample rate.\n"), desired, PROGRAM_NAME, actual));
3343
3344         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
3345         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
3346         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
3347         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
3348         dialog.add_button (_("Do not load session"), RESPONSE_REJECT);
3349         dialog.add_button (_("Load session anyway"), RESPONSE_ACCEPT);
3350         dialog.set_default_response (RESPONSE_ACCEPT);
3351         dialog.set_position (WIN_POS_CENTER);
3352         message.show();
3353         image->show();
3354         hbox->show();
3355
3356         switch (dialog.run ()) {
3357         case RESPONSE_ACCEPT:
3358                 return 0;
3359         default:
3360                 return 1;
3361         }
3362 }
3363
3364
3365 void
3366 ARDOUR_UI::disconnect_from_jack ()
3367 {
3368         if (engine) {
3369                 if (engine->disconnect_from_jack ()) {
3370                         MessageDialog msg (*editor, _("Could not disconnect from JACK"));
3371                         msg.run ();
3372                 }
3373
3374                 update_sample_rate (0);
3375         }
3376 }
3377
3378 void
3379 ARDOUR_UI::reconnect_to_jack ()
3380 {
3381         if (engine) {
3382                 if (engine->reconnect_to_jack ()) {
3383                         MessageDialog msg (*editor,  _("Could not reconnect to JACK"));
3384                         msg.run ();
3385                 }
3386
3387                 update_sample_rate (0);
3388         }
3389 }
3390
3391 void
3392 ARDOUR_UI::use_config ()
3393 {
3394         XMLNode* node = Config->extra_xml (X_("TransportControllables"));
3395         if (node) {
3396                 set_transport_controllable_state (*node);
3397         }
3398 }
3399
3400 void
3401 ARDOUR_UI::update_transport_clocks (framepos_t pos)
3402 {
3403         if (Config->get_primary_clock_delta_edit_cursor()) {
3404                 primary_clock->set (pos, false, editor->get_preferred_edit_position());
3405         } else {
3406                 primary_clock->set (pos);
3407         }
3408
3409         if (Config->get_secondary_clock_delta_edit_cursor()) {
3410                 secondary_clock->set (pos, false, editor->get_preferred_edit_position());
3411         } else {
3412                 secondary_clock->set (pos);
3413         }
3414
3415         if (big_clock_window->get()) {
3416                 big_clock->set (pos);
3417         }
3418 }
3419
3420
3421 void
3422 ARDOUR_UI::step_edit_status_change (bool yn)
3423 {
3424         // XXX should really store pre-step edit status of things
3425         // we make insensitive
3426
3427         if (yn) {
3428                 rec_button.set_active_state (Gtkmm2ext::ImplicitActive);
3429                 rec_button.set_sensitive (false);
3430         } else {
3431                 rec_button.unset_active_state ();;
3432                 rec_button.set_sensitive (true);
3433         }
3434 }
3435
3436 void
3437 ARDOUR_UI::record_state_changed ()
3438 {
3439         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::record_state_changed);
3440
3441         if (!_session || !big_clock_window->get()) {
3442                 /* why bother - the clock isn't visible */
3443                 return;
3444         }
3445
3446         if (_session->record_status () == Session::Recording && _session->have_rec_enabled_track ()) {
3447                 big_clock->set_active (true);
3448         } else {
3449                 big_clock->set_active (false);
3450         }
3451 }
3452
3453 bool
3454 ARDOUR_UI::first_idle ()
3455 {
3456         if (_session) {
3457                 _session->allow_auto_play (true);
3458         }
3459
3460         if (editor) {
3461                 editor->first_idle();
3462         }
3463
3464         Keyboard::set_can_save_keybindings (true);
3465         return false;
3466 }
3467
3468 void
3469 ARDOUR_UI::store_clock_modes ()
3470 {
3471         XMLNode* node = new XMLNode(X_("ClockModes"));
3472
3473         for (vector<AudioClock*>::iterator x = AudioClock::clocks.begin(); x != AudioClock::clocks.end(); ++x) {
3474                 XMLNode* child = new XMLNode (X_("Clock"));
3475                 
3476                 child->add_property (X_("name"), (*x)->name());
3477                 child->add_property (X_("mode"), enum_2_string ((*x)->mode()));
3478                 child->add_property (X_("on"), ((*x)->off() ? X_("no") : X_("yes")));
3479
3480                 node->add_child_nocopy (*child);
3481         }
3482
3483         _session->add_extra_xml (*node);
3484         _session->set_dirty ();
3485 }
3486
3487 ARDOUR_UI::TransportControllable::TransportControllable (std::string name, ARDOUR_UI& u, ToggleType tp)
3488         : Controllable (name), ui (u), type(tp)
3489 {
3490
3491 }
3492
3493 void
3494 ARDOUR_UI::TransportControllable::set_value (double val)
3495 {
3496         if (val < 0.5) {
3497                 /* do nothing: these are radio-style actions */
3498                 return;
3499         }
3500
3501         const char *action = 0;
3502
3503         switch (type) {
3504         case Roll:
3505                 action = X_("Roll");
3506                 break;
3507         case Stop:
3508                 action = X_("Stop");
3509                 break;
3510         case GotoStart:
3511                 action = X_("Goto Start");
3512                 break;
3513         case GotoEnd:
3514                 action = X_("Goto End");
3515                 break;
3516         case AutoLoop:
3517                 action = X_("Loop");
3518                 break;
3519         case PlaySelection:
3520                 action = X_("Play Selection");
3521                 break;
3522         case RecordEnable:
3523                 action = X_("Record");
3524                 break;
3525         default:
3526                 break;
3527         }
3528
3529         if (action == 0) {
3530                 return;
3531         }
3532
3533         Glib::RefPtr<Action> act = ActionManager::get_action ("Transport", action);
3534
3535         if (act) {
3536                 act->activate ();
3537         }
3538 }
3539
3540 double
3541 ARDOUR_UI::TransportControllable::get_value (void) const
3542 {
3543         float val = 0.0;
3544
3545         switch (type) {
3546         case Roll:
3547                 break;
3548         case Stop:
3549                 break;
3550         case GotoStart:
3551                 break;
3552         case GotoEnd:
3553                 break;
3554         case AutoLoop:
3555                 break;
3556         case PlaySelection:
3557                 break;
3558         case RecordEnable:
3559                 break;
3560         default:
3561                 break;
3562         }
3563
3564         return val;
3565 }
3566
3567 void
3568 ARDOUR_UI::setup_profile ()
3569 {
3570         if (gdk_screen_width() < 1200 || getenv ("ARDOUR_NARROW_SCREEN")) {
3571                 Profile->set_small_screen ();
3572         }
3573
3574         if (getenv ("ARDOUR_SAE")) {
3575                 Profile->set_sae ();
3576                 Profile->set_single_package ();
3577         }
3578 }
3579
3580 void
3581 ARDOUR_UI::toggle_translations ()
3582 {
3583         using namespace Glib;
3584
3585         RefPtr<Action> act = ActionManager::get_action (X_("Main"), X_("EnableTranslation"));
3586         if (act) {
3587                 RefPtr<ToggleAction> ract = RefPtr<ToggleAction>::cast_dynamic (act);
3588                 if (ract) {
3589
3590                         string i18n_killer = ARDOUR::translation_kill_path();
3591
3592                         bool already_enabled = !ARDOUR::translations_are_disabled ();
3593
3594                         if (ract->get_active ()) {
3595                                 /* we don't care about errors */
3596                                 int fd = ::open (i18n_killer.c_str(), O_RDONLY|O_CREAT, 0644);
3597                                 close (fd);
3598                         } else {
3599                                 /* we don't care about errors */
3600                                 unlink (i18n_killer.c_str());
3601                         }
3602
3603                         if (already_enabled != ract->get_active()) {
3604                                 MessageDialog win (already_enabled ? _("Translations disabled") : _("Translations enabled"),
3605                                                    false,
3606                                                    Gtk::MESSAGE_WARNING,
3607                                                    Gtk::BUTTONS_OK);
3608                                 win.set_secondary_text (string_compose (_("You must restart %1 for this to take effect."), PROGRAM_NAME));
3609                                 win.set_position (Gtk::WIN_POS_CENTER);
3610                                 win.present ();
3611                                 win.run ();
3612                         }
3613                 }
3614         }
3615 }
3616
3617 /** Add a window proxy to our list, so that its state will be saved.
3618  *  This call also causes the window to be created and opened if its
3619  *  state was saved as `visible'.
3620  */
3621 void
3622 ARDOUR_UI::add_window_proxy (WindowProxyBase* p)
3623 {
3624         _window_proxies.push_back (p);
3625         p->maybe_show ();
3626 }
3627
3628 /** Remove a window proxy from our list.  Must be called if a WindowProxy
3629  *  is deleted, to prevent hanging pointers.
3630  */
3631 void
3632 ARDOUR_UI::remove_window_proxy (WindowProxyBase* p)
3633 {
3634         _window_proxies.remove (p);
3635 }
3636
3637 int
3638 ARDOUR_UI::missing_file (Session*s, std::string str, DataType type)
3639 {
3640         MissingFileDialog dialog (s, str, type);
3641
3642         dialog.show ();
3643         dialog.present ();
3644
3645         int result = dialog.run ();
3646         dialog.hide ();
3647
3648         switch (result) {
3649         case RESPONSE_OK:
3650                 break;
3651         default:
3652                 return 1; // quit entire session load
3653         }
3654
3655         result = dialog.get_action ();
3656
3657         return result;
3658 }
3659
3660 int
3661 ARDOUR_UI::ambiguous_file (std::string file, std::string /*path*/, std::vector<std::string> hits)
3662 {
3663         AmbiguousFileDialog dialog (file, hits);
3664
3665         dialog.show ();
3666         dialog.present ();
3667
3668         dialog.run ();
3669         return dialog.get_which ();
3670 }
3671
3672 /** Allocate our thread-local buffers */
3673 void
3674 ARDOUR_UI::get_process_buffers ()
3675 {
3676         _process_thread->get_buffers ();
3677 }
3678
3679 /** Drop our thread-local buffers */
3680 void
3681 ARDOUR_UI::drop_process_buffers ()
3682 {
3683         _process_thread->drop_buffers ();
3684 }
3685
3686 void
3687 ARDOUR_UI::feedback_detected ()
3688 {
3689         _feedback_exists = true;
3690 }
3691
3692 void
3693 ARDOUR_UI::successful_graph_sort ()
3694 {
3695         _feedback_exists = false;
3696 }
3697
3698 void
3699 ARDOUR_UI::midi_panic ()
3700 {
3701         if (_session) {
3702                 _session->midi_panic();
3703         }
3704 }