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