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