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