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