handle libXML errors via our own error handling methods
[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 #include "gtk2ardour-version.h"
23 #endif
24
25 #include <algorithm>
26 #include <cmath>
27 #include <iostream>
28 #include <cerrno>
29 #include <fstream>
30
31 #include <stdarg.h>
32
33 #ifndef PLATFORM_WINDOWS
34 #include <sys/resource.h>
35 #endif
36
37 #include <stdint.h>
38 #include <fcntl.h>
39 #include <signal.h>
40 #include <unistd.h>
41 #include <time.h>
42
43 #include <glib.h>
44 #include <glib/gstdio.h>
45
46 #include <gtkmm/messagedialog.h>
47 #include <gtkmm/accelmap.h>
48
49 #include "pbd/error.h"
50 #include "pbd/basename.h"
51 #include "pbd/compose.h"
52 #include "pbd/failed_constructor.h"
53 #include "pbd/enumwriter.h"
54 #include "pbd/memento_command.h"
55 #include "pbd/openuri.h"
56 #include "pbd/stl_delete.h"
57 #include "pbd/file_utils.h"
58 #include "pbd/localtime_r.h"
59 #include "pbd/pthread_utils.h"
60 #include "pbd/replace_all.h"
61 #include "pbd/xml++.h"
62
63 #include "gtkmm2ext/application.h"
64 #include "gtkmm2ext/bindings.h"
65 #include "gtkmm2ext/gtk_ui.h"
66 #include "gtkmm2ext/utils.h"
67 #include "gtkmm2ext/click_box.h"
68 #include "gtkmm2ext/fastmeter.h"
69 #include "gtkmm2ext/popup.h"
70 #include "gtkmm2ext/window_title.h"
71
72 #include "ardour/ardour.h"
73 #include "ardour/audio_backend.h"
74 #include "ardour/audioengine.h"
75 #include "ardour/audiofilesource.h"
76 #include "ardour/automation_watch.h"
77 #include "ardour/diskstream.h"
78 #include "ardour/filename_extensions.h"
79 #include "ardour/filesystem_paths.h"
80 #include "ardour/port.h"
81 #include "ardour/plugin_manager.h"
82 #include "ardour/process_thread.h"
83 #include "ardour/profile.h"
84 #include "ardour/recent_sessions.h"
85 #include "ardour/session_directory.h"
86 #include "ardour/session_route.h"
87 #include "ardour/session_state_utils.h"
88 #include "ardour/session_utils.h"
89 #include "ardour/slave.h"
90 #include "ardour/system_exec.h"
91
92 #ifdef WINDOWS_VST_SUPPORT
93 #include <fst.h>
94 #endif
95 #ifdef AUDIOUNIT_SUPPORT
96 #include "ardour/audio_unit.h"
97 #endif
98
99 #include "timecode/time.h"
100
101 typedef uint64_t microseconds_t;
102
103 #include "about.h"
104 #include "editing.h"
105 #include "actions.h"
106 #include "add_route_dialog.h"
107 #include "ambiguous_file_dialog.h"
108 #include "ardour_ui.h"
109 #include "audio_clock.h"
110 #include "big_clock_window.h"
111 #include "bundle_manager.h"
112 #include "engine_dialog.h"
113 #include "export_video_dialog.h"
114 #include "export_video_infobox.h"
115 #include "gain_meter.h"
116 #include "global_port_matrix.h"
117 #include "gui_object.h"
118 #include "gui_thread.h"
119 #include "keyboard.h"
120 #include "keyeditor.h"
121 #include "location_ui.h"
122 #include "main_clock.h"
123 #include "missing_file_dialog.h"
124 #include "missing_plugin_dialog.h"
125 #include "mixer_ui.h"
126 #include "mouse_cursors.h"
127 #include "nsm.h"
128 #include "opts.h"
129 #include "pingback.h"
130 #include "processor_box.h"
131 #include "prompter.h"
132 #include "public_editor.h"
133 #include "rc_option_editor.h"
134 #include "route_time_axis.h"
135 #include "route_params_ui.h"
136 #include "save_as_dialog.h"
137 #include "session_dialog.h"
138 #include "session_metadata_dialog.h"
139 #include "session_option_editor.h"
140 #include "shuttle_control.h"
141 #include "speaker_dialog.h"
142 #include "splash.h"
143 #include "startup.h"
144 #include "theme_manager.h"
145 #include "time_axis_view_item.h"
146 #include "timers.h"
147 #include "utils.h"
148 #include "video_server_dialog.h"
149 #include "add_video_dialog.h"
150 #include "transcode_video_dialog.h"
151
152 #include "i18n.h"
153
154 using namespace ARDOUR;
155 using namespace ARDOUR_UI_UTILS;
156 using namespace PBD;
157 using namespace Gtkmm2ext;
158 using namespace Gtk;
159 using namespace std;
160 using namespace Editing;
161
162 ARDOUR_UI *ARDOUR_UI::theArdourUI = 0;
163
164 sigc::signal<void, framepos_t, bool, framepos_t> ARDOUR_UI::Clock;
165 sigc::signal<void>      ARDOUR_UI::CloseAllDialogs;
166
167 float ARDOUR_UI::ui_scale = 1.0;
168
169 static bool
170 ask_about_configuration_copy (string const & old_dir, string const & new_dir, int version)
171 {
172         MessageDialog msg (string_compose (_("%1 %2.x has discovered configuration files from %1 %3.x.\n\n"
173                                              "Would you like these files to be copied and used for %1 %2.x?\n\n"
174                                              "(This will require you to restart %1.)"),
175                                            PROGRAM_NAME, PROGRAM_VERSION, version),
176                            false, /* no markup */
177                            Gtk::MESSAGE_INFO,
178                            Gtk::BUTTONS_YES_NO,
179                            true /* modal, though it hardly matters since it is the only window */
180                 );
181
182         msg.set_default_response (Gtk::RESPONSE_YES);
183         msg.show_all ();
184
185         return (msg.run() == Gtk::RESPONSE_YES);
186 }
187
188 static void
189 libxml_generic_error_func (void* /* parsing_context*/,
190                    const char* msg,
191                    ...)
192 {
193         va_list ap;
194         char buf[2048];
195
196         va_start (ap, msg);
197         vsnprintf (buf, sizeof (buf), msg, ap);
198         error << buf << endmsg;
199         va_end (ap);
200 }
201
202 static void
203 libxml_structured_error_func (void* /* parsing_context*/,
204                               xmlErrorPtr err)
205 {
206         string msg = err->message;
207
208         replace_all (msg, "\n", "");
209
210         error << X_("XML error: ") << msg << " in " << err->file << " at line " << err->line;
211         if (err->int2) {
212                 error << ':' << err->int2;
213         }
214         error << endmsg;
215 }
216
217
218 ARDOUR_UI::ARDOUR_UI (int *argcp, char **argvp[], const char* localedir, UIConfiguration* uic)
219
220         : Gtkmm2ext::UI (PROGRAM_NAME, argcp, argvp)
221         , ui_config (uic->post_gui_init ())
222         , session_loaded (false)
223         , gui_object_state (new GUIObjectState)
224         , primary_clock   (new MainClock (X_("primary"),   X_("transport"), true ))
225         , secondary_clock (new MainClock (X_("secondary"), X_("secondary"), false))
226         , big_clock (new AudioClock (X_("bigclock"), false, "big", true, true, false, false))
227         , video_timeline(0)
228         , ignore_dual_punch (false)
229         , editor (0)
230         , mixer (0)
231         , nsm (0)
232         , _was_dirty (false)
233         , _mixer_on_top (false)
234         , first_time_engine_run (true)
235         , roll_controllable (new TransportControllable ("transport roll", *this, TransportControllable::Roll))
236         , stop_controllable (new TransportControllable ("transport stop", *this, TransportControllable::Stop))
237         , goto_start_controllable (new TransportControllable ("transport goto start", *this, TransportControllable::GotoStart))
238         , goto_end_controllable (new TransportControllable ("transport goto end", *this, TransportControllable::GotoEnd))
239         , auto_loop_controllable (new TransportControllable ("transport auto loop", *this, TransportControllable::AutoLoop))
240         , play_selection_controllable (new TransportControllable ("transport play selection", *this, TransportControllable::PlaySelection))
241         , rec_controllable (new TransportControllable ("transport rec-enable", *this, TransportControllable::RecordEnable))
242         , auto_return_button (ArdourButton::led_default_elements)
243         , follow_edits_button (ArdourButton::led_default_elements)
244         , auto_input_button (ArdourButton::led_default_elements)
245         , auditioning_alert_button (_("Audition"))
246         , solo_alert_button (_("Solo"))
247         , feedback_alert_button (_("Feedback"))
248         , error_alert_button ( ArdourButton::just_led_default_elements )
249         , editor_meter(0)
250         , editor_meter_peak_display()
251         , session_selector_window (0)
252         , open_session_selector (0)
253         , _numpad_locate_happening (false)
254         , _session_is_new (false)
255         , last_key_press_time (0)
256         , save_as_dialog (0)
257         , meterbridge (0)
258         , speaker_config_window (X_("speaker-config"), _("Speaker Configuration"))
259         , key_editor (X_("key-editor"), _("Key Bindings"))
260         , rc_option_editor (X_("rc-options-editor"), _("Preferences"))
261         , add_route_dialog (X_("add-routes"), _("Add Tracks/Busses"))
262         , about (X_("about"), _("About"))
263         , location_ui (X_("locations"), _("Locations"))
264         , route_params (X_("inspector"), _("Tracks and Busses"))
265         , audio_midi_setup (X_("audio-midi-setup"), _("Audio/MIDI Setup"))
266         , export_video_dialog (X_("video-export"), _("Video Export Dialog"))
267         , session_option_editor (X_("session-options-editor"), _("Properties"), boost::bind (&ARDOUR_UI::create_session_option_editor, this))
268         , add_video_dialog (X_("add-video"), _("Add Tracks/Busses"), boost::bind (&ARDOUR_UI::create_add_video_dialog, this))
269         , bundle_manager (X_("bundle-manager"), _("Bundle Manager"), boost::bind (&ARDOUR_UI::create_bundle_manager, this))
270         , big_clock_window (X_("big-clock"), _("Big Clock"), boost::bind (&ARDOUR_UI::create_big_clock_window, this))
271         , audio_port_matrix (X_("audio-connection-manager"), _("Audio Connections"), boost::bind (&ARDOUR_UI::create_global_port_matrix, this, ARDOUR::DataType::AUDIO))
272         , midi_port_matrix (X_("midi-connection-manager"), _("MIDI Connections"), boost::bind (&ARDOUR_UI::create_global_port_matrix, this, ARDOUR::DataType::MIDI))
273         , video_server_process (0)
274         , splash (0)
275         , have_configure_timeout (false)
276         , last_configure_time (0)
277         , last_peak_grab (0)
278         , have_disk_speed_dialog_displayed (false)
279         , _status_bar_visibility (X_("status-bar"))
280         , _feedback_exists (false)
281         , _log_not_acknowledged (LogLevelNone)
282 {
283         Gtkmm2ext::init (localedir);
284
285         if (ARDOUR::handle_old_configuration_files (boost::bind (ask_about_configuration_copy, _1, _2, _3))) {
286                 MessageDialog msg (string_compose (_("Your configuration files were copied. You can now restart %1."), PROGRAM_NAME), true);
287                 msg.run ();
288                 /* configuration was modified, exit immediately */
289                 _exit (0);
290         }
291         
292         if (theArdourUI == 0) {
293                 theArdourUI = this;
294         }
295
296         /* stop libxml from spewing to stdout/stderr */
297
298         xmlSetGenericErrorFunc (this, libxml_generic_error_func);
299         xmlSetStructuredErrorFunc (this, libxml_structured_error_func);
300         
301         ui_config->ParameterChanged.connect (sigc::mem_fun (*this, &ARDOUR_UI::parameter_changed));
302         boost::function<void (string)> pc (boost::bind (&ARDOUR_UI::parameter_changed, this, _1));
303         ui_config->map_parameters (pc);
304
305         roll_button.set_controllable (roll_controllable);
306         stop_button.set_controllable (stop_controllable);
307         goto_start_button.set_controllable (goto_start_controllable);
308         goto_end_button.set_controllable (goto_end_controllable);
309         auto_loop_button.set_controllable (auto_loop_controllable);
310         play_selection_button.set_controllable (play_selection_controllable);
311         rec_button.set_controllable (rec_controllable);
312
313         roll_button.set_name ("transport button");
314         stop_button.set_name ("transport button");
315         goto_start_button.set_name ("transport button");
316         goto_end_button.set_name ("transport button");
317         auto_loop_button.set_name ("transport button");
318         play_selection_button.set_name ("transport button");
319         rec_button.set_name ("transport recenable button");
320         midi_panic_button.set_name ("transport button");
321
322         ARDOUR::Diskstream::DiskOverrun.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::disk_overrun_handler, this), gui_context());
323         ARDOUR::Diskstream::DiskUnderrun.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::disk_underrun_handler, this), gui_context());
324
325         ARDOUR::Session::VersionMismatch.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::session_format_mismatch, this, _1, _2), gui_context());
326
327         /* handle dialog requests */
328
329         ARDOUR::Session::Dialog.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::session_dialog, this, _1), gui_context());
330
331         /* handle pending state with a dialog (PROBLEM: needs to return a value and thus cannot be x-thread) */
332
333         ARDOUR::Session::AskAboutPendingState.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::pending_state_dialog, this));
334
335         /* handle Audio/MIDI setup when session requires it */
336
337         ARDOUR::Session::AudioEngineSetupRequired.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::do_audio_midi_setup, this, _1));
338
339         /* handle sr mismatch with a dialog (PROBLEM: needs to return a value and thus cannot be x-thread) */
340
341         ARDOUR::Session::AskAboutSampleRateMismatch.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::sr_mismatch_dialog, this, _1, _2));
342
343         /* handle requests to quit (coming from JACK session) */
344
345         ARDOUR::Session::Quit.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::finish, this), gui_context ());
346
347         /* tell the user about feedback */
348
349         ARDOUR::Session::FeedbackDetected.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::feedback_detected, this), gui_context ());
350         ARDOUR::Session::SuccessfulGraphSort.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::successful_graph_sort, this), gui_context ());
351
352         /* handle requests to deal with missing files */
353
354         ARDOUR::Session::MissingFile.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::missing_file, this, _1, _2, _3));
355
356         /* and ambiguous files */
357
358         ARDOUR::FileSource::AmbiguousFileName.connect_same_thread (forever_connections, boost::bind (&ARDOUR_UI::ambiguous_file, this, _1, _2));
359
360         /* also plugin scan messages */
361         ARDOUR::PluginScanMessage.connect (forever_connections, MISSING_INVALIDATOR, boost::bind(&ARDOUR_UI::plugin_scan_dialog, this, _1, _2, _3), gui_context());
362         ARDOUR::PluginScanTimeout.connect (forever_connections, MISSING_INVALIDATOR, boost::bind(&ARDOUR_UI::plugin_scan_timeout, this, _1), gui_context());
363
364         ARDOUR::GUIIdle.connect (forever_connections, MISSING_INVALIDATOR, boost::bind(&ARDOUR_UI::gui_idle_handler, this), gui_context());
365
366         Config->ParameterChanged.connect ( forever_connections, MISSING_INVALIDATOR, boost::bind(&ARDOUR_UI::set_flat_buttons, this), gui_context() );
367         set_flat_buttons();
368
369         /* lets get this party started */
370
371         setup_gtk_ardour_enums ();
372         setup_profile ();
373
374         SessionEvent::create_per_thread_pool ("GUI", 512);
375
376         /* we like keyboards */
377
378         keyboard = new ArdourKeyboard(*this);
379
380         XMLNode* node = ARDOUR_UI::instance()->keyboard_settings();
381         if (node) {
382                 keyboard->set_state (*node, Stateful::loading_state_version);
383         }
384
385         /* we don't like certain modifiers */
386         Bindings::set_ignored_state (GDK_LOCK_MASK|GDK_MOD2_MASK|GDK_MOD3_MASK);
387
388         reset_dpi();
389
390         TimeAxisViewItem::set_constant_heights ();
391
392         /* Set this up so that our window proxies can register actions */
393
394         ActionManager::init ();
395
396         /* The following must happen after ARDOUR::init() so that Config is set up */
397
398         const XMLNode* ui_xml = Config->extra_xml (X_("UI"));
399
400         if (ui_xml) {
401                 key_editor.set_state (*ui_xml);
402                 rc_option_editor.set_state (*ui_xml);
403                 session_option_editor.set_state (*ui_xml);
404                 speaker_config_window.set_state (*ui_xml);
405                 about.set_state (*ui_xml);
406                 add_route_dialog.set_state (*ui_xml);
407                 add_video_dialog.set_state (*ui_xml);
408                 route_params.set_state (*ui_xml);
409                 bundle_manager.set_state (*ui_xml);
410                 location_ui.set_state (*ui_xml);
411                 big_clock_window.set_state (*ui_xml);
412                 audio_port_matrix.set_state (*ui_xml);
413                 midi_port_matrix.set_state (*ui_xml);
414                 export_video_dialog.set_state (*ui_xml);
415         }
416
417         WM::Manager::instance().register_window (&key_editor);
418         WM::Manager::instance().register_window (&rc_option_editor);
419         WM::Manager::instance().register_window (&session_option_editor);
420         WM::Manager::instance().register_window (&speaker_config_window);
421         WM::Manager::instance().register_window (&about);
422         WM::Manager::instance().register_window (&add_route_dialog);
423         WM::Manager::instance().register_window (&add_video_dialog);
424         WM::Manager::instance().register_window (&route_params);
425         WM::Manager::instance().register_window (&audio_midi_setup);
426         WM::Manager::instance().register_window (&export_video_dialog);
427         WM::Manager::instance().register_window (&bundle_manager);
428         WM::Manager::instance().register_window (&location_ui);
429         WM::Manager::instance().register_window (&big_clock_window);
430         WM::Manager::instance().register_window (&audio_port_matrix);
431         WM::Manager::instance().register_window (&midi_port_matrix);
432
433         /* Trigger setting up the color scheme and loading the GTK RC file */
434
435         ARDOUR_UI::config()->load_rc_file (false);
436         
437         _process_thread = new ProcessThread ();
438         _process_thread->init ();
439
440         DPIReset.connect (sigc::mem_fun (*this, &ARDOUR_UI::resize_text_widgets));
441
442         attach_to_engine ();
443 }
444
445 GlobalPortMatrixWindow*
446 ARDOUR_UI::create_global_port_matrix (ARDOUR::DataType type)
447 {
448         if (!_session) {
449                 return 0;
450         }
451         return new GlobalPortMatrixWindow (_session, type);
452 }
453
454 void
455 ARDOUR_UI::attach_to_engine ()
456 {
457         AudioEngine::instance()->Running.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::engine_running, this), gui_context());
458         ARDOUR::Port::set_connecting_blocked (ARDOUR_COMMAND_LINE::no_connect_ports);
459 }
460
461 void
462 ARDOUR_UI::engine_stopped ()
463 {
464         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::engine_stopped)
465         ActionManager::set_sensitive (ActionManager::engine_sensitive_actions, false);
466         ActionManager::set_sensitive (ActionManager::engine_opposite_sensitive_actions, true);
467 }
468
469 void
470 ARDOUR_UI::engine_running ()
471 {
472         if (first_time_engine_run) {
473                 post_engine();
474                 first_time_engine_run = false;
475         } 
476         
477         if (_session) {
478                 _session->reset_xrun_count ();
479         }
480         update_disk_space ();
481         update_cpu_load ();
482         update_xrun_count ();
483         update_sample_rate (AudioEngine::instance()->sample_rate());
484         update_timecode_format ();
485 }
486
487 void
488 ARDOUR_UI::engine_halted (const char* reason, bool free_reason)
489 {
490         if (!Gtkmm2ext::UI::instance()->caller_is_ui_thread()) {
491                 /* we can't rely on the original string continuing to exist when we are called
492                    again in the GUI thread, so make a copy and note that we need to
493                    free it later.
494                 */
495                 char *copy = strdup (reason);
496                 Gtkmm2ext::UI::instance()->call_slot (MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::engine_halted, this, copy, true));
497                 return;
498         }
499
500         ActionManager::set_sensitive (ActionManager::engine_sensitive_actions, false);
501         ActionManager::set_sensitive (ActionManager::engine_opposite_sensitive_actions, true);
502
503         update_sample_rate (0);
504
505         string msgstr;
506
507         /* if the reason is a non-empty string, it means that the backend was shutdown
508            rather than just Ardour.
509         */
510
511         if (strlen (reason)) {
512                 msgstr = string_compose (_("The audio backend was shutdown because:\n\n%1"), reason);
513         } else {
514                 msgstr = string_compose (_("\
515 The audio backend has either been shutdown or it\n\
516 disconnected %1 because %1\n\
517 was not fast enough. Try to restart\n\
518 the audio backend and save the session."), PROGRAM_NAME);
519         }
520
521         MessageDialog msg (*editor, msgstr);
522         pop_back_splash (msg);
523         msg.run ();
524         
525         if (free_reason) {
526                 free (const_cast<char*> (reason));
527         }
528 }
529
530 void
531 ARDOUR_UI::post_engine ()
532 {
533         /* Things to be done once (and once ONLY) after we have a backend running in the AudioEngine
534          */
535 #ifdef AUDIOUNIT_SUPPORT
536         std::string au_msg;
537         if (AUPluginInfo::au_get_crashlog(au_msg)) {
538                 popup_error(_("Audio Unit Plugin Scan Failed. Automatic AU scanning has been disabled. Please see the log window for further details."));
539                 error << _("Audio Unit Plugin Scan Failed:") << endmsg;
540                 info << au_msg << endmsg;
541         }
542 #endif
543
544         ARDOUR::init_post_engine ();
545         
546         /* connect to important signals */
547
548         AudioEngine::instance()->Stopped.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::engine_stopped, this), gui_context());
549         AudioEngine::instance()->SampleRateChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::update_sample_rate, this, _1), gui_context());
550         AudioEngine::instance()->BufferSizeChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::update_sample_rate, this, _1), gui_context());
551         AudioEngine::instance()->Halted.connect_same_thread (halt_connection, boost::bind (&ARDOUR_UI::engine_halted, this, _1, false));
552         AudioEngine::instance()->BecameSilent.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::audioengine_became_silent, this), gui_context());
553
554         _tooltips.enable();
555
556         if (setup_windows ()) {
557                 throw failed_constructor ();
558         }
559
560         /* Do this after setup_windows (), as that's when the _status_bar_visibility is created */
561         XMLNode* n = Config->extra_xml (X_("UI"));
562         if (n) {
563                 _status_bar_visibility.set_state (*n);
564         }
565         
566         check_memory_locking();
567
568         /* this is the first point at which all the keybindings are available */
569
570         if (ARDOUR_COMMAND_LINE::show_key_actions) {
571                 vector<string> names;
572                 vector<string> paths;
573                 vector<string> tooltips;
574                 vector<string> keys;
575                 vector<AccelKey> bindings;
576
577                 ActionManager::get_all_actions (names, paths, tooltips, keys, bindings);
578
579                 vector<string>::iterator n;
580                 vector<string>::iterator k;
581                 vector<string>::iterator p;
582                 for (n = names.begin(), k = keys.begin(), p = paths.begin(); n != names.end(); ++n, ++k, ++p) {
583                         cout << "Action: '" << (*n) << "' bound to '" << (*k) << "' Path: '" << (*p) << "'" << endl;
584                 }
585
586                 halt_connection.disconnect ();
587                 AudioEngine::instance()->stop ();
588                 exit (0);
589         }
590
591         /* this being a GUI and all, we want peakfiles */
592
593         AudioFileSource::set_build_peakfiles (true);
594         AudioFileSource::set_build_missing_peakfiles (true);
595
596         /* set default clock modes */
597
598         if (Profile->get_sae()) {
599                 primary_clock->set_mode (AudioClock::BBT);
600                 secondary_clock->set_mode (AudioClock::MinSec);
601         }  else {
602                 primary_clock->set_mode (AudioClock::Timecode);
603                 secondary_clock->set_mode (AudioClock::BBT);
604         }
605
606         /* start the time-of-day-clock */
607
608 #ifndef GTKOSX
609         /* OS X provides a nearly-always visible wallclock, so don't be stupid */
610         update_wall_clock ();
611         Glib::signal_timeout().connect_seconds (sigc::mem_fun(*this, &ARDOUR_UI::update_wall_clock), 1);
612 #endif
613
614         {
615                 DisplaySuspender ds;
616                 Config->ParameterChanged.connect (forever_connections, MISSING_INVALIDATOR, boost::bind (&ARDOUR_UI::parameter_changed, this, _1), gui_context());
617                 boost::function<void (string)> pc (boost::bind (&ARDOUR_UI::parameter_changed, this, _1));
618                 Config->map_parameters (pc);
619
620                 ui_config->map_parameters (pc);
621         }
622 }
623
624 ARDOUR_UI::~ARDOUR_UI ()
625 {
626         ui_config->save_state();
627
628         stop_video_server();
629
630         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
631                 // don't bother at 'real' exit. the OS cleans up for us.
632                 delete big_clock;
633                 delete primary_clock;
634                 delete secondary_clock;
635                 delete _process_thread;
636                 delete gui_object_state;
637                 FastMeter::flush_pattern_cache ();
638         }
639 }
640
641 void
642 ARDOUR_UI::pop_back_splash (Gtk::Window& win)
643 {
644         if (Splash::instance()) {
645                 Splash::instance()->pop_back_for (win);
646         }
647 }
648
649 gint
650 ARDOUR_UI::configure_timeout ()
651 {
652         if (last_configure_time == 0) {
653                 /* no configure events yet */
654                 return true;
655         }
656
657         /* force a gap of 0.5 seconds since the last configure event
658          */
659
660         if (get_microseconds() - last_configure_time < 500000) {
661                 return true;
662         } else {
663                 have_configure_timeout = false;
664                 save_ardour_state ();
665                 return false;
666         }
667 }
668
669 gboolean
670 ARDOUR_UI::configure_handler (GdkEventConfigure* /*conf*/)
671 {
672         if (have_configure_timeout) {
673                 last_configure_time = get_microseconds();
674         } else {
675                 Glib::signal_timeout().connect (sigc::mem_fun(*this, &ARDOUR_UI::configure_timeout), 100);
676                 have_configure_timeout = true;
677         }
678
679         return FALSE;
680 }
681
682 void
683 ARDOUR_UI::set_transport_controllable_state (const XMLNode& node)
684 {
685         const XMLProperty* prop;
686
687         if ((prop = node.property ("roll")) != 0) {
688                 roll_controllable->set_id (prop->value());
689         }
690         if ((prop = node.property ("stop")) != 0) {
691                 stop_controllable->set_id (prop->value());
692         }
693         if ((prop = node.property ("goto-start")) != 0) {
694                 goto_start_controllable->set_id (prop->value());
695         }
696         if ((prop = node.property ("goto-end")) != 0) {
697                 goto_end_controllable->set_id (prop->value());
698         }
699         if ((prop = node.property ("auto-loop")) != 0) {
700                 auto_loop_controllable->set_id (prop->value());
701         }
702         if ((prop = node.property ("play-selection")) != 0) {
703                 play_selection_controllable->set_id (prop->value());
704         }
705         if ((prop = node.property ("rec")) != 0) {
706                 rec_controllable->set_id (prop->value());
707         }
708         if ((prop = node.property ("shuttle")) != 0) {
709                 shuttle_box->controllable()->set_id (prop->value());
710         }
711 }
712
713 XMLNode&
714 ARDOUR_UI::get_transport_controllable_state ()
715 {
716         XMLNode* node = new XMLNode(X_("TransportControllables"));
717         char buf[64];
718
719         roll_controllable->id().print (buf, sizeof (buf));
720         node->add_property (X_("roll"), buf);
721         stop_controllable->id().print (buf, sizeof (buf));
722         node->add_property (X_("stop"), buf);
723         goto_start_controllable->id().print (buf, sizeof (buf));
724         node->add_property (X_("goto_start"), buf);
725         goto_end_controllable->id().print (buf, sizeof (buf));
726         node->add_property (X_("goto_end"), buf);
727         auto_loop_controllable->id().print (buf, sizeof (buf));
728         node->add_property (X_("auto_loop"), buf);
729         play_selection_controllable->id().print (buf, sizeof (buf));
730         node->add_property (X_("play_selection"), buf);
731         rec_controllable->id().print (buf, sizeof (buf));
732         node->add_property (X_("rec"), buf);
733         shuttle_box->controllable()->id().print (buf, sizeof (buf));
734         node->add_property (X_("shuttle"), buf);
735
736         return *node;
737 }
738
739 void
740 ARDOUR_UI::save_session_at_its_request (std::string snapshot_name)
741 {
742         if (_session) {
743                 _session->save_state (snapshot_name);
744         }
745 }
746
747 gint
748 ARDOUR_UI::autosave_session ()
749 {
750         if (g_main_depth() > 1) {
751                 /* inside a recursive main loop,
752                    give up because we may not be able to
753                    take a lock.
754                 */
755                 return 1;
756         }
757
758         if (!Config->get_periodic_safety_backups()) {
759                 return 1;
760         }
761
762         if (_session) {
763                 _session->maybe_write_autosave();
764         }
765
766         return 1;
767 }
768
769 void
770 ARDOUR_UI::update_autosave ()
771 {
772         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::update_autosave)
773
774         if (_session && _session->dirty()) {
775                 if (_autosave_connection.connected()) {
776                         _autosave_connection.disconnect();
777                 }
778
779                 _autosave_connection = Glib::signal_timeout().connect (sigc::mem_fun (*this, &ARDOUR_UI::autosave_session),
780                                 Config->get_periodic_safety_backup_interval() * 1000);
781
782         } else {
783                 if (_autosave_connection.connected()) {
784                         _autosave_connection.disconnect();
785                 }
786         }
787 }
788
789 void
790 ARDOUR_UI::check_announcements ()
791 {
792 #ifdef PHONE_HOME
793         string _annc_filename;
794
795 #ifdef __APPLE__
796         _annc_filename = PROGRAM_NAME "_announcements_osx_";
797 #else
798         _annc_filename = PROGRAM_NAME "_announcements_linux_";
799 #endif
800         _annc_filename.append (VERSIONSTRING);
801
802         std::string path = Glib::build_filename (user_config_directory(), _annc_filename);
803         std::ifstream announce_file (path.c_str());
804         if ( announce_file.fail() )
805                 _announce_string = "";
806         else {
807                 std::stringstream oss;
808                 oss << announce_file.rdbuf();
809                 _announce_string = oss.str();
810         }
811
812         pingback (VERSIONSTRING, path);
813 #endif
814 }
815
816 int
817 ARDOUR_UI::starting ()
818 {
819         Application* app = Application::instance ();
820         const char *nsm_url;
821         bool brand_new_user = ArdourStartup::required ();
822
823         app->ShouldQuit.connect (sigc::mem_fun (*this, &ARDOUR_UI::queue_finish));
824         app->ShouldLoad.connect (sigc::mem_fun (*this, &ARDOUR_UI::load_from_application_api));
825
826         if (ARDOUR_COMMAND_LINE::check_announcements) {
827                 check_announcements ();
828         }
829
830         app->ready ();
831
832         /* we need to create this early because it may need to set the
833          *  audio backend end up.
834          */
835         
836         try {
837                 audio_midi_setup.get (true);
838         } catch (...) {
839                 std::cerr << "audio-midi engine setup failed."<< std::endl;
840                 return -1;
841         }
842
843         if ((nsm_url = g_getenv ("NSM_URL")) != 0) {
844                 nsm = new NSM_Client;
845                 if (!nsm->init (nsm_url)) {
846                         /* the ardour executable may have different names:
847                          *
848                          * waf's obj.target for distro versions: eg ardour4, ardourvst4
849                          * Ardour4, Mixbus3 for bundled versions + full path on OSX & windows
850                          * argv[0] does not apply since we need the wrapper-script (not the binary itself)
851                          *
852                          * The wrapper startup script should set the environment variable 'ARDOUR_SELF'
853                          */
854                         const char *process_name = g_getenv ("ARDOUR_SELF");
855                         nsm->announce (PROGRAM_NAME, ":dirty:", process_name ? process_name : "ardour4");
856
857                         unsigned int i = 0;
858                         // wait for announce reply from nsm server
859                         for ( i = 0; i < 5000; ++i) {
860                                 nsm->check ();
861
862                                 Glib::usleep (i);
863                                 if (nsm->is_active()) {
864                                         break;
865                                 }
866                         }
867                         if (i == 5000) {
868                                 error << _("NSM server did not announce itself") << endmsg;
869                                 return -1;
870                         }
871                         // wait for open command from nsm server
872                         for ( i = 0; i < 5000; ++i) {
873                                 nsm->check ();
874                                 Glib::usleep (1000);
875                                 if (nsm->client_id ()) {
876                                         break;
877                                 }
878                         }
879
880                         if (i == 5000) {
881                                 error << _("NSM: no client ID provided") << endmsg;
882                                 return -1;
883                         }
884
885                         if (_session && nsm) {
886                                 _session->set_nsm_state( nsm->is_active() );
887                         } else {
888                                 error << _("NSM: no session created") << endmsg;
889                                 return -1;
890                         }
891
892                         // nsm requires these actions disabled
893                         vector<string> action_names;
894                         action_names.push_back("SaveAs");
895                         action_names.push_back("Rename");
896                         action_names.push_back("New");
897                         action_names.push_back("Open");
898                         action_names.push_back("Recent");
899                         action_names.push_back("Close");
900
901                         for (vector<string>::const_iterator n = action_names.begin(); n != action_names.end(); ++n) {
902                                 Glib::RefPtr<Action> act = ActionManager::get_action (X_("Main"), (*n).c_str());
903                                 if (act) {
904                                         act->set_sensitive (false);
905                                 }
906                         }
907
908                 } else {
909                         delete nsm;
910                         nsm = 0;
911                         error << _("NSM: initialization failed") << endmsg;
912                         return -1;
913                 }
914
915         } else  {
916                 
917                 if (brand_new_user) {
918                         ArdourStartup s;
919                         s.present ();
920                         main().run();
921                         s.hide ();
922                         switch (s.response ()) {
923                         case Gtk::RESPONSE_OK:
924                                 break;
925                         default:
926                                 return -1;
927                         }
928                 }
929
930 #ifdef NO_PLUGIN_STATE
931
932                 ARDOUR::RecentSessions rs;
933                 ARDOUR::read_recent_sessions (rs);
934
935                 string path = Glib::build_filename (user_config_directory(), ".iknowaboutfreeversion");
936                 
937                 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS) && !rs.empty()) {
938                         
939                         /* already used Ardour, have sessions ... warn about plugin state */
940                         
941                         ArdourDialog d (_("Free/Demo Version Warning"), true);
942                         Label l;
943                         Button b (string_compose (_("Subscribe and support development of %1"), PROGRAM_NAME));
944                         CheckButton c (_("Don't warn me about this again"));
945                         
946                         l.set_markup (string_compose (_("<span weight=\"bold\" size=\"large\">%1</span>\n\n<b>%2</b>\n\n<i>%3</i>\n\n%4"),
947                                                       string_compose (_("This is a free/demo version of %1"), PROGRAM_NAME),
948                                                       _("It will not restore OR save any plugin settings"),
949                                                       _("If you load an existing session with plugin settings\n"
950                                                         "they will not be used and will be lost."),
951                                                       _("To get full access to updates without this limitation\n"
952                                                         "consider becoming a subscriber for a low cost every month.")));
953                         l.set_justify (JUSTIFY_CENTER);
954                         
955                         b.signal_clicked().connect (mem_fun(*this, &ARDOUR_UI::launch_subscribe));
956                         
957                         d.get_vbox()->pack_start (l, true, true);
958                         d.get_vbox()->pack_start (b, false, false, 12);
959                         d.get_vbox()->pack_start (c, false, false, 12);
960                         
961                         d.add_button (_("Quit now"), RESPONSE_CANCEL);
962                         d.add_button (string_compose (_("Continue using %1"), PROGRAM_NAME), RESPONSE_OK);
963                         
964                         d.show_all ();
965
966                         c.signal_toggled().connect (sigc::hide_return (sigc::bind (sigc::ptr_fun (toggle_file_existence), path)));
967                         
968                         if (d.run () != RESPONSE_OK) {
969                                 _exit (0);
970                         }
971                 }
972 #endif
973                         
974                 /* go get a session */
975
976                 const bool new_session_required = (ARDOUR_COMMAND_LINE::new_session || brand_new_user);
977
978                 if (get_session_parameters (false, new_session_required, ARDOUR_COMMAND_LINE::load_template)) {
979                         std::cerr << "Cannot get session parameters."<< std::endl;
980                         return -1;
981                 }
982         }
983
984         use_config ();
985
986         goto_editor_window ();
987
988         WM::Manager::instance().show_visible ();
989
990         /* We have to do this here since goto_editor_window() ends up calling show_all() on the
991          * editor window, and we may want stuff to be hidden.
992          */
993         _status_bar_visibility.update ();
994
995         BootMessage (string_compose (_("%1 is ready for use"), PROGRAM_NAME));
996         return 0;
997 }
998
999 void
1000 ARDOUR_UI::check_memory_locking ()
1001 {
1002 #if defined(__APPLE__) || defined(PLATFORM_WINDOWS)
1003         /* OS X doesn't support mlockall(2), and so testing for memory locking capability there is pointless */
1004         return;
1005 #else // !__APPLE__
1006
1007         XMLNode* memory_warning_node = Config->instant_xml (X_("no-memory-warning"));
1008
1009         if (AudioEngine::instance()->is_realtime() && memory_warning_node == 0) {
1010
1011                 struct rlimit limits;
1012                 int64_t ram;
1013                 long pages, page_size;
1014 #ifdef __FreeBSD__
1015                 size_t pages_len=sizeof(pages);
1016                 if ((page_size = getpagesize()) < 0 ||
1017                                 sysctlbyname("hw.availpages", &pages, &pages_len, NULL, 0))
1018 #else
1019                 if ((page_size = sysconf (_SC_PAGESIZE)) < 0 ||(pages = sysconf (_SC_PHYS_PAGES)) < 0)
1020 #endif
1021                 {
1022                         ram = 0;
1023                 } else {
1024                         ram = (int64_t) pages * (int64_t) page_size;
1025                 }
1026
1027                 if (getrlimit (RLIMIT_MEMLOCK, &limits)) {
1028                         return;
1029                 }
1030
1031                 if (limits.rlim_cur != RLIM_INFINITY) {
1032
1033                         if (ram == 0 || ((double) limits.rlim_cur / ram) < 0.75) {
1034
1035                                 MessageDialog msg (
1036                                         string_compose (
1037                                                 _("WARNING: Your system has a limit for maximum amount of locked memory. "
1038                                                   "This might cause %1 to run out of memory before your system "
1039                                                   "runs out of memory. \n\n"
1040                                                   "You can view the memory limit with 'ulimit -l', "
1041                                                   "and it is normally controlled by %2"),
1042                                                 PROGRAM_NAME, 
1043 #ifdef __FreeBSD__
1044                                                 X_("/etc/login.conf")
1045 #else
1046                                                 X_(" /etc/security/limits.conf")
1047 #endif
1048                                         ).c_str());
1049
1050                                 msg.set_default_response (RESPONSE_OK);
1051
1052                                 VBox* vbox = msg.get_vbox();
1053                                 HBox hbox;
1054                                 CheckButton cb (_("Do not show this window again"));
1055                                 hbox.pack_start (cb, true, false);
1056                                 vbox->pack_start (hbox);
1057                                 cb.show();
1058                                 vbox->show();
1059                                 hbox.show ();
1060
1061                                 pop_back_splash (msg);
1062
1063                                 editor->ensure_float (msg);
1064                                 msg.run ();
1065
1066                                 if (cb.get_active()) {
1067                                         XMLNode node (X_("no-memory-warning"));
1068                                         Config->add_instant_xml (node);
1069                                 }
1070                         }
1071                 }
1072         }
1073 #endif // !__APPLE__
1074 }
1075
1076
1077 void
1078 ARDOUR_UI::queue_finish ()
1079 {
1080         Glib::signal_idle().connect (mem_fun (*this, &ARDOUR_UI::idle_finish));
1081 }
1082
1083 bool
1084 ARDOUR_UI::idle_finish ()
1085 {
1086         finish ();
1087         return false; /* do not call again */
1088 }
1089
1090 void
1091 ARDOUR_UI::finish()
1092 {
1093         if (_session) {
1094                 ARDOUR_UI::instance()->video_timeline->sync_session_state();
1095
1096                 if (_session->dirty()) {
1097                         vector<string> actions;
1098                         actions.push_back (_("Don't quit"));
1099                         actions.push_back (_("Just quit"));
1100                         actions.push_back (_("Save and quit"));
1101                         switch (ask_about_saving_session(actions)) {
1102                         case -1:
1103                                 return;
1104                                 break;
1105                         case 1:
1106                                 /* use the default name */
1107                                 if (save_state_canfail ("")) {
1108                                         /* failed - don't quit */
1109                                         MessageDialog msg (*editor,
1110                                                            string_compose (_("\
1111 %1 was unable to save your session.\n\n\
1112 If you still wish to quit, please use the\n\n\
1113 \"Just quit\" option."), PROGRAM_NAME));
1114                                         pop_back_splash(msg);
1115                                         msg.run ();
1116                                         return;
1117                                 }
1118                                 break;
1119                         case 0:
1120                                 break;
1121                         }
1122                 }
1123
1124                 second_connection.disconnect ();
1125                 point_one_second_connection.disconnect ();
1126                 point_zero_something_second_connection.disconnect();
1127                 fps_connection.disconnect();
1128         }
1129
1130         delete ARDOUR_UI::instance()->video_timeline;
1131         ARDOUR_UI::instance()->video_timeline = NULL;
1132         stop_video_server();
1133
1134         /* Save state before deleting the session, as that causes some
1135            windows to be destroyed before their visible state can be
1136            saved.
1137         */
1138         save_ardour_state ();
1139
1140         close_all_dialogs ();
1141
1142         if (_session) {
1143                 _session->set_clean ();
1144                 _session->remove_pending_capture_state ();
1145                 delete _session;
1146                 _session = 0;
1147         }
1148
1149         halt_connection.disconnect ();
1150         AudioEngine::instance()->stop ();
1151 #ifdef WINDOWS_VST_SUPPORT
1152         fst_stop_threading();
1153 #endif
1154         quit ();
1155 }
1156
1157 int
1158 ARDOUR_UI::ask_about_saving_session (const vector<string>& actions)
1159 {
1160         ArdourDialog window (_("Unsaved Session"));
1161         Gtk::HBox dhbox;  // the hbox for the image and text
1162         Gtk::Label  prompt_label;
1163         Gtk::Image* dimage = manage (new Gtk::Image(Stock::DIALOG_WARNING,  Gtk::ICON_SIZE_DIALOG));
1164
1165         string msg;
1166
1167         assert (actions.size() >= 3);
1168
1169         window.add_button (actions[0], RESPONSE_REJECT);
1170         window.add_button (actions[1], RESPONSE_APPLY);
1171         window.add_button (actions[2], RESPONSE_ACCEPT);
1172
1173         window.set_default_response (RESPONSE_ACCEPT);
1174
1175         Gtk::Button noquit_button (msg);
1176         noquit_button.set_name ("EditorGTKButton");
1177
1178         string prompt;
1179
1180         if (_session->snap_name() == _session->name()) {
1181                 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?"),
1182                                         _session->snap_name());
1183         } else {
1184                 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?"),
1185                                         _session->snap_name());
1186         }
1187
1188         prompt_label.set_text (prompt);
1189         prompt_label.set_name (X_("PrompterLabel"));
1190         prompt_label.set_alignment(ALIGN_LEFT, ALIGN_TOP);
1191
1192         dimage->set_alignment(ALIGN_CENTER, ALIGN_TOP);
1193         dhbox.set_homogeneous (false);
1194         dhbox.pack_start (*dimage, false, false, 5);
1195         dhbox.pack_start (prompt_label, true, false, 5);
1196         window.get_vbox()->pack_start (dhbox);
1197
1198         window.set_name (_("Prompter"));
1199         window.set_modal (true);
1200         window.set_resizable (false);
1201
1202         dhbox.show();
1203         prompt_label.show();
1204         dimage->show();
1205         window.show();
1206         window.present ();
1207
1208         ResponseType r = (ResponseType) window.run();
1209
1210         window.hide ();
1211
1212         switch (r) {
1213         case RESPONSE_ACCEPT: // save and get out of here
1214                 return 1;
1215         case RESPONSE_APPLY:  // get out of here
1216                 return 0;
1217         default:
1218                 break;
1219         }
1220
1221         return -1;
1222 }
1223
1224
1225 void
1226 ARDOUR_UI::every_second ()
1227 {
1228         update_cpu_load ();
1229         update_xrun_count ();
1230         update_buffer_load ();
1231         update_disk_space ();
1232         update_timecode_format ();
1233
1234         if (nsm && nsm->is_active ()) {
1235                 nsm->check ();
1236
1237                 if (!_was_dirty && _session->dirty ()) {
1238                         nsm->is_dirty ();
1239                         _was_dirty = true;
1240                 }
1241                 else if (_was_dirty && !_session->dirty ()){
1242                         nsm->is_clean ();
1243                         _was_dirty = false;
1244                 }
1245         }
1246 }
1247
1248 void
1249 ARDOUR_UI::every_point_one_seconds ()
1250 {
1251         // TODO get rid of this..
1252         // ShuttleControl is updated directly via TransportStateChange signal
1253 }
1254
1255 void
1256 ARDOUR_UI::every_point_zero_something_seconds ()
1257 {
1258         // august 2007: actual update frequency: 25Hz (40ms), not 100Hz
1259
1260         if (editor_meter && ARDOUR_UI::config()->get_show_editor_meter()) {
1261                 float mpeak = editor_meter->update_meters();
1262                 if (mpeak > editor_meter_max_peak) {
1263                         if (mpeak >= ARDOUR_UI::config()->get_meter_peak()) {
1264                                 editor_meter_peak_display.set_active_state ( Gtkmm2ext::ExplicitActive );
1265                         }
1266                 }
1267         }
1268 }
1269
1270 void
1271 ARDOUR_UI::set_fps_timeout_connection ()
1272 {
1273         unsigned int interval = 40;
1274         if (!_session) return;
1275         if (_session->timecode_frames_per_second() != 0) {
1276                 /* ideally we'll use a select() to sleep and not accumulate
1277                  * idle time to provide a regular periodic signal.
1278                  * See linux_vst_gui_support.cc 'elapsed_time_ms'.
1279                  * However, that'll require a dedicated thread and cross-thread
1280                  * signals to the GUI Thread..
1281                  */
1282                 interval = floor(500. /* update twice per FPS, since Glib::signal_timeout is very irregular */
1283                                 * _session->frame_rate() / _session->nominal_frame_rate()
1284                                 / _session->timecode_frames_per_second()
1285                                 );
1286 #ifdef PLATFORM_WINDOWS
1287                 // the smallest windows scheduler time-slice is ~15ms.
1288                 // periodic GUI timeouts shorter than that will cause
1289                 // WaitForSingleObject to spinlock (100% of one CPU Core)
1290                 // and gtk never enters idle mode.
1291                 // also changing timeBeginPeriod(1) does not affect that in
1292                 // any beneficial way, so we just limit the max rate for now.
1293                 interval = std::max(30u, interval); // at most ~33Hz.
1294 #else
1295                 interval = std::max(8u, interval); // at most 120Hz.
1296 #endif
1297         }
1298         fps_connection.disconnect();
1299         Timers::set_fps_interval (interval);
1300 }
1301
1302 void
1303 ARDOUR_UI::update_sample_rate (framecnt_t)
1304 {
1305         char buf[64];
1306
1307         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::update_sample_rate, ignored)
1308
1309         if (!AudioEngine::instance()->connected()) {
1310
1311                 snprintf (buf, sizeof (buf), "%s", _("Audio: <span foreground=\"red\">none</span>"));
1312
1313         } else {
1314
1315                 framecnt_t rate = AudioEngine::instance()->sample_rate();
1316
1317                 if (rate == 0) {
1318                         /* no sample rate available */
1319                         snprintf (buf, sizeof (buf), "%s", _("Audio: <span foreground=\"red\">none</span>"));
1320                 } else {
1321
1322                         if (fmod (rate, 1000.0) != 0.0) {
1323                                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"green\">%.1f kHz / %4.1f ms</span>"),
1324                                           (float) rate / 1000.0f,
1325                                           (AudioEngine::instance()->usecs_per_cycle() / 1000.0f));
1326                         } else {
1327                                 snprintf (buf, sizeof (buf), _("Audio: <span foreground=\"green\">%" PRId64 " kHz / %4.1f ms</span>"),
1328                                           rate/1000,
1329                                           (AudioEngine::instance()->usecs_per_cycle() / 1000.0f));
1330                         }
1331                 }
1332         }
1333         sample_rate_label.set_markup (buf);
1334 }
1335
1336 void
1337 ARDOUR_UI::update_format ()
1338 {
1339         if (!_session) {
1340                 format_label.set_text ("");
1341                 return;
1342         }
1343
1344         stringstream s;
1345         s << _("File:") << X_(" <span foreground=\"green\">");
1346
1347         switch (_session->config.get_native_file_header_format ()) {
1348         case BWF:
1349                 s << _("BWF");
1350                 break;
1351         case WAVE:
1352                 s << _("WAV");
1353                 break;
1354         case WAVE64:
1355                 s << _("WAV64");
1356                 break;
1357         case CAF:
1358                 s << _("CAF");
1359                 break;
1360         case AIFF:
1361                 s << _("AIFF");
1362                 break;
1363         case iXML:
1364                 s << _("iXML");
1365                 break;
1366         case RF64:
1367                 s << _("RF64");
1368                 break;
1369         }
1370
1371         s << " ";
1372         
1373         switch (_session->config.get_native_file_data_format ()) {
1374         case FormatFloat:
1375                 s << _("32-float");
1376                 break;
1377         case FormatInt24:
1378                 s << _("24-int");
1379                 break;
1380         case FormatInt16:
1381                 s << _("16-int");
1382                 break;
1383         }
1384
1385         s << X_("</span>");
1386
1387         format_label.set_markup (s.str ());
1388 }
1389
1390 void
1391 ARDOUR_UI::update_xrun_count ()
1392 {
1393         char buf[64];
1394
1395         /* If this text is changed, the set_size_request_to_display_given_text call in ARDOUR_UI::resize_text_widgets
1396            should also be changed.
1397         */
1398
1399         if (_session) {
1400                 const unsigned int x = _session->get_xrun_count ();
1401                 if (x > 9999) {
1402                         snprintf (buf, sizeof (buf), _("X: <span foreground=\"%s\">&gt;10K</span>"), X_("red"));
1403                 } else {
1404                         snprintf (buf, sizeof (buf), _("X: <span foreground=\"%s\">%u</span>"), x > 0 ? X_("red") : X_("green"), x);
1405                 }
1406         } else {
1407                 snprintf (buf, sizeof (buf), _("X: <span foreground=\"%s\">?</span>"), X_("yellow"));
1408         }
1409         xrun_label.set_markup (buf);
1410         set_tip (xrun_label, _("Audio dropouts. Shift+click to reset"));
1411 }
1412
1413 void
1414 ARDOUR_UI::update_cpu_load ()
1415 {
1416         char buf[64];
1417
1418         /* If this text is changed, the set_size_request_to_display_given_text call in ARDOUR_UI::resize_text_widgets
1419            should also be changed.
1420         */
1421
1422         double const c = AudioEngine::instance()->get_dsp_load ();
1423         snprintf (buf, sizeof (buf), _("DSP: <span foreground=\"%s\">%5.1f%%</span>"), c >= 90 ? X_("red") : X_("green"), c);
1424         cpu_load_label.set_markup (buf);
1425 }
1426
1427 void
1428 ARDOUR_UI::update_buffer_load ()
1429 {
1430         char buf[256];
1431
1432         uint32_t const playback = _session ? _session->playback_load () : 100;
1433         uint32_t const capture = _session ? _session->capture_load () : 100;
1434
1435         /* If this text is changed, the set_size_request_to_display_given_text call in ARDOUR_UI::resize_text_widgets
1436            should also be changed.
1437         */
1438         
1439         if (_session) {
1440                 snprintf (
1441                         buf, sizeof (buf),
1442                         _("Buffers: <span foreground=\"green\">p:</span><span foreground=\"%s\">%" PRIu32 "%%</span> "
1443                                    "<span foreground=\"green\">c:</span><span foreground=\"%s\">%" PRIu32 "%%</span>"),
1444                         playback <= 5 ? X_("red") : X_("green"),
1445                         playback,
1446                         capture <= 5 ? X_("red") : X_("green"),
1447                         capture
1448                         );
1449
1450                 buffer_load_label.set_markup (buf);
1451         } else {
1452                 buffer_load_label.set_text ("");
1453         }
1454 }
1455
1456 void
1457 ARDOUR_UI::count_recenabled_streams (Route& route)
1458 {
1459         Track* track = dynamic_cast<Track*>(&route);
1460         if (track && track->record_enabled()) {
1461                 rec_enabled_streams += track->n_inputs().n_total();
1462         }
1463 }
1464
1465 void
1466 ARDOUR_UI::update_disk_space()
1467 {
1468         if (_session == 0) {
1469                 return;
1470         }
1471
1472         boost::optional<framecnt_t> opt_frames = _session->available_capture_duration();
1473         char buf[64];
1474         framecnt_t fr = _session->frame_rate();
1475
1476         if (fr == 0) {
1477                 /* skip update - no SR available */
1478                 return;
1479         }
1480
1481         if (!opt_frames) {
1482                 /* Available space is unknown */
1483                 snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">Unknown</span>"));
1484         } else if (opt_frames.get_value_or (0) == max_framecnt) {
1485                 snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">24hrs+</span>"));
1486         } else {
1487                 rec_enabled_streams = 0;
1488                 _session->foreach_route (this, &ARDOUR_UI::count_recenabled_streams, false);
1489
1490                 framecnt_t frames = opt_frames.get_value_or (0);
1491
1492                 if (rec_enabled_streams) {
1493                         frames /= rec_enabled_streams;
1494                 }
1495
1496                 int hrs;
1497                 int mins;
1498                 int secs;
1499
1500                 hrs  = frames / (fr * 3600);
1501
1502                 if (hrs > 24) {
1503                         snprintf (buf, sizeof (buf), "%s", _("Disk: <span foreground=\"green\">&gt;24 hrs</span>"));
1504                 } else {
1505                         frames -= hrs * fr * 3600;
1506                         mins = frames / (fr * 60);
1507                         frames -= mins * fr * 60;
1508                         secs = frames / fr;
1509                         
1510                         bool const low = (hrs == 0 && mins <= 30);
1511                         
1512                         snprintf (
1513                                 buf, sizeof(buf),
1514                                 _("Disk: <span foreground=\"%s\">%02dh:%02dm:%02ds</span>"),
1515                                 low ? X_("red") : X_("green"),
1516                                 hrs, mins, secs
1517                                 );
1518                 }
1519         }
1520
1521         disk_space_label.set_markup (buf);
1522 }
1523
1524 void
1525 ARDOUR_UI::update_timecode_format ()
1526 {
1527         char buf[64];
1528
1529         if (_session) {
1530                 bool matching;
1531                 TimecodeSlave* tcslave;
1532                 SyncSource sync_src = Config->get_sync_source();
1533
1534                 if ((sync_src == LTC || sync_src == MTC) && (tcslave = dynamic_cast<TimecodeSlave*>(_session->slave())) != 0) {
1535                         matching = (tcslave->apparent_timecode_format() == _session->config.get_timecode_format());
1536                 } else {
1537                         matching = true;
1538                 }
1539                         
1540                 snprintf (buf, sizeof (buf), S_("Timecode|TC: <span foreground=\"%s\">%s</span>"),
1541                           matching ? X_("green") : X_("red"),
1542                           Timecode::timecode_format_name (_session->config.get_timecode_format()).c_str());
1543         } else {
1544                 snprintf (buf, sizeof (buf), "TC: n/a");
1545         }
1546
1547         timecode_format_label.set_markup (buf);
1548 }       
1549
1550 gint
1551 ARDOUR_UI::update_wall_clock ()
1552 {
1553         time_t now;
1554         struct tm *tm_now;
1555         static int last_min = -1;
1556
1557         time (&now);
1558         tm_now = localtime (&now);
1559         if (last_min != tm_now->tm_min) {
1560                 char buf[16];
1561                 sprintf (buf, "%02d:%02d", tm_now->tm_hour, tm_now->tm_min);
1562                 wall_clock_label.set_text (buf);
1563                 last_min = tm_now->tm_min;
1564         }
1565
1566         return TRUE;
1567 }
1568
1569 void
1570 ARDOUR_UI::redisplay_recent_sessions ()
1571 {
1572         std::vector<std::string> session_directories;
1573         RecentSessionsSorter cmp;
1574
1575         recent_session_display.set_model (Glib::RefPtr<TreeModel>(0));
1576         recent_session_model->clear ();
1577
1578         ARDOUR::RecentSessions rs;
1579         ARDOUR::read_recent_sessions (rs);
1580
1581         if (rs.empty()) {
1582                 recent_session_display.set_model (recent_session_model);
1583                 return;
1584         }
1585
1586         // sort them alphabetically
1587         sort (rs.begin(), rs.end(), cmp);
1588
1589         for (ARDOUR::RecentSessions::iterator i = rs.begin(); i != rs.end(); ++i) {
1590                 session_directories.push_back ((*i).second);
1591         }
1592
1593         for (vector<std::string>::const_iterator i = session_directories.begin();
1594                         i != session_directories.end(); ++i)
1595         {
1596                 std::vector<std::string> state_file_paths;
1597
1598                 // now get available states for this session
1599
1600                 get_state_files_in_directory (*i, state_file_paths);
1601
1602                 vector<string> states;
1603                 vector<const gchar*> item;
1604                 string fullpath = *i;
1605
1606                 /* remove any trailing / */
1607
1608                 if (fullpath[fullpath.length() - 1] == '/') {
1609                         fullpath = fullpath.substr (0, fullpath.length() - 1);
1610                 }
1611
1612                 /* check whether session still exists */
1613                 if (!Glib::file_test(fullpath.c_str(), Glib::FILE_TEST_EXISTS)) {
1614                         /* session doesn't exist */
1615                         continue;
1616                 }
1617
1618                 /* now get available states for this session */
1619                 states = Session::possible_states (fullpath);
1620
1621                 if (states.empty()) {
1622                         /* no state file? */
1623                         continue;
1624                 }
1625
1626                 std::vector<string> state_file_names(get_file_names_no_extension (state_file_paths));
1627
1628                 Gtk::TreeModel::Row row = *(recent_session_model->append());
1629
1630                 row[recent_session_columns.fullpath] = fullpath;
1631                 row[recent_session_columns.tip] = Glib::Markup::escape_text (fullpath);
1632
1633                 if (state_file_names.size() > 1) {
1634                         // multiple session files in the session directory - show the directory name.
1635                         row[recent_session_columns.visible_name] = Glib::path_get_basename (fullpath);
1636
1637                         // add the children
1638                         for (std::vector<std::string>::iterator i2 = state_file_names.begin();
1639                                         i2 != state_file_names.end(); ++i2)
1640                         {
1641
1642                                 Gtk::TreeModel::Row child_row = *(recent_session_model->append (row.children()));
1643
1644                                 child_row[recent_session_columns.visible_name] = *i2;
1645                                 child_row[recent_session_columns.fullpath] = fullpath;
1646                                 child_row[recent_session_columns.tip] = Glib::Markup::escape_text (fullpath);
1647                         }
1648                 } else {
1649                         // only a single session file in the directory - show its actual name.
1650                         row[recent_session_columns.visible_name] = state_file_names.front ();
1651                 }
1652         }
1653
1654         recent_session_display.set_tooltip_column(1); // recent_session_columns.tip
1655         recent_session_display.set_model (recent_session_model);
1656 }
1657
1658 void
1659 ARDOUR_UI::build_session_selector ()
1660 {
1661         session_selector_window = new ArdourDialog (_("Recent Sessions"));
1662
1663         Gtk::ScrolledWindow *scroller = manage (new Gtk::ScrolledWindow);
1664
1665         session_selector_window->add_button (Stock::CANCEL, RESPONSE_CANCEL);
1666         session_selector_window->add_button (Stock::OPEN, RESPONSE_ACCEPT);
1667         session_selector_window->set_default_response (RESPONSE_ACCEPT);
1668         recent_session_model = TreeStore::create (recent_session_columns);
1669         recent_session_display.set_model (recent_session_model);
1670         recent_session_display.append_column (_("Recent Sessions"), recent_session_columns.visible_name);
1671         recent_session_display.set_headers_visible (false);
1672         recent_session_display.get_selection()->set_mode (SELECTION_BROWSE);
1673         recent_session_display.signal_row_activated().connect (sigc::mem_fun (*this, &ARDOUR_UI::recent_session_row_activated));
1674
1675         scroller->add (recent_session_display);
1676         scroller->set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
1677
1678         session_selector_window->set_name ("SessionSelectorWindow");
1679         session_selector_window->set_size_request (200, 400);
1680         session_selector_window->get_vbox()->pack_start (*scroller);
1681
1682         recent_session_display.show();
1683         scroller->show();
1684 }
1685
1686 void
1687 ARDOUR_UI::recent_session_row_activated (const TreePath& /*path*/, TreeViewColumn* /*col*/)
1688 {
1689         session_selector_window->response (RESPONSE_ACCEPT);
1690 }
1691
1692 void
1693 ARDOUR_UI::open_recent_session ()
1694 {
1695         bool can_return = (_session != 0);
1696
1697         if (session_selector_window == 0) {
1698                 build_session_selector ();
1699         }
1700
1701         redisplay_recent_sessions ();
1702
1703         while (true) {
1704
1705                 ResponseType r = (ResponseType) session_selector_window->run ();
1706
1707                 switch (r) {
1708                 case RESPONSE_ACCEPT:
1709                         break;
1710                 default:
1711                         if (can_return) {
1712                                 session_selector_window->hide();
1713                                 return;
1714                         } else {
1715                                 exit (1);
1716                         }
1717                 }
1718
1719                 if (recent_session_display.get_selection()->count_selected_rows() == 0) {
1720                         continue;
1721                 }
1722
1723                 session_selector_window->hide();
1724
1725                 Gtk::TreeModel::iterator i = recent_session_display.get_selection()->get_selected();
1726
1727                 if (i == recent_session_model->children().end()) {
1728                         return;
1729                 }
1730
1731                 std::string path = (*i)[recent_session_columns.fullpath];
1732                 std::string state = (*i)[recent_session_columns.visible_name];
1733
1734                 _session_is_new = false;
1735
1736                 if (load_session (path, state) == 0) {
1737                         break;
1738                 }
1739
1740                 can_return = false;
1741         }
1742 }
1743
1744 bool
1745 ARDOUR_UI::check_audioengine ()
1746 {
1747         if (!AudioEngine::instance()->connected()) {
1748                 MessageDialog msg (string_compose (
1749                                            _("%1 is not connected to any audio backend.\n"
1750                                              "You cannot open or close sessions in this condition"),
1751                                            PROGRAM_NAME));
1752                 pop_back_splash (msg);
1753                 msg.run ();
1754                 return false;
1755         }
1756         return true;
1757 }
1758
1759 void
1760 ARDOUR_UI::open_session ()
1761 {
1762         if (!check_audioengine()) {
1763                 return;
1764
1765         }
1766
1767         /* popup selector window */
1768
1769         if (open_session_selector == 0) {
1770
1771                 /* ardour sessions are folders */
1772
1773                 open_session_selector = new Gtk::FileChooserDialog (_("Open Session"), FILE_CHOOSER_ACTION_OPEN);
1774                 open_session_selector->add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1775                 open_session_selector->add_button (Gtk::Stock::OPEN, Gtk::RESPONSE_ACCEPT);
1776                 open_session_selector->set_default_response(Gtk::RESPONSE_ACCEPT);
1777                 
1778                 if (_session) {
1779                         string session_parent_dir = Glib::path_get_dirname(_session->path());
1780                         string::size_type last_dir_sep = session_parent_dir.rfind(G_DIR_SEPARATOR);
1781                         session_parent_dir = session_parent_dir.substr(0, last_dir_sep);
1782                         open_session_selector->set_current_folder(session_parent_dir);
1783                 } else {
1784                         open_session_selector->set_current_folder(Config->get_default_session_parent_dir());
1785                 }
1786
1787                 string default_session_folder = Config->get_default_session_parent_dir();
1788                 try {
1789                         /* add_shortcut_folder throws an exception if the folder being added already has a shortcut */
1790                         open_session_selector->add_shortcut_folder (default_session_folder);
1791                 }
1792                 catch (Glib::Error & e) {
1793                         std::cerr << "open_session_selector->add_shortcut_folder (" << default_session_folder << ") threw Glib::Error " << e.what() << std::endl;
1794                 }
1795
1796                 FileFilter session_filter;
1797                 session_filter.add_pattern (string_compose(X_("*%1"), ARDOUR::statefile_suffix));
1798                 session_filter.set_name (string_compose (_("%1 sessions"), PROGRAM_NAME));
1799                 open_session_selector->add_filter (session_filter);
1800                 open_session_selector->set_filter (session_filter);
1801         }
1802
1803         int response = open_session_selector->run();
1804         open_session_selector->hide ();
1805
1806         switch (response) {
1807         case RESPONSE_ACCEPT:
1808                 break;
1809         default:
1810                 open_session_selector->hide();
1811                 return;
1812         }
1813
1814         open_session_selector->hide();
1815         string session_path = open_session_selector->get_filename();
1816         string path, name;
1817         bool isnew;
1818
1819         if (session_path.length() > 0) {
1820                 if (ARDOUR::find_session (session_path, path, name, isnew) == 0) {
1821                         _session_is_new = isnew;
1822                         load_session (path, name);
1823                 }
1824         }
1825 }
1826
1827
1828 void
1829 ARDOUR_UI::session_add_mixed_track (const ChanCount& input, const ChanCount& output, RouteGroup* route_group, 
1830                                     uint32_t how_many, const string& name_template, PluginInfoPtr instrument)
1831 {
1832         list<boost::shared_ptr<MidiTrack> > tracks;
1833
1834         if (_session == 0) {
1835                 warning << _("You cannot add a track without a session already loaded.") << endmsg;
1836                 return;
1837         }
1838
1839         try {
1840                 tracks = _session->new_midi_track (input, output, instrument, ARDOUR::Normal, route_group, how_many, name_template);
1841                 
1842                 if (tracks.size() != how_many) {
1843                         error << string_compose(P_("could not create %1 new mixed track", "could not create %1 new mixed tracks", how_many), how_many) << endmsg;
1844                 }
1845         }
1846
1847         catch (...) {
1848                 MessageDialog msg (*editor,
1849                                    string_compose (_("There are insufficient ports available\n\
1850 to create a new track or bus.\n\
1851 You should save %1, exit and\n\
1852 restart with more ports."), PROGRAM_NAME));
1853                 msg.run ();
1854         }
1855 }
1856         
1857
1858 void
1859 ARDOUR_UI::session_add_midi_route (bool disk, RouteGroup* route_group, uint32_t how_many, const string& name_template, PluginInfoPtr instrument)
1860 {
1861         ChanCount one_midi_channel;
1862         one_midi_channel.set (DataType::MIDI, 1);
1863
1864         if (disk) {
1865                 session_add_mixed_track (one_midi_channel, one_midi_channel, route_group, how_many, name_template, instrument);
1866         }
1867 }
1868
1869 void
1870 ARDOUR_UI::session_add_audio_route (
1871         bool track,
1872         int32_t input_channels,
1873         int32_t output_channels,
1874         ARDOUR::TrackMode mode,
1875         RouteGroup* route_group,
1876         uint32_t how_many,
1877         string const & name_template
1878         )
1879 {
1880         list<boost::shared_ptr<AudioTrack> > tracks;
1881         RouteList routes;
1882
1883         if (_session == 0) {
1884                 warning << _("You cannot add a track or bus without a session already loaded.") << endmsg;
1885                 return;
1886         }
1887
1888         try {
1889                 if (track) {
1890                         tracks = _session->new_audio_track (input_channels, output_channels, mode, route_group, how_many, name_template);
1891
1892                         if (tracks.size() != how_many) {
1893                                 error << string_compose (P_("could not create %1 new audio track", "could not create %1 new audio tracks", how_many), how_many) 
1894                                       << endmsg;
1895                         }
1896
1897                 } else {
1898
1899                         routes = _session->new_audio_route (input_channels, output_channels, route_group, how_many, name_template);
1900
1901                         if (routes.size() != how_many) {
1902                                 error << string_compose (P_("could not create %1 new audio bus", "could not create %1 new audio busses", how_many), how_many)
1903                                       << endmsg;
1904                         }
1905                 }
1906         }
1907
1908         catch (...) {
1909                 MessageDialog msg (*editor,
1910                                    string_compose (_("There are insufficient ports available\n\
1911 to create a new track or bus.\n\
1912 You should save %1, exit and\n\
1913 restart with more ports."), PROGRAM_NAME));
1914                 pop_back_splash (msg);
1915                 msg.run ();
1916         }
1917 }
1918
1919 void
1920 ARDOUR_UI::transport_goto_start ()
1921 {
1922         if (_session) {
1923                 _session->goto_start();
1924
1925                 /* force displayed area in editor to start no matter
1926                    what "follow playhead" setting is.
1927                 */
1928
1929                 if (editor) {
1930                         editor->center_screen (_session->current_start_frame ());
1931                 }
1932         }
1933 }
1934
1935 void
1936 ARDOUR_UI::transport_goto_zero ()
1937 {
1938         if (_session) {
1939                 _session->request_locate (0);
1940
1941                 /* force displayed area in editor to start no matter
1942                    what "follow playhead" setting is.
1943                 */
1944
1945                 if (editor) {
1946                         editor->reset_x_origin (0);
1947                 }
1948         }
1949 }
1950
1951 void
1952 ARDOUR_UI::transport_goto_wallclock ()
1953 {
1954         if (_session && editor) {
1955
1956                 time_t now;
1957                 struct tm tmnow;
1958                 framepos_t frames;
1959
1960                 time (&now);
1961                 localtime_r (&now, &tmnow);
1962                 
1963                 int frame_rate = _session->frame_rate();
1964                 
1965                 if (frame_rate == 0) {
1966                         /* no frame rate available */
1967                         return;
1968                 }
1969
1970                 frames = tmnow.tm_hour * (60 * 60 * frame_rate);
1971                 frames += tmnow.tm_min * (60 * frame_rate);
1972                 frames += tmnow.tm_sec * frame_rate;
1973
1974                 _session->request_locate (frames, _session->transport_rolling ());
1975
1976                 /* force displayed area in editor to start no matter
1977                    what "follow playhead" setting is.
1978                 */
1979
1980                 if (editor) {
1981                         editor->center_screen (frames);
1982                 }
1983         }
1984 }
1985
1986 void
1987 ARDOUR_UI::transport_goto_end ()
1988 {
1989         if (_session) {
1990                 framepos_t const frame = _session->current_end_frame();
1991                 _session->request_locate (frame);
1992
1993                 /* force displayed area in editor to start no matter
1994                    what "follow playhead" setting is.
1995                 */
1996
1997                 if (editor) {
1998                         editor->center_screen (frame);
1999                 }
2000         }
2001 }
2002
2003 void
2004 ARDOUR_UI::transport_stop ()
2005 {
2006         if (!_session) {
2007                 return;
2008         }
2009
2010         if (_session->is_auditioning()) {
2011                 _session->cancel_audition ();
2012                 return;
2013         }
2014
2015         _session->request_stop (false, true);
2016 }
2017
2018 /** Check if any tracks are record enabled. If none are, record enable all of them.
2019  * @return true if track record-enabled status was changed, false otherwise.
2020  */  
2021 bool
2022 ARDOUR_UI::trx_record_enable_all_tracks ()
2023 {
2024         if (!_session) {
2025                 return false;
2026         }
2027
2028         boost::shared_ptr<RouteList> rl = _session->get_tracks ();
2029         bool none_record_enabled = true;
2030
2031         for (RouteList::iterator r = rl->begin(); r != rl->end(); ++r) {
2032                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*r);
2033                 assert (t);
2034
2035                 if (t->record_enabled()) {
2036                         none_record_enabled = false;
2037                         break;
2038                 }
2039         }
2040
2041         if (none_record_enabled) {
2042                 _session->set_record_enabled (rl, true, Session::rt_cleanup);
2043         } 
2044
2045         return none_record_enabled;
2046 }
2047
2048 void
2049 ARDOUR_UI::transport_record (bool roll)
2050 {
2051         if (_session) {
2052                 switch (_session->record_status()) {
2053                 case Session::Disabled:
2054                         if (_session->ntracks() == 0) {
2055                                 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."));
2056                                 msg.run ();
2057                                 return;
2058                         }
2059                         if (Profile->get_trx()) {
2060                                 roll = trx_record_enable_all_tracks ();
2061                         }
2062                         _session->maybe_enable_record ();
2063                         if (roll) {
2064                                 transport_roll ();
2065                         }
2066                         break;
2067                 case Session::Recording:
2068                         if (roll) {
2069                                 _session->request_stop();
2070                         } else {
2071                                 _session->disable_record (false, true);
2072                         }
2073                         break;
2074
2075                 case Session::Enabled:
2076                         _session->disable_record (false, true);
2077                 }
2078         }
2079 }
2080
2081 void
2082 ARDOUR_UI::transport_roll ()
2083 {
2084         if (!_session) {
2085                 return;
2086         }
2087
2088         if (_session->is_auditioning()) {
2089                 return;
2090         }
2091
2092 #if 0
2093         if (_session->config.get_external_sync()) {
2094                 switch (Config->get_sync_source()) {
2095                 case Engine:
2096                         break;
2097                 default:
2098                         /* transport controlled by the master */
2099                         return;
2100                 }
2101         }
2102 #endif
2103
2104         bool rolling = _session->transport_rolling();
2105
2106         if (_session->get_play_loop()) {
2107
2108                 /* If loop playback is not a mode, then we should cancel
2109                    it when this action is requested. If it is a mode
2110                    we just leave it in place.
2111                 */
2112
2113                 if (!Config->get_loop_is_mode()) {
2114                         /* XXX it is not possible to just leave seamless loop and keep
2115                            playing at present (nov 4th 2009)
2116                         */
2117                         if (!Config->get_seamless_loop()) {
2118                                 /* stop loop playback and stop rolling */
2119                                 _session->request_play_loop (false, true);
2120                         } else if (rolling) {
2121                                 /* stop loop playback but keep rolling */
2122                                 _session->request_play_loop (false, false);
2123                         }
2124                 } 
2125
2126         } else if (_session->get_play_range () ) {
2127                 /* stop playing a range if we currently are */
2128                 _session->request_play_range (0, true);
2129         }
2130
2131         if (!rolling) {
2132                 _session->request_transport_speed (1.0f);
2133         }
2134 }
2135
2136 bool
2137 ARDOUR_UI::get_smart_mode() const
2138 {
2139         return ( editor->get_smart_mode() );
2140 }
2141
2142
2143 void
2144 ARDOUR_UI::toggle_roll (bool with_abort, bool roll_out_of_bounded_mode)
2145 {
2146         if (!_session) {
2147                 return;
2148         }
2149
2150         if (_session->is_auditioning()) {
2151                 _session->cancel_audition ();
2152                 return;
2153         }
2154
2155         if (_session->config.get_external_sync()) {
2156                 switch (Config->get_sync_source()) {
2157                 case Engine:
2158                         break;
2159                 default:
2160                         /* transport controlled by the master */
2161                         return;
2162                 }
2163         }
2164
2165         bool rolling = _session->transport_rolling();
2166         bool affect_transport = true;
2167
2168         if (rolling && roll_out_of_bounded_mode) {
2169                 /* drop out of loop/range playback but leave transport rolling */
2170                 if (_session->get_play_loop()) {
2171                         if (Config->get_seamless_loop()) {
2172                                 /* the disk buffers contain copies of the loop - we can't
2173                                    just keep playing, so stop the transport. the user
2174                                    can restart as they wish.
2175                                 */
2176                                 affect_transport = true;
2177                         } else {
2178                                 /* disk buffers are normal, so we can keep playing */
2179                                 affect_transport = false;
2180                         }
2181                         _session->request_play_loop (false, affect_transport);
2182                 } else if (_session->get_play_range ()) {
2183                         affect_transport = false;
2184                         _session->request_play_range (0, true);
2185                 }
2186         }
2187
2188         if (affect_transport) {
2189                 if (rolling) {
2190                         _session->request_stop (with_abort, true);
2191                 } else {
2192                         if (ARDOUR_UI::config()->get_follow_edits() && ( editor->get_selection().time.front().start == _session->transport_frame() ) ) {  //if playhead is exactly at the start of a range, we can assume it was placed there by follow_edits
2193                                 _session->request_play_range (&editor->get_selection().time, true);
2194                                 _session->set_requested_return_frame( editor->get_selection().time.front().start );  //force an auto-return here
2195                         }
2196                         _session->request_transport_speed (1.0f);
2197                 }
2198         }
2199 }
2200
2201 void
2202 ARDOUR_UI::toggle_session_auto_loop ()
2203 {
2204         Location * looploc = _session->locations()->auto_loop_location();
2205
2206         if (!_session || !looploc) {
2207                 return;
2208         }
2209
2210         if (_session->get_play_loop()) {
2211
2212                 /* looping enabled, our job is to disable it */
2213
2214                 _session->request_play_loop (false);
2215
2216         } else {
2217
2218                 /* looping not enabled, our job is to enable it.
2219
2220                    loop-is-NOT-mode: this action always starts the transport rolling.
2221                    loop-IS-mode:     this action simply sets the loop play mechanism, but
2222                                         does not start transport.
2223                 */
2224                 if (Config->get_loop_is_mode()) {
2225                         _session->request_play_loop (true, false);
2226                 } else {
2227                         _session->request_play_loop (true, true);
2228                 }
2229         }
2230         
2231         //show the loop markers
2232         looploc->set_hidden (false, this);
2233 }
2234
2235 void
2236 ARDOUR_UI::transport_play_selection ()
2237 {
2238         if (!_session) {
2239                 return;
2240         }
2241
2242         editor->play_selection ();
2243 }
2244
2245 void
2246 ARDOUR_UI::transport_play_preroll ()
2247 {
2248         if (!_session) {
2249                 return;
2250         }
2251         editor->play_with_preroll ();
2252 }
2253
2254 void
2255 ARDOUR_UI::transport_rewind (int option)
2256 {
2257         float current_transport_speed;
2258
2259         if (_session) {
2260                 current_transport_speed = _session->transport_speed();
2261
2262                 if (current_transport_speed >= 0.0f) {
2263                         switch (option) {
2264                         case 0:
2265                                 _session->request_transport_speed (-1.0f);
2266                                 break;
2267                         case 1:
2268                                 _session->request_transport_speed (-4.0f);
2269                                 break;
2270                         case -1:
2271                                 _session->request_transport_speed (-0.5f);
2272                                 break;
2273                         }
2274                 } else {
2275                         /* speed up */
2276                         _session->request_transport_speed (current_transport_speed * 1.5f);
2277                 }
2278         }
2279 }
2280
2281 void
2282 ARDOUR_UI::transport_forward (int option)
2283 {
2284         if (!_session) {
2285                 return;
2286         }
2287         
2288         float current_transport_speed = _session->transport_speed();
2289         
2290         if (current_transport_speed <= 0.0f) {
2291                 switch (option) {
2292                 case 0:
2293                         _session->request_transport_speed (1.0f);
2294                         break;
2295                 case 1:
2296                         _session->request_transport_speed (4.0f);
2297                         break;
2298                 case -1:
2299                         _session->request_transport_speed (0.5f);
2300                         break;
2301                 }
2302         } else {
2303                 /* speed up */
2304                 _session->request_transport_speed (current_transport_speed * 1.5f);
2305         }
2306 }
2307
2308 void
2309 ARDOUR_UI::toggle_record_enable (uint32_t rid)
2310 {
2311         if (!_session) {
2312                 return;
2313         }
2314
2315         boost::shared_ptr<Route> r;
2316
2317         if ((r = _session->route_by_remote_id (rid)) != 0) {
2318
2319                 Track* t;
2320
2321                 if ((t = dynamic_cast<Track*>(r.get())) != 0) {
2322                         t->set_record_enabled (!t->record_enabled(), this);
2323                 }
2324         }
2325 }
2326
2327 void
2328 ARDOUR_UI::map_transport_state ()
2329 {
2330         if (!_session) {
2331                 auto_loop_button.unset_active_state ();
2332                 play_selection_button.unset_active_state ();
2333                 roll_button.unset_active_state ();
2334                 stop_button.set_active_state (Gtkmm2ext::ExplicitActive);
2335                 return;
2336         }
2337
2338         shuttle_box->map_transport_state ();
2339
2340         float sp = _session->transport_speed();
2341
2342         if (sp != 0.0f) {
2343
2344                 /* we're rolling */
2345
2346                 if (_session->get_play_range()) {
2347
2348                         play_selection_button.set_active_state (Gtkmm2ext::ExplicitActive);
2349                         roll_button.unset_active_state ();
2350                         auto_loop_button.unset_active_state ();
2351
2352                 } else if (_session->get_play_loop ()) {
2353
2354                         auto_loop_button.set_active (true);
2355                         play_selection_button.set_active (false);
2356                         if (Config->get_loop_is_mode()) {
2357                                 roll_button.set_active (true);
2358                         } else {
2359                                 roll_button.set_active (false);
2360                         }
2361
2362                 } else {
2363
2364                         roll_button.set_active (true);
2365                         play_selection_button.set_active (false);
2366                         auto_loop_button.set_active (false);
2367                 }
2368
2369                 if (ARDOUR_UI::config()->get_follow_edits()) {
2370                         /* light up both roll and play-selection if they are joined */
2371                         roll_button.set_active (true);
2372                         play_selection_button.set_active (true);
2373                 }
2374
2375                 stop_button.set_active (false);
2376
2377         } else {
2378
2379                 stop_button.set_active (true);
2380                 roll_button.set_active (false);
2381                 play_selection_button.set_active (false);
2382                 if (Config->get_loop_is_mode ()) {
2383                         auto_loop_button.set_active (_session->get_play_loop());
2384                 } else {
2385                         auto_loop_button.set_active (false);
2386                 }
2387                 update_disk_space ();
2388         }
2389 }
2390
2391 void
2392 ARDOUR_UI::blink_handler (bool blink_on)
2393 {
2394         transport_rec_enable_blink (blink_on);
2395         solo_blink (blink_on);
2396         sync_blink (blink_on);
2397         audition_blink (blink_on);
2398         feedback_blink (blink_on);
2399         error_blink (blink_on);
2400 }
2401
2402 void
2403 ARDOUR_UI::update_clocks ()
2404 {
2405         if (!_session) return;
2406
2407         if (editor && !editor->dragging_playhead()) {
2408                 Clock (_session->audible_frame(), false, editor->get_preferred_edit_position (EDIT_IGNORE_PHEAD)); /* EMIT_SIGNAL */
2409         }
2410 }
2411
2412 void
2413 ARDOUR_UI::start_clocking ()
2414 {
2415         if (ui_config->get_super_rapid_clock_update()) {
2416                 clock_signal_connection = Timers::fps_connect (sigc::mem_fun(*this, &ARDOUR_UI::update_clocks));
2417         } else {
2418                 clock_signal_connection = Timers::rapid_connect (sigc::mem_fun(*this, &ARDOUR_UI::update_clocks));
2419         }
2420 }
2421
2422 void
2423 ARDOUR_UI::stop_clocking ()
2424 {
2425         clock_signal_connection.disconnect ();
2426 }
2427
2428 bool
2429 ARDOUR_UI::save_as_progress_update (float fraction, int64_t cnt, int64_t total, Gtk::Label* label, Gtk::ProgressBar* bar)
2430 {
2431         char buf[256];
2432
2433         snprintf (buf, sizeof (buf), _("Copied %" PRId64 " of %" PRId64), cnt, total);
2434
2435         label->set_text (buf);
2436         bar->set_fraction (fraction);
2437
2438         /* process events, redraws, etc. */
2439         
2440         while (gtk_events_pending()) {
2441                 gtk_main_iteration ();
2442         }
2443
2444         return true; /* continue with save-as */
2445 }
2446
2447 void
2448 ARDOUR_UI::save_session_as ()
2449 {
2450         if (!_session) {
2451                 return;
2452         }
2453
2454         if (!save_as_dialog) {
2455                 save_as_dialog = new SaveAsDialog;
2456         } else {
2457                 save_as_dialog->clear_name ();
2458         }
2459
2460         int response = save_as_dialog->run ();
2461
2462         save_as_dialog->hide ();
2463         
2464         switch (response) {
2465         case Gtk::RESPONSE_OK:
2466                 break;
2467         default:
2468                 return;
2469         }
2470         
2471         
2472         Session::SaveAs sa;
2473
2474         sa.new_parent_folder = save_as_dialog->new_parent_folder ();
2475         sa.new_name = save_as_dialog->new_name ();
2476         sa.switch_to = save_as_dialog->switch_to();
2477         sa.copy_media = save_as_dialog->copy_media();
2478         sa.copy_external = save_as_dialog->copy_external();
2479         sa.include_media = save_as_dialog->include_media ();
2480
2481         /* Only bother with a progress dialog if we're going to copy
2482            media into the save-as target. Without that choice, this
2483            will be very fast because we're only talking about a few kB's to
2484            perhaps a couple of MB's of data.
2485         */
2486         
2487         ArdourDialog progress_dialog (_("Save As"), true);
2488
2489         if (sa.include_media && sa.copy_media) {
2490                 
2491                 Gtk::Label label;
2492                 Gtk::ProgressBar progress_bar;
2493                 
2494                 progress_dialog.get_vbox()->pack_start (label);
2495                 progress_dialog.get_vbox()->pack_start (progress_bar);
2496                 label.show ();
2497                 progress_bar.show ();
2498
2499                 /* this signal will be emitted from within this, the calling thread,
2500                  * after every file is copied. It provides information on percentage
2501                  * complete (in terms of total data to copy), the number of files
2502                  * copied so far, and the total number to copy.
2503                  */
2504                 
2505                 ScopedConnection c;
2506                 
2507                 sa.Progress.connect_same_thread (c, boost::bind (&ARDOUR_UI::save_as_progress_update, this, _1, _2, _3, &label, &progress_bar));
2508                 
2509                 progress_dialog.show_all ();
2510                 progress_dialog.present ();
2511         }
2512         
2513         if (_session->save_as (sa)) {
2514                 /* ERROR MESSAGE */
2515                 MessageDialog msg (string_compose (_("Save As failed: %1"), sa.failure_message));
2516                 msg.run ();
2517         }
2518
2519         if (!sa.include_media) {
2520                 unload_session (false);
2521                 load_session (sa.final_session_folder_name, sa.new_name);
2522         }
2523 }
2524
2525 /** Ask the user for the name of a new snapshot and then take it.
2526  */
2527
2528 void
2529 ARDOUR_UI::snapshot_session (bool switch_to_it)
2530 {
2531         ArdourPrompter prompter (true);
2532         string snapname;
2533
2534         prompter.set_name ("Prompter");
2535         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2536         if (switch_to_it) {
2537                 prompter.set_title (_("Save as..."));
2538                 prompter.set_prompt (_("New session name"));
2539         } else {
2540                 prompter.set_title (_("Take Snapshot"));
2541                 prompter.set_prompt (_("Name of new snapshot"));
2542         }
2543
2544         if (!switch_to_it) {
2545                 char timebuf[128];
2546                 time_t n;
2547                 struct tm local_time;
2548
2549                 time (&n);
2550                 localtime_r (&n, &local_time);
2551                 strftime (timebuf, sizeof(timebuf), "%FT%H.%M.%S", &local_time);
2552                 prompter.set_initial_text (timebuf);
2553         }
2554
2555   again:
2556         switch (prompter.run()) {
2557         case RESPONSE_ACCEPT:
2558         {
2559                 prompter.get_result (snapname);
2560
2561                 bool do_save = (snapname.length() != 0);
2562
2563                 if (do_save) {
2564                         char illegal = Session::session_name_is_legal(snapname);
2565                         if (illegal) {
2566                                 MessageDialog msg (string_compose (_("To ensure compatibility with various systems\n"
2567                                                      "snapshot names may not contain a '%1' character"), illegal));
2568                                 msg.run ();
2569                                 goto again;
2570                         }
2571                 }
2572
2573                 vector<std::string> p;
2574                 get_state_files_in_directory (_session->session_directory().root_path(), p);
2575                 vector<string> n = get_file_names_no_extension (p);
2576                 if (find (n.begin(), n.end(), snapname) != n.end()) {
2577
2578                         ArdourDialog confirm (_("Confirm Snapshot Overwrite"), true);
2579                         Label m (_("A snapshot already exists with that name.  Do you want to overwrite it?"));
2580                         confirm.get_vbox()->pack_start (m, true, true);
2581                         confirm.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2582                         confirm.add_button (_("Overwrite"), Gtk::RESPONSE_ACCEPT);
2583                         confirm.show_all ();
2584                         switch (confirm.run()) {
2585                         case RESPONSE_CANCEL:
2586                                 do_save = false;
2587                         }
2588                 }
2589
2590                 if (do_save) {
2591                         save_state (snapname, switch_to_it);
2592                 }
2593                 break;
2594         }
2595
2596         default:
2597                 break;
2598         }
2599 }
2600
2601 /** Ask the user for a new session name and then rename the session to it.
2602  */
2603
2604 void
2605 ARDOUR_UI::rename_session ()
2606 {
2607         if (!_session) {
2608                 return;
2609         }
2610
2611         ArdourPrompter prompter (true);
2612         string name;
2613
2614         prompter.set_name ("Prompter");
2615         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2616         prompter.set_title (_("Rename Session"));
2617         prompter.set_prompt (_("New session name"));
2618
2619   again:
2620         switch (prompter.run()) {
2621         case RESPONSE_ACCEPT:
2622         {
2623                 prompter.get_result (name);
2624
2625                 bool do_rename = (name.length() != 0);
2626
2627                 if (do_rename) {
2628                         char illegal = Session::session_name_is_legal (name);
2629
2630                         if (illegal) {
2631                                 MessageDialog msg (string_compose (_("To ensure compatibility with various systems\n"
2632                                                                      "session names may not contain a '%1' character"), illegal));
2633                                 msg.run ();
2634                                 goto again;
2635                         }
2636
2637                         switch (_session->rename (name)) {
2638                         case -1: {
2639                                 MessageDialog msg (_("That name is already in use by another directory/folder. Please try again."));
2640                                 msg.set_position (WIN_POS_MOUSE);
2641                                 msg.run ();
2642                                 goto again;
2643                                 break;
2644                         }
2645                         case 0:
2646                                 break;
2647                         default: {
2648                                 MessageDialog msg (_("Renaming this session failed.\nThings could be seriously messed up at this point"));
2649                                 msg.set_position (WIN_POS_MOUSE);
2650                                 msg.run ();
2651                                 break;
2652                         }
2653                         }
2654                 }
2655                 
2656                 break;
2657         }
2658
2659         default:
2660                 break;
2661         }
2662 }
2663
2664 void
2665 ARDOUR_UI::save_state (const string & name, bool switch_to_it)
2666 {
2667         XMLNode* node = new XMLNode (X_("UI"));
2668
2669         WM::Manager::instance().add_state (*node);
2670
2671         node->add_child_nocopy (gui_object_state->get_state());
2672
2673         _session->add_extra_xml (*node);
2674
2675         if (export_video_dialog) {
2676                 _session->add_extra_xml (export_video_dialog->get_state());
2677         }
2678
2679         save_state_canfail (name, switch_to_it);
2680 }
2681
2682 int
2683 ARDOUR_UI::save_state_canfail (string name, bool switch_to_it)
2684 {
2685         if (_session) {
2686                 int ret;
2687
2688                 if (name.length() == 0) {
2689                         name = _session->snap_name();
2690                 }
2691
2692                 if ((ret = _session->save_state (name, false, switch_to_it)) != 0) {
2693                         return ret;
2694                 }
2695         }
2696
2697         save_ardour_state (); /* XXX cannot fail? yeah, right ... */
2698         return 0;
2699 }
2700
2701 void
2702 ARDOUR_UI::primary_clock_value_changed ()
2703 {
2704         if (_session) {
2705                 _session->request_locate (primary_clock->current_time ());
2706         }
2707 }
2708
2709 void
2710 ARDOUR_UI::big_clock_value_changed ()
2711 {
2712         if (_session) {
2713                 _session->request_locate (big_clock->current_time ());
2714         }
2715 }
2716
2717 void
2718 ARDOUR_UI::secondary_clock_value_changed ()
2719 {
2720         if (_session) {
2721                 _session->request_locate (secondary_clock->current_time ());
2722         }
2723 }
2724
2725 void
2726 ARDOUR_UI::transport_rec_enable_blink (bool onoff)
2727 {
2728         if (_session == 0) {
2729                 return;
2730         }
2731
2732         if (_session->step_editing()) {
2733                 return;
2734         }
2735
2736         Session::RecordState const r = _session->record_status ();
2737         bool const h = _session->have_rec_enabled_track ();
2738
2739         if (r == Session::Enabled || (r == Session::Recording && !h)) {
2740                 if (onoff) {
2741                         rec_button.set_active_state (Gtkmm2ext::ExplicitActive);
2742                 } else {
2743                         rec_button.set_active_state (Gtkmm2ext::Off);
2744                 }
2745         } else if (r == Session::Recording && h) {
2746                 rec_button.set_active_state (Gtkmm2ext::ExplicitActive);
2747         } else {
2748                 rec_button.unset_active_state ();
2749         }
2750 }
2751
2752 void
2753 ARDOUR_UI::save_template ()
2754 {
2755         ArdourPrompter prompter (true);
2756         string name;
2757
2758         if (!check_audioengine()) {
2759                 return;
2760         }
2761
2762         prompter.set_name (X_("Prompter"));
2763         prompter.set_title (_("Save Template"));
2764         prompter.set_prompt (_("Name for template:"));
2765         prompter.set_initial_text(_session->name() + _("-template"));
2766         prompter.add_button (Gtk::Stock::SAVE, Gtk::RESPONSE_ACCEPT);
2767
2768         switch (prompter.run()) {
2769         case RESPONSE_ACCEPT:
2770                 prompter.get_result (name);
2771
2772                 if (name.length()) {
2773                         _session->save_template (name);
2774                 }
2775                 break;
2776
2777         default:
2778                 break;
2779         }
2780 }
2781
2782 void
2783 ARDOUR_UI::edit_metadata ()
2784 {
2785         SessionMetadataEditor dialog;
2786         dialog.set_session (_session);
2787         dialog.grab_focus ();
2788         dialog.run ();
2789 }
2790
2791 void
2792 ARDOUR_UI::import_metadata ()
2793 {
2794         SessionMetadataImporter dialog;
2795         dialog.set_session (_session);
2796         dialog.run ();
2797 }
2798
2799 bool
2800 ARDOUR_UI::ask_about_loading_existing_session (const std::string& session_path)
2801 {
2802         std::string str = string_compose (_("This session\n%1\nalready exists. Do you want to open it?"), session_path);
2803
2804         MessageDialog msg (str,
2805                            false,
2806                            Gtk::MESSAGE_WARNING,
2807                            Gtk::BUTTONS_YES_NO,
2808                            true);
2809
2810
2811         msg.set_name (X_("OpenExistingDialog"));
2812         msg.set_title (_("Open Existing Session"));
2813         msg.set_wmclass (X_("existing_session"), PROGRAM_NAME);
2814         msg.set_position (Gtk::WIN_POS_CENTER);
2815         pop_back_splash (msg);
2816
2817         switch (msg.run()) {
2818         case RESPONSE_YES:
2819                 return true;
2820                 break;
2821         }
2822         return false;
2823 }
2824
2825 int
2826 ARDOUR_UI::build_session_from_dialog (SessionDialog& sd, const std::string& session_path, const std::string& session_name)
2827 {
2828         BusProfile bus_profile;
2829
2830         if (nsm || Profile->get_sae()) {
2831
2832                 bus_profile.master_out_channels = 2;
2833                 bus_profile.input_ac = AutoConnectPhysical;
2834                 bus_profile.output_ac = AutoConnectMaster;
2835                 bus_profile.requested_physical_in = 0; // use all available
2836                 bus_profile.requested_physical_out = 0; // use all available
2837
2838         } else {
2839
2840                 /* get settings from advanced section of NSD */
2841
2842                 if (sd.create_master_bus()) {
2843                         bus_profile.master_out_channels = (uint32_t) sd.master_channel_count();
2844                 } else {
2845                         bus_profile.master_out_channels = 0;
2846                 }
2847
2848                 if (sd.connect_inputs()) {
2849                         bus_profile.input_ac = AutoConnectPhysical;
2850                 } else {
2851                         bus_profile.input_ac = AutoConnectOption (0);
2852                 }
2853
2854                 bus_profile.output_ac = AutoConnectOption (0);
2855
2856                 if (sd.connect_outputs ()) {
2857                         if (sd.connect_outs_to_master()) {
2858                                 bus_profile.output_ac = AutoConnectMaster;
2859                         } else if (sd.connect_outs_to_physical()) {
2860                                 bus_profile.output_ac = AutoConnectPhysical;
2861                         }
2862                 }
2863
2864                 bus_profile.requested_physical_in = (uint32_t) sd.input_limit_count();
2865                 bus_profile.requested_physical_out = (uint32_t) sd.output_limit_count();
2866         }
2867
2868         if (build_session (session_path, session_name, bus_profile)) {
2869                 return -1;
2870         }
2871
2872         return 0;
2873 }
2874
2875 void
2876 ARDOUR_UI::load_from_application_api (const std::string& path)
2877 {
2878         ARDOUR_COMMAND_LINE::session_name = path;
2879
2880         if (Glib::file_test (path, Glib::FILE_TEST_IS_DIR)) {
2881                 /* /path/to/foo => /path/to/foo, foo */
2882                 load_session (path, basename_nosuffix (path));
2883         } else {
2884                 /* /path/to/foo/foo.ardour => /path/to/foo, foo */
2885                 load_session (Glib::path_get_dirname (path), basename_nosuffix (path));
2886         }
2887 }
2888
2889 /** @param quit_on_cancel true if exit() should be called if the user clicks `cancel' in the new session dialog */
2890 int
2891 ARDOUR_UI::get_session_parameters (bool quit_on_cancel, bool should_be_new, string load_template)
2892 {
2893         string session_name;
2894         string session_path;
2895         string template_name;
2896         int ret = -1;
2897         bool likely_new = false;
2898         bool cancel_not_quit;
2899
2900         /* deal with any existing DIRTY session now, rather than later. don't
2901          * treat a non-dirty session this way, so that it stays visible 
2902          * as we bring up the new session dialog.
2903          */
2904
2905         if (_session && ARDOUR_UI::instance()->video_timeline) {
2906                 ARDOUR_UI::instance()->video_timeline->sync_session_state();
2907         }
2908
2909         /* if there is already a session, relabel the button
2910            on the SessionDialog so that we don't Quit directly
2911         */
2912         cancel_not_quit = (_session != 0);
2913
2914         if (_session && _session->dirty()) {
2915                 if (unload_session (false)) {
2916                         /* unload cancelled by user */
2917                         return 0;
2918                 }
2919                 ARDOUR_COMMAND_LINE::session_name = "";
2920         }
2921
2922         if (!load_template.empty()) {
2923                 should_be_new = true;
2924                 template_name = load_template;
2925         }
2926
2927         session_name = basename_nosuffix (ARDOUR_COMMAND_LINE::session_name);
2928         session_path = ARDOUR_COMMAND_LINE::session_name;
2929         
2930         if (!session_path.empty()) {
2931                 if (Glib::file_test (session_path.c_str(), Glib::FILE_TEST_EXISTS)) {
2932                         if (Glib::file_test (session_path.c_str(), Glib::FILE_TEST_IS_REGULAR)) {
2933                                 /* session/snapshot file, change path to be dir */
2934                                 session_path = Glib::path_get_dirname (session_path);
2935                         }
2936                 }
2937         }
2938
2939         SessionDialog session_dialog (should_be_new, session_name, session_path, load_template, cancel_not_quit);
2940
2941         while (ret != 0) {
2942
2943                 if (!ARDOUR_COMMAND_LINE::session_name.empty()) {
2944
2945                         /* if they named a specific statefile, use it, otherwise they are
2946                            just giving a session folder, and we want to use it as is
2947                            to find the session.
2948                         */
2949
2950                         string::size_type suffix = ARDOUR_COMMAND_LINE::session_name.find (statefile_suffix);
2951
2952                         if (suffix != string::npos) {
2953                                 session_path = Glib::path_get_dirname (ARDOUR_COMMAND_LINE::session_name);
2954                                 session_name = ARDOUR_COMMAND_LINE::session_name.substr (0, suffix);
2955                                 session_name = Glib::path_get_basename (session_name);
2956                         } else {
2957                                 session_path = ARDOUR_COMMAND_LINE::session_name;
2958                                 session_name = Glib::path_get_basename (ARDOUR_COMMAND_LINE::session_name);
2959                         }
2960                 } else {
2961                         session_path = "";
2962                         session_name = "";
2963                         session_dialog.clear_given ();
2964                 }
2965                 
2966                 if (should_be_new || session_name.empty()) {
2967                         /* need the dialog to get info from user */
2968
2969                         cerr << "run dialog\n";
2970
2971                         switch (session_dialog.run()) {
2972                         case RESPONSE_ACCEPT:
2973                                 break;
2974                         default:
2975                                 if (quit_on_cancel) {
2976                                         // JE - Currently (July 2014) this section can only get reached if the
2977                                         // user quits from the main 'Session Setup' dialog (i.e. reaching this
2978                                         // point does NOT indicate an abnormal termination). Therefore, let's
2979                                         // behave gracefully (i.e. let's do some cleanup) before we call exit()
2980                                         ARDOUR::cleanup ();
2981                                         pthread_cancel_all ();
2982
2983                                         exit (1);
2984                                 } else {
2985                                         return ret;
2986                                 }
2987                         }
2988
2989                         session_dialog.hide ();
2990                 }
2991
2992                 /* if we run the startup dialog again, offer more than just "new session" */
2993                 
2994                 should_be_new = false;
2995                 
2996                 session_name = session_dialog.session_name (likely_new);
2997                 session_path = session_dialog.session_folder ();
2998
2999                 if (nsm) {
3000                         likely_new = true;
3001                 }
3002
3003                 string::size_type suffix = session_name.find (statefile_suffix);
3004                 
3005                 if (suffix != string::npos) {
3006                         session_name = session_name.substr (0, suffix);
3007                 }
3008                 
3009                 /* this shouldn't happen, but we catch it just in case it does */
3010                 
3011                 if (session_name.empty()) {
3012                         continue;
3013                 }
3014                 
3015                 if (session_dialog.use_session_template()) {
3016                         template_name = session_dialog.session_template_name();
3017                         _session_is_new = true;
3018                 }
3019                 
3020                 if (session_name[0] == G_DIR_SEPARATOR ||
3021 #ifdef PLATFORM_WINDOWS
3022                     (session_name.length() > 3 && session_name[1] == ':' && session_name[2] == G_DIR_SEPARATOR)
3023 #else
3024                     (session_name.length() > 2 && session_name[0] == '.' && session_name[1] == G_DIR_SEPARATOR) ||
3025                     (session_name.length() > 3 && session_name[0] == '.' && session_name[1] == '.' && session_name[2] == G_DIR_SEPARATOR)
3026 #endif
3027                          )
3028                 {
3029                         
3030                         /* absolute path or cwd-relative path specified for session name: infer session folder
3031                            from what was given.
3032                         */
3033                         
3034                         session_path = Glib::path_get_dirname (session_name);
3035                         session_name = Glib::path_get_basename (session_name);
3036                         
3037                 } else {
3038
3039                         session_path = session_dialog.session_folder();
3040                         
3041                         char illegal = Session::session_name_is_legal (session_name);
3042                         
3043                         if (illegal) {
3044                                 MessageDialog msg (session_dialog,
3045                                                    string_compose (_("To ensure compatibility with various systems\n"
3046                                                                      "session names may not contain a '%1' character"),
3047                                                                    illegal));
3048                                 msg.run ();
3049                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
3050                                 continue;
3051                         }
3052                 }
3053         
3054                 if (Glib::file_test (session_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) {
3055
3056
3057                         if (likely_new && !nsm) {
3058
3059                                 std::string existing = Glib::build_filename (session_path, session_name);
3060
3061                                 if (!ask_about_loading_existing_session (existing)) {
3062                                         ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
3063                                         continue;
3064                                 }
3065                         }
3066
3067                         _session_is_new = false;
3068
3069                 } else {
3070
3071                         if (!likely_new) {
3072                                 pop_back_splash (session_dialog);
3073                                 MessageDialog msg (string_compose (_("There is no existing session at \"%1\""), session_path));
3074                                 msg.run ();
3075                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
3076                                 continue;
3077                         }
3078
3079                         char illegal = Session::session_name_is_legal(session_name);
3080
3081                         if (illegal) {
3082                                 pop_back_splash (session_dialog);
3083                                 MessageDialog msg (session_dialog, string_compose(_("To ensure compatibility with various systems\n"
3084                                                                                     "session names may not contain a '%1' character"), illegal));
3085                                 msg.run ();
3086                                 ARDOUR_COMMAND_LINE::session_name = ""; // cancel that
3087                                 continue;
3088                         }
3089
3090                         _session_is_new = true;
3091                 }
3092
3093                 if (likely_new && template_name.empty()) {
3094
3095                         ret = build_session_from_dialog (session_dialog, session_path, session_name);
3096
3097                 } else {
3098
3099                         ret = load_session (session_path, session_name, template_name);
3100
3101                         if (ret == -2) {
3102                                 /* not connected to the AudioEngine, so quit to avoid an infinite loop */
3103                                 exit (1);
3104                         }
3105
3106                         if (!ARDOUR_COMMAND_LINE::immediate_save.empty()) {
3107                                 _session->save_state (ARDOUR_COMMAND_LINE::immediate_save, false);
3108                                 exit (1);
3109                         }
3110
3111                         /* clear this to avoid endless attempts to load the
3112                            same session.
3113                         */
3114
3115                         ARDOUR_COMMAND_LINE::session_name = "";
3116                 }
3117         }
3118
3119         return ret;
3120 }
3121
3122 void
3123 ARDOUR_UI::close_session()
3124 {
3125         if (!check_audioengine()) {
3126                 return;
3127         }
3128
3129         if (unload_session (true)) {
3130                 return;
3131         }
3132
3133         ARDOUR_COMMAND_LINE::session_name = "";
3134
3135         if (get_session_parameters (true, false)) {
3136                 exit (1);
3137         }
3138
3139         goto_editor_window ();
3140 }
3141
3142 /** @param snap_name Snapshot name (without .ardour suffix).
3143  *  @return -2 if the load failed because we are not connected to the AudioEngine.
3144  */
3145 int
3146 ARDOUR_UI::load_session (const std::string& path, const std::string& snap_name, std::string mix_template)
3147 {
3148         Session *new_session;
3149         int unload_status;
3150         int retval = -1;
3151
3152         if (_session) {
3153                 unload_status = unload_session ();
3154                 
3155                 if (unload_status < 0) {
3156                         goto out;
3157                 } else if (unload_status > 0) {
3158                         retval = 0;
3159                         goto out;
3160                 }
3161         }
3162
3163         session_loaded = false;
3164
3165         loading_message (string_compose (_("Please wait while %1 loads your session"), PROGRAM_NAME));
3166
3167         try {
3168                 new_session = new Session (*AudioEngine::instance(), path, snap_name, 0, mix_template);
3169         }
3170
3171         /* this one is special */
3172
3173         catch (AudioEngine::PortRegistrationFailure& err) {
3174
3175                 MessageDialog msg (err.what(),
3176                                    true,
3177                                    Gtk::MESSAGE_INFO,
3178                                    Gtk::BUTTONS_CLOSE);
3179
3180                 msg.set_title (_("Port Registration Error"));
3181                 msg.set_secondary_text (_("Click the Close button to try again."));
3182                 msg.set_position (Gtk::WIN_POS_CENTER);
3183                 pop_back_splash (msg);
3184                 msg.present ();
3185
3186                 int response = msg.run ();
3187
3188                 msg.hide ();
3189
3190                 switch (response) {
3191                 case RESPONSE_CANCEL:
3192                         exit (1);
3193                 default:
3194                         break;
3195                 }
3196                 goto out;
3197         }
3198
3199         catch (...) {
3200
3201                 MessageDialog msg (string_compose(
3202                                            _("Session \"%1 (snapshot %2)\" did not load successfully"),
3203                                            path, snap_name),
3204                                    true,
3205                                    Gtk::MESSAGE_INFO,
3206                                    BUTTONS_OK);
3207
3208                 msg.set_title (_("Loading Error"));
3209                 msg.set_position (Gtk::WIN_POS_CENTER);
3210                 pop_back_splash (msg);
3211                 msg.present ();
3212                 (void) msg.run ();
3213                 msg.hide ();
3214
3215                 goto out;
3216         }
3217
3218         {
3219                 list<string> const u = new_session->unknown_processors ();
3220                 if (!u.empty()) {
3221                         MissingPluginDialog d (_session, u);
3222                         d.run ();
3223                 }
3224         }
3225
3226         if (!new_session->writable()) {
3227                 MessageDialog msg (_("This session has been opened in read-only mode.\n\nYou will not be able to record or save."),
3228                                    true,
3229                                    Gtk::MESSAGE_INFO,
3230                                    BUTTONS_OK);
3231
3232                 msg.set_title (_("Read-only Session"));
3233                 msg.set_position (Gtk::WIN_POS_CENTER);
3234                 pop_back_splash (msg);
3235                 msg.present ();
3236                 (void) msg.run ();
3237                 msg.hide ();
3238         }
3239         
3240
3241         /* Now the session been created, add the transport controls */
3242         new_session->add_controllable(roll_controllable);
3243         new_session->add_controllable(stop_controllable);
3244         new_session->add_controllable(goto_start_controllable);
3245         new_session->add_controllable(goto_end_controllable);
3246         new_session->add_controllable(auto_loop_controllable);
3247         new_session->add_controllable(play_selection_controllable);
3248         new_session->add_controllable(rec_controllable);
3249
3250         set_session (new_session);
3251
3252         session_loaded = true;
3253
3254         goto_editor_window ();
3255
3256         if (_session) {
3257                 _session->set_clean ();
3258         }
3259
3260 #ifdef WINDOWS_VST_SUPPORT
3261         fst_stop_threading();
3262 #endif
3263
3264         flush_pending ();
3265
3266 #ifdef WINDOWS_VST_SUPPORT
3267         fst_start_threading();
3268 #endif
3269         retval = 0;
3270
3271   out:
3272         return retval;
3273 }
3274
3275 int
3276 ARDOUR_UI::build_session (const std::string& path, const std::string& snap_name, BusProfile& bus_profile)
3277 {
3278         Session *new_session;
3279         int x;
3280
3281         session_loaded = false;
3282         x = unload_session ();
3283
3284         if (x < 0) {
3285                 return -1;
3286         } else if (x > 0) {
3287                 return 0;
3288         }
3289
3290         _session_is_new = true;
3291
3292         try {
3293                 new_session = new Session (*AudioEngine::instance(), path, snap_name, &bus_profile);
3294         }
3295
3296         catch (...) {
3297
3298                 MessageDialog msg (string_compose(_("Could not create session in \"%1\""), path));
3299                 pop_back_splash (msg);
3300                 msg.run ();
3301                 return -1;
3302         }
3303
3304         /* Give the new session the default GUI state, if such things exist */
3305
3306         XMLNode* n;
3307         n = Config->instant_xml (X_("Editor"));
3308         if (n) {
3309                 n->remove_nodes_and_delete ("Selection"); // no not apply selection to new sessions.
3310                 new_session->add_instant_xml (*n, false);
3311         }
3312         n = Config->instant_xml (X_("Mixer"));
3313         if (n) {
3314                 new_session->add_instant_xml (*n, false);
3315         }
3316
3317         /* Put the playhead at 0 and scroll fully left */
3318         n = new_session->instant_xml (X_("Editor"));
3319         if (n) {
3320                 n->add_property (X_("playhead"), X_("0"));
3321                 n->add_property (X_("left-frame"), X_("0"));
3322         }
3323
3324         set_session (new_session);
3325
3326         session_loaded = true;
3327
3328         new_session->save_state(new_session->name());
3329
3330         return 0;
3331 }
3332
3333 void
3334 ARDOUR_UI::launch_chat ()
3335 {
3336 #ifdef __APPLE__
3337         open_uri("http://webchat.freenode.net/?channels=ardour-osx");
3338 #elif defined PLATFORM_WINDOWS
3339         open_uri("http://webchat.freenode.net/?channels=ardour-windows");
3340 #else
3341         open_uri("http://webchat.freenode.net/?channels=ardour");
3342 #endif
3343 }
3344
3345 void
3346 ARDOUR_UI::launch_manual ()
3347 {
3348         PBD::open_uri (Config->get_tutorial_manual_url());
3349 }
3350
3351 void
3352 ARDOUR_UI::launch_reference ()
3353 {
3354         PBD::open_uri (Config->get_reference_manual_url());
3355 }
3356
3357 void
3358 ARDOUR_UI::launch_tracker ()
3359 {
3360         PBD::open_uri ("http://tracker.ardour.org/bug_report_page.php");
3361 }
3362
3363 void
3364 ARDOUR_UI::launch_subscribe ()
3365 {
3366         PBD::open_uri ("https://community.ardour.org/s/subscribe");
3367 }
3368
3369 void
3370 ARDOUR_UI::launch_cheat_sheet ()
3371 {
3372 #ifdef __APPLE__
3373         PBD::open_uri ("http://manual.ardour.org/files/a3_mnemonic_cheat_sheet_osx.pdf");
3374 #else
3375         PBD::open_uri ("http://manual.ardour.org/files/a3_mnemonic_cheatsheet.pdf");
3376 #endif
3377 }
3378
3379 void
3380 ARDOUR_UI::launch_website ()
3381 {
3382         PBD::open_uri ("http://ardour.org");
3383 }
3384
3385 void
3386 ARDOUR_UI::launch_website_dev ()
3387 {
3388         PBD::open_uri ("http://ardour.org/development.html");
3389 }
3390
3391 void
3392 ARDOUR_UI::launch_forums ()
3393 {
3394         PBD::open_uri ("https://community.ardour.org/forums");
3395 }
3396
3397 void
3398 ARDOUR_UI::launch_howto_report ()
3399 {
3400         PBD::open_uri ("http://ardour.org/reporting_bugs");
3401 }
3402
3403 void
3404 ARDOUR_UI::loading_message (const std::string& msg)
3405 {
3406         if (ARDOUR_COMMAND_LINE::no_splash) {
3407                 return;
3408         }
3409
3410         if (!splash) {
3411                 show_splash ();
3412         }
3413
3414         splash->message (msg);
3415 }
3416
3417 void
3418 ARDOUR_UI::show_splash ()
3419 {
3420         if (splash == 0) {
3421                 try {
3422                         splash = new Splash;
3423                 } catch (...) {
3424                         return;
3425                 }
3426         }
3427
3428         splash->display ();
3429 }
3430
3431 void
3432 ARDOUR_UI::hide_splash ()
3433 {
3434         delete splash;
3435         splash = 0;
3436 }
3437
3438 void
3439 ARDOUR_UI::display_cleanup_results (ARDOUR::CleanupReport& rep, const gchar* list_title, const bool msg_delete)
3440 {
3441         size_t removed;
3442
3443         removed = rep.paths.size();
3444
3445         if (removed == 0) {
3446                 MessageDialog msgd (*editor,
3447                                     _("No files were ready for clean-up"),
3448                                     true,
3449                                     Gtk::MESSAGE_INFO,
3450                                     Gtk::BUTTONS_OK);
3451                 msgd.set_title (_("Clean-up"));
3452                 msgd.set_secondary_text (_("If this seems suprising, \n\
3453 check for any existing snapshots.\n\
3454 These may still include regions that\n\
3455 require some unused files to continue to exist."));
3456
3457                 msgd.run ();
3458                 return;
3459         }
3460
3461         ArdourDialog results (_("Clean-up"), true, false);
3462
3463         struct CleanupResultsModelColumns : public Gtk::TreeModel::ColumnRecord {
3464             CleanupResultsModelColumns() {
3465                     add (visible_name);
3466                     add (fullpath);
3467             }
3468             Gtk::TreeModelColumn<std::string> visible_name;
3469             Gtk::TreeModelColumn<std::string> fullpath;
3470         };
3471
3472
3473         CleanupResultsModelColumns results_columns;
3474         Glib::RefPtr<Gtk::ListStore> results_model;
3475         Gtk::TreeView results_display;
3476
3477         results_model = ListStore::create (results_columns);
3478         results_display.set_model (results_model);
3479         results_display.append_column (list_title, results_columns.visible_name);
3480
3481         results_display.set_name ("CleanupResultsList");
3482         results_display.set_headers_visible (true);
3483         results_display.set_headers_clickable (false);
3484         results_display.set_reorderable (false);
3485
3486         Gtk::ScrolledWindow list_scroller;
3487         Gtk::Label txt;
3488         Gtk::VBox dvbox;
3489         Gtk::HBox dhbox;  // the hbox for the image and text
3490         Gtk::HBox ddhbox; // the hbox we eventually pack into the dialog's vbox
3491         Gtk::Image* dimage = manage (new Gtk::Image(Stock::DIALOG_INFO,  Gtk::ICON_SIZE_DIALOG));
3492
3493         dimage->set_alignment(ALIGN_LEFT, ALIGN_TOP);
3494
3495         const string dead_directory = _session->session_directory().dead_path();
3496
3497         /* subst:
3498            %1 - number of files removed
3499            %2 - location of "dead"
3500            %3 - size of files affected
3501            %4 - prefix for "bytes" to produce sensible results (e.g. mega, kilo, giga)
3502         */
3503
3504         const char* bprefix;
3505         double space_adjusted = 0;
3506
3507         if (rep.space < 1000) {
3508                 bprefix = X_("");
3509                 space_adjusted = rep.space;
3510         } else if (rep.space < 1000000) {
3511                 bprefix = _("kilo");
3512                 space_adjusted = floorf((float)rep.space / 1000.0);
3513         } else if (rep.space < 1000000 * 1000) {
3514                 bprefix = _("mega");
3515                 space_adjusted = floorf((float)rep.space / (1000.0 * 1000.0));
3516         } else {
3517                 bprefix = _("giga");
3518                 space_adjusted = floorf((float)rep.space / (1000.0 * 1000 * 1000.0));
3519         }
3520
3521         if (msg_delete) {
3522                 txt.set_markup (string_compose (P_("\
3523 The following file was deleted from %2,\n\
3524 releasing %3 %4bytes of disk space", "\
3525 The following %1 files were deleted from %2,\n\
3526 releasing %3 %4bytes of disk space", removed),
3527                                         removed, Glib::Markup::escape_text (dead_directory), space_adjusted, bprefix, PROGRAM_NAME));
3528         } else {
3529                 txt.set_markup (string_compose (P_("\
3530 The following file was not in use and \n\
3531 has been moved to: %2\n\n\
3532 After a restart of %5\n\n\
3533 <span face=\"mono\">Session -> Clean-up -> Flush Wastebasket</span>\n\n\
3534 will release an additional %3 %4bytes of disk space.\n", "\
3535 The following %1 files were not in use and \n\
3536 have been moved to: %2\n\n\
3537 After a restart of %5\n\n\
3538 <span face=\"mono\">Session -> Clean-up -> Flush Wastebasket</span>\n\n\
3539 will release an additional %3 %4bytes of disk space.\n", removed),
3540                                         removed, Glib::Markup::escape_text (dead_directory), space_adjusted, bprefix, PROGRAM_NAME));
3541         }
3542
3543         dhbox.pack_start (*dimage, true, false, 5);
3544         dhbox.pack_start (txt, true, false, 5);
3545
3546         for (vector<string>::iterator i = rep.paths.begin(); i != rep.paths.end(); ++i) {
3547                 TreeModel::Row row = *(results_model->append());
3548                 row[results_columns.visible_name] = *i;
3549                 row[results_columns.fullpath] = *i;
3550         }
3551
3552         list_scroller.add (results_display);
3553         list_scroller.set_size_request (-1, 150);
3554         list_scroller.set_policy (Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC);
3555
3556         dvbox.pack_start (dhbox, true, false, 5);
3557         dvbox.pack_start (list_scroller, true, false, 5);
3558         ddhbox.pack_start (dvbox, true, false, 5);
3559
3560         results.get_vbox()->pack_start (ddhbox, true, false, 5);
3561         results.add_button (Stock::CLOSE, RESPONSE_CLOSE);
3562         results.set_default_response (RESPONSE_CLOSE);
3563         results.set_position (Gtk::WIN_POS_MOUSE);
3564
3565         results_display.show();
3566         list_scroller.show();
3567         txt.show();
3568         dvbox.show();
3569         dhbox.show();
3570         ddhbox.show();
3571         dimage->show();
3572
3573         //results.get_vbox()->show();
3574         results.set_resizable (false);
3575
3576         results.run ();
3577
3578 }
3579
3580 void
3581 ARDOUR_UI::cleanup ()
3582 {
3583         if (_session == 0) {
3584                 /* shouldn't happen: menu item is insensitive */
3585                 return;
3586         }
3587
3588
3589         MessageDialog checker (_("Are you sure you want to clean-up?"),
3590                                 true,
3591                                 Gtk::MESSAGE_QUESTION,
3592                                 Gtk::BUTTONS_NONE);
3593
3594         checker.set_title (_("Clean-up"));
3595
3596         checker.set_secondary_text(_("Clean-up is a destructive operation.\n\
3597 ALL undo/redo information will be lost if you clean-up.\n\
3598 Clean-up will move all unused files to a \"dead\" location."));
3599
3600         checker.add_button (Stock::CANCEL, RESPONSE_CANCEL);
3601         checker.add_button (_("Clean-up"), RESPONSE_ACCEPT);
3602         checker.set_default_response (RESPONSE_CANCEL);
3603
3604         checker.set_name (_("CleanupDialog"));
3605         checker.set_wmclass (X_("ardour_cleanup"), PROGRAM_NAME);
3606         checker.set_position (Gtk::WIN_POS_MOUSE);
3607
3608         switch (checker.run()) {
3609         case RESPONSE_ACCEPT:
3610                 break;
3611         default:
3612                 return;
3613         }
3614
3615         ARDOUR::CleanupReport rep;
3616
3617         editor->prepare_for_cleanup ();
3618
3619         /* do not allow flush until a session is reloaded */
3620
3621         Glib::RefPtr<Action> act = ActionManager::get_action (X_("Main"), X_("FlushWastebasket"));
3622         if (act) {
3623                 act->set_sensitive (false);
3624         }
3625
3626         if (_session->cleanup_sources (rep)) {
3627                 editor->finish_cleanup ();
3628                 return;
3629         }
3630
3631         editor->finish_cleanup ();
3632
3633         checker.hide();
3634         display_cleanup_results (rep, _("Cleaned Files"), false);
3635 }
3636
3637 void
3638 ARDOUR_UI::flush_trash ()
3639 {
3640         if (_session == 0) {
3641                 /* shouldn't happen: menu item is insensitive */
3642                 return;
3643         }
3644
3645         ARDOUR::CleanupReport rep;
3646
3647         if (_session->cleanup_trash_sources (rep)) {
3648                 return;
3649         }
3650
3651         display_cleanup_results (rep, _("deleted file"), true);
3652 }
3653
3654 void
3655 ARDOUR_UI::setup_order_hint (AddRouteDialog::InsertAt place)
3656 {
3657         uint32_t order_hint = UINT32_MAX;
3658
3659         if (editor->get_selection().tracks.empty()) {
3660                 return;
3661         }
3662         
3663         /*
3664           we want the new routes to have their order keys set starting from 
3665           the highest order key in the selection + 1 (if available).
3666         */
3667         
3668         if (place == AddRouteDialog::AfterSelection) {
3669                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView*> (editor->get_selection().tracks.back());
3670                 if (rtav) {
3671                         order_hint = rtav->route()->order_key();
3672                         order_hint++;
3673                 }
3674         } else if (place == AddRouteDialog::BeforeSelection) {
3675                 RouteTimeAxisView *rtav = dynamic_cast<RouteTimeAxisView*> (editor->get_selection().tracks.front());
3676                 if (rtav) {
3677                         order_hint = rtav->route()->order_key();
3678                 }
3679         } else if (place == AddRouteDialog::First) {
3680                 order_hint = 0;
3681         } else {
3682                 /* leave order_hint at UINT32_MAX */
3683         }
3684
3685         if (order_hint == UINT32_MAX) {
3686                 /** AddRouteDialog::Last or selection with first/last not a RouteTimeAxisView
3687                  * not setting an order hint will place new routes last.
3688                  */
3689                 return;
3690         }
3691
3692         _session->set_order_hint (order_hint);
3693
3694         /* create a gap in the existing route order keys to accomodate new routes.*/
3695         boost::shared_ptr <RouteList> rd = _session->get_routes();
3696         for (RouteList::iterator ri = rd->begin(); ri != rd->end(); ++ri) {
3697                 boost::shared_ptr<Route> rt (*ri);
3698
3699                 if (rt->is_monitor()) {
3700                         continue;
3701                 }
3702
3703                 if (rt->order_key () >= order_hint) {
3704                         rt->set_order_key (rt->order_key () + add_route_dialog->count());
3705                 }
3706         }
3707 }
3708
3709 void
3710 ARDOUR_UI::add_route (Gtk::Window* /* ignored */)
3711 {
3712         int count;
3713
3714         if (!_session) {
3715                 return;
3716         }
3717
3718         if (add_route_dialog->is_visible()) {
3719                 /* we're already doing this */
3720                 return;
3721         }
3722
3723         ResponseType r = (ResponseType) add_route_dialog->run ();
3724
3725         add_route_dialog->hide();
3726
3727         switch (r) {
3728                 case RESPONSE_ACCEPT:
3729                         break;
3730                 default:
3731                         return;
3732                         break;
3733         }
3734
3735         if ((count = add_route_dialog->count()) <= 0) {
3736                 return;
3737         }
3738
3739         setup_order_hint(add_route_dialog->insert_at());
3740
3741         string template_path = add_route_dialog->track_template();
3742         DisplaySuspender ds;
3743
3744         if (!template_path.empty()) {
3745                 if (add_route_dialog->name_template_is_default())  {
3746                         _session->new_route_from_template (count, template_path, string());
3747                 } else {
3748                         _session->new_route_from_template (count, template_path, add_route_dialog->name_template());
3749                 }
3750                 return;
3751         }
3752
3753         ChanCount input_chan= add_route_dialog->channels ();
3754         ChanCount output_chan;
3755         string name_template = add_route_dialog->name_template ();
3756         PluginInfoPtr instrument = add_route_dialog->requested_instrument ();
3757         RouteGroup* route_group = add_route_dialog->route_group ();
3758         AutoConnectOption oac = Config->get_output_auto_connect();
3759
3760         if (oac & AutoConnectMaster) {
3761                 output_chan.set (DataType::AUDIO, (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan.n_audio()));
3762                 output_chan.set (DataType::MIDI, 0);
3763         } else {
3764                 output_chan = input_chan;
3765         }
3766
3767         /* XXX do something with name template */
3768
3769         switch (add_route_dialog->type_wanted()) {
3770         case AddRouteDialog::AudioTrack:
3771                 session_add_audio_track (input_chan.n_audio(), output_chan.n_audio(), add_route_dialog->mode(), route_group, count, name_template);
3772                 break;
3773         case AddRouteDialog::MidiTrack:
3774                 session_add_midi_track (route_group, count, name_template, instrument);
3775                 break;
3776         case AddRouteDialog::MixedTrack:
3777                 session_add_mixed_track (input_chan, output_chan, route_group, count, name_template, instrument);
3778                 break;
3779         case AddRouteDialog::AudioBus:
3780                 session_add_audio_bus (input_chan.n_audio(), output_chan.n_audio(), route_group, count, name_template);
3781                 break;
3782         }
3783 }
3784
3785 void
3786 ARDOUR_UI::stop_video_server (bool ask_confirm)
3787 {
3788         if (!video_server_process && ask_confirm) {
3789                 warning << string_compose (_("Video-Server was not launched by %1. The request to stop it is ignored."), PROGRAM_NAME) << endmsg;
3790         }
3791         if (video_server_process) {
3792                 if(ask_confirm) {
3793                         ArdourDialog confirm (_("Stop Video-Server"), true);
3794                         Label m (_("Do you really want to stop the Video Server?"));
3795                         confirm.get_vbox()->pack_start (m, true, true);
3796                         confirm.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
3797                         confirm.add_button (_("Yes, Stop It"), Gtk::RESPONSE_ACCEPT);
3798                         confirm.show_all ();
3799                         if (confirm.run() == RESPONSE_CANCEL) {
3800                                 return;
3801                         }
3802                 }
3803                 delete video_server_process;
3804                 video_server_process =0;
3805         }
3806 }
3807
3808 void
3809 ARDOUR_UI::start_video_server_menu (Gtk::Window* float_window)
3810 {
3811   ARDOUR_UI::start_video_server( float_window, true);
3812 }
3813
3814 bool
3815 ARDOUR_UI::start_video_server (Gtk::Window* float_window, bool popup_msg)
3816 {
3817         if (!_session) {
3818                 return false;
3819         }
3820         if (popup_msg) {
3821                 if (ARDOUR_UI::instance()->video_timeline->check_server()) {
3822                         if (video_server_process) {
3823                                 popup_error(_("The Video Server is already started."));
3824                         } else {
3825                                 popup_error(_("An external Video Server is configured and can be reached. Not starting a new instance."));
3826                         }
3827                 }
3828         }
3829
3830         int firsttime = 0;
3831         while (!ARDOUR_UI::instance()->video_timeline->check_server()) {
3832                 if (firsttime++) {
3833                         warning << _("Could not connect to the Video Server. Start it or configure its access URL in Preferences.") << endmsg;
3834                 }
3835                 VideoServerDialog *video_server_dialog = new VideoServerDialog (_session);
3836                 if (float_window) {
3837                         video_server_dialog->set_transient_for (*float_window);
3838                 }
3839
3840                 if (!Config->get_show_video_server_dialog() && firsttime < 2) {
3841                         video_server_dialog->hide();
3842                 } else {
3843                         ResponseType r = (ResponseType) video_server_dialog->run ();
3844                         video_server_dialog->hide();
3845                         if (r != RESPONSE_ACCEPT) { return false; }
3846                         if (video_server_dialog->show_again()) {
3847                                 Config->set_show_video_server_dialog(false);
3848                         }
3849                 }
3850
3851                 std::string icsd_exec = video_server_dialog->get_exec_path();
3852                 std::string icsd_docroot = video_server_dialog->get_docroot();
3853                 if (icsd_docroot.empty()) {
3854 #ifndef PLATFORM_WINDOWS
3855                         icsd_docroot = X_("/");
3856 #else
3857                         icsd_docroot = X_("C:\\");
3858 #endif
3859                 }
3860
3861                 GStatBuf sb;
3862                 if (g_lstat (icsd_docroot.c_str(), &sb) != 0 || !S_ISDIR(sb.st_mode)) {
3863                         warning << _("Specified docroot is not an existing directory.") << endmsg;
3864                         continue;
3865                 }
3866 #ifndef PLATFORM_WINDOWS
3867                 if ( (g_lstat (icsd_exec.c_str(), &sb) != 0)
3868                      || (sb.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0 ) {
3869                         warning << _("Given Video Server is not an executable file.") << endmsg;
3870                         continue;
3871                 }
3872 #else
3873                 if ( (g_lstat (icsd_exec.c_str(), &sb) != 0)
3874                      || (sb.st_mode & (S_IXUSR)) == 0 ) {
3875                         warning << _("Given Video Server is not an executable file.") << endmsg;
3876                         continue;
3877                 }
3878 #endif
3879
3880                 char **argp;
3881                 argp=(char**) calloc(9,sizeof(char*));
3882                 argp[0] = strdup(icsd_exec.c_str());
3883                 argp[1] = strdup("-P");
3884                 argp[2] = (char*) calloc(16,sizeof(char)); snprintf(argp[2], 16, "%s", video_server_dialog->get_listenaddr().c_str());
3885                 argp[3] = strdup("-p");
3886                 argp[4] = (char*) calloc(6,sizeof(char)); snprintf(argp[4], 6, "%i", video_server_dialog->get_listenport());
3887                 argp[5] = strdup("-C");
3888                 argp[6] = (char*) calloc(6,sizeof(char)); snprintf(argp[6], 6, "%i", video_server_dialog->get_cachesize());
3889                 argp[7] = strdup(icsd_docroot.c_str());
3890                 argp[8] = 0;
3891                 stop_video_server();
3892
3893                 if (icsd_docroot == X_("/") || icsd_docroot == X_("C:\\")) {
3894                         Config->set_video_advanced_setup(false);
3895                 } else {
3896                         std::ostringstream osstream;
3897                         osstream << "http://localhost:" << video_server_dialog->get_listenport() << "/";
3898                         Config->set_video_server_url(osstream.str());
3899                         Config->set_video_server_docroot(icsd_docroot);
3900                         Config->set_video_advanced_setup(true);
3901                 }
3902
3903                 if (video_server_process) {
3904                         delete video_server_process;
3905                 }
3906
3907                 video_server_process = new ARDOUR::SystemExec(icsd_exec, argp);
3908                 if (video_server_process->start()) {
3909                         warning << _("Cannot launch the video-server") << endmsg;
3910                         continue;
3911                 }
3912                 int timeout = 120; // 6 sec
3913                 while (!ARDOUR_UI::instance()->video_timeline->check_server()) {
3914                         Glib::usleep (50000);
3915                         gui_idle_handler();
3916                         if (--timeout <= 0 || !video_server_process->is_running()) break;
3917                 }
3918                 if (timeout <= 0) {
3919                         warning << _("Video-server was started but does not respond to requests...") << endmsg;
3920                 } else {
3921                         if (!ARDOUR_UI::instance()->video_timeline->check_server_docroot()) {
3922                                 delete video_server_process;
3923                                 video_server_process = 0;
3924                         }
3925                 }
3926         }
3927         return true;
3928 }
3929
3930 void
3931 ARDOUR_UI::add_video (Gtk::Window* float_window)
3932 {
3933         if (!_session) {
3934                 return;
3935         }
3936
3937         if (!start_video_server(float_window, false)) {
3938                 warning << _("Could not connect to the Video Server. Start it or configure its access URL in Preferences.") << endmsg;
3939                 return;
3940         }
3941
3942         if (float_window) {
3943                 add_video_dialog->set_transient_for (*float_window);
3944         }
3945
3946         if (add_video_dialog->is_visible()) {
3947                 /* we're already doing this */
3948                 return;
3949         }
3950
3951         ResponseType r = (ResponseType) add_video_dialog->run ();
3952         add_video_dialog->hide();
3953         if (r != RESPONSE_ACCEPT) { return; }
3954
3955         bool local_file, orig_local_file;
3956         std::string path = add_video_dialog->file_name(local_file);
3957
3958         std::string orig_path = path;
3959         orig_local_file = local_file;
3960
3961         bool auto_set_session_fps = add_video_dialog->auto_set_session_fps();
3962
3963         if (local_file && !Glib::file_test(path, Glib::FILE_TEST_EXISTS)) {
3964                 warning << string_compose(_("could not open %1"), path) << endmsg;
3965                 return;
3966         }
3967         if (!local_file && path.length() == 0) {
3968                 warning << _("no video-file selected") << endmsg;
3969                 return;
3970         }
3971
3972         switch (add_video_dialog->import_option()) {
3973                 case VTL_IMPORT_TRANSCODE:
3974                         {
3975                                 TranscodeVideoDialog *transcode_video_dialog;
3976                                 transcode_video_dialog = new TranscodeVideoDialog (_session, path);
3977                                 ResponseType r = (ResponseType) transcode_video_dialog->run ();
3978                                 transcode_video_dialog->hide();
3979                                 if (r != RESPONSE_ACCEPT) {
3980                                         delete transcode_video_dialog;
3981                                         return;
3982                                 }
3983                                 if (!transcode_video_dialog->get_audiofile().empty()) {
3984                                         editor->embed_audio_from_video(
3985                                                         transcode_video_dialog->get_audiofile(),
3986                                                         video_timeline->get_offset(),
3987                                                         (transcode_video_dialog->import_option() != VTL_IMPORT_NO_VIDEO)
3988                                                         );
3989                                 }
3990                                 switch (transcode_video_dialog->import_option()) {
3991                                         case VTL_IMPORT_TRANSCODED:
3992                                                 path = transcode_video_dialog->get_filename();
3993                                                 local_file = true;
3994                                                 break;
3995                                         case VTL_IMPORT_REFERENCE:
3996                                                 break;
3997                                         default:
3998                                                 delete transcode_video_dialog;
3999                                                 return;
4000                                 }
4001                                 delete transcode_video_dialog;
4002                         }
4003                         break;
4004                 default:
4005                 case VTL_IMPORT_NONE:
4006                         break;
4007         }
4008
4009         /* strip _session->session_directory().video_path() from video file if possible */
4010         if (local_file && !path.compare(0, _session->session_directory().video_path().size(), _session->session_directory().video_path())) {
4011                  path=path.substr(_session->session_directory().video_path().size());
4012                  if (path.at(0) == G_DIR_SEPARATOR) {
4013                          path=path.substr(1);
4014                  }
4015         }
4016
4017         video_timeline->set_update_session_fps(auto_set_session_fps);
4018         if (video_timeline->video_file_info(path, local_file)) {
4019                 XMLNode* node = new XMLNode(X_("Videotimeline"));
4020                 node->add_property (X_("Filename"), path);
4021                 node->add_property (X_("AutoFPS"), auto_set_session_fps?X_("1"):X_("0"));
4022                 node->add_property (X_("LocalFile"), local_file?X_("1"):X_("0"));
4023                 if (orig_local_file) {
4024                         node->add_property (X_("OriginalVideoFile"), orig_path);
4025                 } else {
4026                         node->remove_property (X_("OriginalVideoFile"));
4027                 }
4028                 _session->add_extra_xml (*node);
4029                 _session->set_dirty ();
4030
4031                 _session->maybe_update_session_range(
4032                         std::max(video_timeline->get_offset(), (ARDOUR::frameoffset_t) 0),
4033                         std::max(video_timeline->get_offset() + video_timeline->get_duration(), (ARDOUR::frameoffset_t) 0));
4034
4035
4036                 if (add_video_dialog->launch_xjadeo() && local_file) {
4037                         editor->set_xjadeo_sensitive(true);
4038                         editor->toggle_xjadeo_proc(1);
4039                 } else {
4040                         editor->toggle_xjadeo_proc(0);
4041                 }
4042                 editor->toggle_ruler_video(true);
4043         }
4044 }
4045
4046 void
4047 ARDOUR_UI::remove_video ()
4048 {
4049         video_timeline->close_session();
4050         editor->toggle_ruler_video(false);
4051
4052         /* reset state */
4053         video_timeline->set_offset_locked(false);
4054         video_timeline->set_offset(0);
4055
4056         /* delete session state */
4057         XMLNode* node = new XMLNode(X_("Videotimeline"));
4058         _session->add_extra_xml(*node);
4059         node = new XMLNode(X_("Videomonitor"));
4060         _session->add_extra_xml(*node);
4061         node = new XMLNode(X_("Videoexport"));
4062         _session->add_extra_xml(*node);
4063         stop_video_server();
4064 }
4065
4066 void
4067 ARDOUR_UI::flush_videotimeline_cache (bool localcacheonly)
4068 {
4069         if (localcacheonly) {
4070                 video_timeline->vmon_update();
4071         } else {
4072                 video_timeline->flush_cache();
4073         }
4074         editor->queue_visual_videotimeline_update();
4075 }
4076
4077 void
4078 ARDOUR_UI::export_video (bool range)
4079 {
4080         if (ARDOUR::Config->get_show_video_export_info()) {
4081                 ExportVideoInfobox infobox (_session);
4082                 Gtk::ResponseType rv = (Gtk::ResponseType) infobox.run();
4083                 if (infobox.show_again()) {
4084                         ARDOUR::Config->set_show_video_export_info(false);
4085                 }
4086                 switch (rv) {
4087                         case GTK_RESPONSE_YES:
4088                                 PBD::open_uri (ARDOUR::Config->get_reference_manual_url() + "/video-timeline/operations/#export");
4089                                 break;
4090                         default:
4091                                 break;
4092                 }
4093         }
4094         export_video_dialog->set_session (_session);
4095         export_video_dialog->apply_state(editor->get_selection().time, range);
4096         export_video_dialog->run ();
4097         export_video_dialog->hide ();
4098 }
4099
4100 XMLNode*
4101 ARDOUR_UI::mixer_settings () const
4102 {
4103         XMLNode* node = 0;
4104
4105         if (_session) {
4106                 node = _session->instant_xml(X_("Mixer"));
4107         } else {
4108                 node = Config->instant_xml(X_("Mixer"));
4109         }
4110
4111         if (!node) {
4112                 node = new XMLNode (X_("Mixer"));
4113         }
4114
4115         return node;
4116 }
4117
4118 XMLNode*
4119 ARDOUR_UI::editor_settings () const
4120 {
4121         XMLNode* node = 0;
4122
4123         if (_session) {
4124                 node = _session->instant_xml(X_("Editor"));
4125         } else {
4126                 node = Config->instant_xml(X_("Editor"));
4127         }
4128
4129         if (!node) {
4130                 if (getenv("ARDOUR_INSTANT_XML_PATH")) {
4131                         node = Config->instant_xml(getenv("ARDOUR_INSTANT_XML_PATH"));
4132                 }
4133         }
4134
4135         if (!node) {
4136                 node = new XMLNode (X_("Editor"));
4137         }
4138
4139         return node;
4140 }
4141
4142 XMLNode*
4143 ARDOUR_UI::keyboard_settings () const
4144 {
4145         XMLNode* node = 0;
4146
4147         node = Config->extra_xml(X_("Keyboard"));
4148
4149         if (!node) {
4150                 node = new XMLNode (X_("Keyboard"));
4151         }
4152
4153         return node;
4154 }
4155
4156 void
4157 ARDOUR_UI::create_xrun_marker (framepos_t where)
4158 {
4159         if (_session) {
4160                 Location *location = new Location (*_session, where, where, _("xrun"), Location::IsMark);
4161                 _session->locations()->add (location);
4162         }
4163 }
4164
4165 void
4166 ARDOUR_UI::halt_on_xrun_message ()
4167 {
4168         cerr << "HALT on xrun\n";
4169         MessageDialog msg (*editor, _("Recording was stopped because your system could not keep up."));
4170         msg.run ();
4171 }
4172
4173 void
4174 ARDOUR_UI::xrun_handler (framepos_t where)
4175 {
4176         if (!_session) {
4177                 return;
4178         }
4179
4180         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::xrun_handler, where)
4181
4182         if (_session && Config->get_create_xrun_marker() && _session->actively_recording()) {
4183                 create_xrun_marker(where);
4184         }
4185
4186         if (_session && Config->get_stop_recording_on_xrun() && _session->actively_recording()) {
4187                 halt_on_xrun_message ();
4188         }
4189 }
4190
4191 void
4192 ARDOUR_UI::disk_overrun_handler ()
4193 {
4194         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_overrun_handler)
4195
4196         if (!have_disk_speed_dialog_displayed) {
4197                 have_disk_speed_dialog_displayed = true;
4198                 MessageDialog* msg = new MessageDialog (*editor, string_compose (_("\
4199 The disk system on your computer\n\
4200 was not able to keep up with %1.\n\
4201 \n\
4202 Specifically, it failed to write data to disk\n\
4203 quickly enough to keep up with recording.\n"), PROGRAM_NAME));
4204                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
4205                 msg->show ();
4206         }
4207 }
4208
4209
4210 /* TODO: this is getting elaborate enough to warrant being split into a dedicated class */
4211 static MessageDialog *scan_dlg = NULL;
4212 static ProgressBar   *scan_pbar = NULL;
4213 static HBox          *scan_tbox = NULL;
4214
4215 void
4216 ARDOUR_UI::cancel_plugin_scan ()
4217 {
4218         PluginManager::instance().cancel_plugin_scan();
4219 }
4220
4221 void
4222 ARDOUR_UI::cancel_plugin_timeout ()
4223 {
4224         PluginManager::instance().cancel_plugin_timeout();
4225         scan_tbox->hide();
4226 }
4227
4228 void
4229 ARDOUR_UI::plugin_scan_timeout (int timeout)
4230 {
4231         if (!scan_dlg || !scan_dlg->is_mapped() || !scan_pbar) {
4232                 return;
4233         }
4234         if (timeout > 0) {
4235                 scan_pbar->set_fraction ((float) timeout / (float) Config->get_vst_scan_timeout());
4236                 scan_tbox->show();
4237         } else {
4238                 scan_tbox->hide();
4239         }
4240         gui_idle_handler();
4241 }
4242
4243 void
4244 ARDOUR_UI::plugin_scan_dialog (std::string type, std::string plugin, bool can_cancel)
4245 {
4246         if (type == X_("closeme") && !(scan_dlg && scan_dlg->is_mapped())) {
4247                 return;
4248         }
4249
4250         const bool cancelled = PluginManager::instance().cancelled();
4251         if (type != X_("closeme") && !ui_config->get_show_plugin_scan_window()) {
4252                 if (cancelled && scan_dlg->is_mapped()) {
4253                         scan_dlg->hide();
4254                         gui_idle_handler();
4255                         return;
4256                 }
4257                 if (cancelled || !can_cancel) {
4258                         return;
4259                 }
4260         }
4261
4262         static Gtk::Button *cancel_button;
4263         static Gtk::Button *timeout_button;
4264         if (!scan_dlg) {
4265                 scan_dlg = new MessageDialog("", false, MESSAGE_INFO, BUTTONS_NONE); // TODO manage
4266                 VBox* vbox = scan_dlg->get_vbox();
4267                 vbox->set_size_request(400,-1);
4268                 scan_dlg->set_title (_("Scanning for plugins"));
4269
4270                 cancel_button = manage(new Gtk::Button(_("Cancel plugin scan")));
4271                 cancel_button->set_name ("EditorGTKButton");
4272                 cancel_button->signal_clicked().connect ( mem_fun (*this, &ARDOUR_UI::cancel_plugin_scan) );
4273                 cancel_button->show();
4274
4275                 scan_dlg->get_vbox()->pack_start ( *cancel_button, PACK_SHRINK);
4276
4277                 scan_tbox = manage( new HBox() );
4278
4279                 timeout_button = manage(new Gtk::Button(_("Stop Timeout")));
4280                 timeout_button->set_name ("EditorGTKButton");
4281                 timeout_button->signal_clicked().connect ( mem_fun (*this, &ARDOUR_UI::cancel_plugin_timeout) );
4282                 timeout_button->show();
4283
4284                 scan_pbar = manage(new ProgressBar());
4285                 scan_pbar->set_orientation(Gtk::PROGRESS_RIGHT_TO_LEFT);
4286                 scan_pbar->set_text(_("Scan Timeout"));
4287                 scan_pbar->show();
4288
4289                 scan_tbox->pack_start (*scan_pbar, PACK_EXPAND_WIDGET, 4);
4290                 scan_tbox->pack_start (*timeout_button, PACK_SHRINK, 4);
4291
4292                 scan_dlg->get_vbox()->pack_start (*scan_tbox, PACK_SHRINK, 4);
4293         }
4294
4295         assert(scan_dlg && scan_tbox && cancel_button);
4296
4297         if (type == X_("closeme")) {
4298                 scan_dlg->hide();
4299         } else {
4300                 scan_dlg->set_message(type + ": " + Glib::path_get_basename(plugin));
4301                 scan_dlg->show();
4302         }
4303         if (!can_cancel || !cancelled) {
4304                 scan_tbox->hide();
4305         }
4306         cancel_button->set_sensitive(can_cancel && !cancelled);
4307
4308         gui_idle_handler();
4309 }
4310
4311 void
4312 ARDOUR_UI::gui_idle_handler ()
4313 {
4314         int timeout = 30;
4315         /* due to idle calls, gtk_events_pending() may always return true */
4316         while (gtk_events_pending() && --timeout) {
4317                 gtk_main_iteration ();
4318         }
4319 }
4320
4321 void
4322 ARDOUR_UI::disk_underrun_handler ()
4323 {
4324         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::disk_underrun_handler)
4325
4326         if (!have_disk_speed_dialog_displayed) {
4327                 have_disk_speed_dialog_displayed = true;
4328                 MessageDialog* msg = new MessageDialog (
4329                         *editor, string_compose (_("The disk system on your computer\n\
4330 was not able to keep up with %1.\n\
4331 \n\
4332 Specifically, it failed to read data from disk\n\
4333 quickly enough to keep up with playback.\n"), PROGRAM_NAME));
4334                 msg->signal_response().connect (sigc::bind (sigc::mem_fun (*this, &ARDOUR_UI::disk_speed_dialog_gone), msg));
4335                 msg->show ();
4336         }
4337 }
4338
4339 void
4340 ARDOUR_UI::disk_speed_dialog_gone (int /*ignored_response*/, MessageDialog* msg)
4341 {
4342         have_disk_speed_dialog_displayed = false;
4343         delete msg;
4344 }
4345
4346 void
4347 ARDOUR_UI::session_dialog (std::string msg)
4348 {
4349         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::session_dialog, msg)
4350
4351         MessageDialog* d;
4352
4353         if (editor) {
4354                 d = new MessageDialog (*editor, msg, false, MESSAGE_INFO, BUTTONS_OK, true);
4355         } else {
4356                 d = new MessageDialog (msg, false, MESSAGE_INFO, BUTTONS_OK, true);
4357         }
4358
4359         d->show_all ();
4360         d->run ();
4361         delete d;
4362 }
4363
4364 int
4365 ARDOUR_UI::pending_state_dialog ()
4366 {
4367         HBox* hbox = manage (new HBox());
4368         Image* image = manage (new Image (Stock::DIALOG_QUESTION, ICON_SIZE_DIALOG));
4369         ArdourDialog dialog (_("Crash Recovery"), true);
4370         Label  message (string_compose (_("\
4371 This session appears to have been in the\n\
4372 middle of recording when %1 or\n\
4373 the computer was shutdown.\n\
4374 \n\
4375 %1 can recover any captured audio for\n\
4376 you, or it can ignore it. Please decide\n\
4377 what you would like to do.\n"), PROGRAM_NAME));
4378         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
4379         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
4380         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
4381         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
4382         dialog.add_button (_("Ignore crash data"), RESPONSE_REJECT);
4383         dialog.add_button (_("Recover from crash"), RESPONSE_ACCEPT);
4384         dialog.set_default_response (RESPONSE_ACCEPT);
4385         dialog.set_position (WIN_POS_CENTER);
4386         message.show();
4387         image->show();
4388         hbox->show();
4389
4390         switch (dialog.run ()) {
4391         case RESPONSE_ACCEPT:
4392                 return 1;
4393         default:
4394                 return 0;
4395         }
4396 }
4397
4398 int
4399 ARDOUR_UI::sr_mismatch_dialog (framecnt_t desired, framecnt_t actual)
4400 {
4401         HBox* hbox = new HBox();
4402         Image* image = new Image (Stock::DIALOG_WARNING, ICON_SIZE_DIALOG);
4403         ArdourDialog dialog (_("Sample Rate Mismatch"), true);
4404         Label  message (string_compose (_("\
4405 This session was created with a sample rate of %1 Hz, but\n\
4406 %2 is currently running at %3 Hz.  If you load this session,\n\
4407 audio may be played at the wrong sample rate.\n"), desired, PROGRAM_NAME, actual));
4408
4409         image->set_alignment(ALIGN_CENTER, ALIGN_TOP);
4410         hbox->pack_start (*image, PACK_EXPAND_WIDGET, 12);
4411         hbox->pack_end (message, PACK_EXPAND_PADDING, 12);
4412         dialog.get_vbox()->pack_start(*hbox, PACK_EXPAND_PADDING, 6);
4413         dialog.add_button (_("Do not load session"), RESPONSE_REJECT);
4414         dialog.add_button (_("Load session anyway"), RESPONSE_ACCEPT);
4415         dialog.set_default_response (RESPONSE_ACCEPT);
4416         dialog.set_position (WIN_POS_CENTER);
4417         message.show();
4418         image->show();
4419         hbox->show();
4420
4421         switch (dialog.run()) {
4422         case RESPONSE_ACCEPT:
4423                 return 0;
4424         default:
4425                 break;
4426         }
4427
4428         return 1;
4429 }
4430
4431 int
4432 ARDOUR_UI::disconnect_from_engine ()
4433 {
4434         /* drop connection to AudioEngine::Halted so that we don't act
4435          *  as if the engine unexpectedly shut down
4436          */
4437
4438         halt_connection.disconnect ();
4439         
4440         if (AudioEngine::instance()->stop ()) {
4441                 MessageDialog msg (*editor, _("Could not disconnect from Audio/MIDI engine"));
4442                 msg.run ();
4443                 return -1;
4444         } else {
4445                 AudioEngine::instance()->Halted.connect_same_thread (halt_connection, boost::bind (&ARDOUR_UI::engine_halted, this, _1, false));
4446         }
4447         
4448         update_sample_rate (0);
4449         return 0;
4450 }
4451
4452 int
4453 ARDOUR_UI::reconnect_to_engine ()
4454 {
4455         if (AudioEngine::instance()->start ()) {
4456                 // TODO somehow make this the topmost window (above any dialogs currently visible)
4457                 if (editor) {
4458                         MessageDialog msg (*editor,  _("Could not reconnect to the Audio/MIDI engine"));
4459                         msg.run ();
4460                 } else {
4461                         MessageDialog msg (_("Could not reconnect to the Audio/MIDI engine"));
4462                         msg.run ();
4463                 }
4464                 return -1;
4465         }
4466         
4467         update_sample_rate (0);
4468         return 0;
4469 }
4470
4471 void
4472 ARDOUR_UI::use_config ()
4473 {
4474         XMLNode* node = Config->extra_xml (X_("TransportControllables"));
4475         if (node) {
4476                 set_transport_controllable_state (*node);
4477         }
4478 }
4479
4480 void
4481 ARDOUR_UI::update_transport_clocks (framepos_t pos)
4482 {
4483         if (ui_config->get_primary_clock_delta_edit_cursor()) {
4484                 primary_clock->set (pos, false, editor->get_preferred_edit_position (EDIT_IGNORE_PHEAD));
4485         } else {
4486                 primary_clock->set (pos);
4487         }
4488
4489         if (ui_config->get_secondary_clock_delta_edit_cursor()) {
4490                 secondary_clock->set (pos, false, editor->get_preferred_edit_position (EDIT_IGNORE_PHEAD));
4491         } else {
4492                 secondary_clock->set (pos);
4493         }
4494
4495         if (big_clock_window) {
4496                 big_clock->set (pos);
4497         }
4498         ARDOUR_UI::instance()->video_timeline->manual_seek_video_monitor(pos);
4499 }
4500
4501 void
4502 ARDOUR_UI::step_edit_status_change (bool yn)
4503 {
4504         // XXX should really store pre-step edit status of things
4505         // we make insensitive
4506
4507         if (yn) {
4508                 rec_button.set_active_state (Gtkmm2ext::ImplicitActive);
4509                 rec_button.set_sensitive (false);
4510         } else {
4511                 rec_button.unset_active_state ();;
4512                 rec_button.set_sensitive (true);
4513         }
4514 }
4515
4516 void
4517 ARDOUR_UI::record_state_changed ()
4518 {
4519         ENSURE_GUI_THREAD (*this, &ARDOUR_UI::record_state_changed);
4520
4521         if (!_session || !big_clock_window) {
4522                 /* why bother - the clock isn't visible */
4523                 return;
4524         }
4525
4526         if (_session->record_status () == Session::Recording && _session->have_rec_enabled_track ()) {
4527                 big_clock->set_active (true);
4528         } else {
4529                 big_clock->set_active (false);
4530         }
4531 }
4532
4533 bool
4534 ARDOUR_UI::first_idle ()
4535 {
4536         if (_session) {
4537                 _session->allow_auto_play (true);
4538         }
4539
4540         if (editor) {
4541                 editor->first_idle();
4542         }
4543
4544         Keyboard::set_can_save_keybindings (true);
4545         return false;
4546 }
4547
4548 void
4549 ARDOUR_UI::store_clock_modes ()
4550 {
4551         XMLNode* node = new XMLNode(X_("ClockModes"));
4552
4553         for (vector<AudioClock*>::iterator x = AudioClock::clocks.begin(); x != AudioClock::clocks.end(); ++x) {
4554                 XMLNode* child = new XMLNode (X_("Clock"));
4555                 
4556                 child->add_property (X_("name"), (*x)->name());
4557                 child->add_property (X_("mode"), enum_2_string ((*x)->mode()));
4558                 child->add_property (X_("on"), ((*x)->off() ? X_("no") : X_("yes")));
4559
4560                 node->add_child_nocopy (*child);
4561         }
4562
4563         _session->add_extra_xml (*node);
4564         _session->set_dirty ();
4565 }
4566
4567 ARDOUR_UI::TransportControllable::TransportControllable (std::string name, ARDOUR_UI& u, ToggleType tp)
4568         : Controllable (name), ui (u), type(tp)
4569 {
4570
4571 }
4572
4573 void
4574 ARDOUR_UI::TransportControllable::set_value (double val)
4575 {
4576         if (val < 0.5) {
4577                 /* do nothing: these are radio-style actions */
4578                 return;
4579         }
4580
4581         const char *action = 0;
4582
4583         switch (type) {
4584         case Roll:
4585                 action = X_("Roll");
4586                 break;
4587         case Stop:
4588                 action = X_("Stop");
4589                 break;
4590         case GotoStart:
4591                 action = X_("GotoStart");
4592                 break;
4593         case GotoEnd:
4594                 action = X_("GotoEnd");
4595                 break;
4596         case AutoLoop:
4597                 action = X_("Loop");
4598                 break;
4599         case PlaySelection:
4600                 action = X_("PlaySelection");
4601                 break;
4602         case RecordEnable:
4603                 action = X_("Record");
4604                 break;
4605         default:
4606                 break;
4607         }
4608
4609         if (action == 0) {
4610                 return;
4611         }
4612
4613         Glib::RefPtr<Action> act = ActionManager::get_action ("Transport", action);
4614
4615         if (act) {
4616                 act->activate ();
4617         }
4618 }
4619
4620 double
4621 ARDOUR_UI::TransportControllable::get_value (void) const
4622 {
4623         float val = 0.0;
4624
4625         switch (type) {
4626         case Roll:
4627                 break;
4628         case Stop:
4629                 break;
4630         case GotoStart:
4631                 break;
4632         case GotoEnd:
4633                 break;
4634         case AutoLoop:
4635                 break;
4636         case PlaySelection:
4637                 break;
4638         case RecordEnable:
4639                 break;
4640         default:
4641                 break;
4642         }
4643
4644         return val;
4645 }
4646
4647 void
4648 ARDOUR_UI::setup_profile ()
4649 {
4650         if (gdk_screen_width() < 1200 || getenv ("ARDOUR_NARROW_SCREEN")) {
4651                 Profile->set_small_screen ();
4652         }
4653
4654         if (g_getenv ("ARDOUR_SAE")) {
4655                 Profile->set_sae ();
4656                 Profile->set_single_package ();
4657         }
4658
4659         if (g_getenv ("TRX")) {
4660                 Profile->set_trx ();
4661         }
4662
4663         if (g_getenv ("MIXBUS")) {
4664                 Profile->set_mixbus ();
4665         }
4666 }
4667
4668 int
4669 ARDOUR_UI::missing_file (Session*s, std::string str, DataType type)
4670 {
4671         MissingFileDialog dialog (s, str, type);
4672
4673         dialog.show ();
4674         dialog.present ();
4675
4676         int result = dialog.run ();
4677         dialog.hide ();
4678
4679         switch (result) {
4680         case RESPONSE_OK:
4681                 break;
4682         default:
4683                 return 1; // quit entire session load
4684         }
4685
4686         result = dialog.get_action ();
4687
4688         return result;
4689 }
4690
4691 int
4692 ARDOUR_UI::ambiguous_file (std::string file, std::vector<std::string> hits)
4693 {
4694         AmbiguousFileDialog dialog (file, hits);
4695
4696         dialog.show ();
4697         dialog.present ();
4698
4699         dialog.run ();
4700         return dialog.get_which ();
4701 }
4702
4703 /** Allocate our thread-local buffers */
4704 void
4705 ARDOUR_UI::get_process_buffers ()
4706 {
4707         _process_thread->get_buffers ();
4708 }
4709
4710 /** Drop our thread-local buffers */
4711 void
4712 ARDOUR_UI::drop_process_buffers ()
4713 {
4714         _process_thread->drop_buffers ();
4715 }
4716
4717 void
4718 ARDOUR_UI::feedback_detected ()
4719 {
4720         _feedback_exists = true;
4721 }
4722
4723 void
4724 ARDOUR_UI::successful_graph_sort ()
4725 {
4726         _feedback_exists = false;
4727 }
4728
4729 void
4730 ARDOUR_UI::midi_panic ()
4731 {
4732         if (_session) {
4733                 _session->midi_panic();
4734         }
4735 }
4736
4737 void
4738 ARDOUR_UI::session_format_mismatch (std::string xml_path, std::string backup_path)
4739 {
4740         const char* start_big = "<span size=\"x-large\" weight=\"bold\">";
4741         const char* end_big = "</span>";
4742         const char* start_mono = "<tt>";
4743         const char* end_mono = "</tt>";
4744
4745         MessageDialog msg (string_compose (_("%4This is a session from an older version of %3%5\n\n"
4746                                              "%3 has copied the old session file\n\n%6%1%7\n\nto\n\n%6%2%7\n\n"
4747                                              "From now on, use the -2000 version with older versions of %3"),
4748                                            xml_path, backup_path, PROGRAM_NAME,
4749                                            start_big, end_big,
4750                                            start_mono, end_mono), true);
4751
4752         msg.run ();
4753 }
4754
4755
4756 void
4757 ARDOUR_UI::reset_peak_display ()
4758 {
4759         if (!_session || !_session->master_out() || !editor_meter) return;
4760         editor_meter->clear_meters();
4761         editor_meter_max_peak = -INFINITY;
4762         editor_meter_peak_display.set_active_state ( Gtkmm2ext::Off );
4763 }
4764
4765 void
4766 ARDOUR_UI::reset_group_peak_display (RouteGroup* group)
4767 {
4768         if (!_session || !_session->master_out()) return;
4769         if (group == _session->master_out()->route_group()) {
4770                 reset_peak_display ();
4771         }
4772 }
4773
4774 void
4775 ARDOUR_UI::reset_route_peak_display (Route* route)
4776 {
4777         if (!_session || !_session->master_out()) return;
4778         if (_session->master_out().get() == route) {
4779                 reset_peak_display ();
4780         }
4781 }
4782
4783 int
4784 ARDOUR_UI::do_audio_midi_setup (uint32_t desired_sample_rate)
4785 {
4786         audio_midi_setup->set_desired_sample_rate (desired_sample_rate);
4787         audio_midi_setup->set_position (WIN_POS_CENTER);
4788
4789         switch (audio_midi_setup->run()) {
4790         case Gtk::RESPONSE_OK:
4791                 return 0;
4792         case Gtk::RESPONSE_APPLY:
4793                 return 0;
4794         default:
4795                 return -1;
4796         }
4797 }
4798
4799
4800 gint
4801 ARDOUR_UI::transport_numpad_timeout ()
4802 {
4803         _numpad_locate_happening = false;
4804         if (_numpad_timeout_connection.connected() )
4805                 _numpad_timeout_connection.disconnect();
4806         return 1;
4807 }
4808
4809 void
4810 ARDOUR_UI::transport_numpad_decimal ()
4811 {
4812         _numpad_timeout_connection.disconnect();
4813
4814         if (_numpad_locate_happening) {
4815                 if (editor) editor->goto_nth_marker(_pending_locate_num - 1);
4816                 _numpad_locate_happening = false;
4817         } else {
4818                 _pending_locate_num = 0;
4819                 _numpad_locate_happening = true;
4820                 _numpad_timeout_connection = Glib::signal_timeout().connect (mem_fun(*this, &ARDOUR_UI::transport_numpad_timeout), 2*1000);
4821         }
4822 }
4823
4824 void
4825 ARDOUR_UI::transport_numpad_event (int num)
4826 {
4827         if ( _numpad_locate_happening ) {
4828                 _pending_locate_num = _pending_locate_num*10 + num;
4829         } else {
4830                 switch (num) {          
4831                         case 0:  toggle_roll(false, false);             break;
4832                         case 1:  transport_rewind(1);                           break;
4833                         case 2:  transport_forward(1);                          break;
4834                         case 3:  transport_record(true);                        break;
4835                         case 4:  toggle_session_auto_loop();            break;
4836                         case 5:  transport_record(false); toggle_session_auto_loop();   break;
4837                         case 6:  toggle_punch();                                        break;
4838                         case 7:  toggle_click();                                break;
4839                         case 8:  toggle_auto_return();                  break;
4840                         case 9:  toggle_follow_edits();         break;
4841                 }
4842         }
4843 }
4844
4845 void
4846 ARDOUR_UI::set_flat_buttons ()
4847 {
4848         CairoWidget::set_flat_buttons( config()->get_flat_buttons() );
4849 }
4850
4851 void
4852 ARDOUR_UI::audioengine_became_silent ()
4853 {
4854         MessageDialog msg (string_compose (_("This is a free/demo copy of %1. It has just switched to silent mode."), PROGRAM_NAME),
4855                            true,
4856                            Gtk::MESSAGE_WARNING,
4857                            Gtk::BUTTONS_NONE,
4858                            true);
4859
4860         msg.set_title (string_compose (_("%1 is now silent"), PROGRAM_NAME));
4861
4862         Gtk::Label pay_label (string_compose (_("Please consider paying for a copy of %1 - you can pay whatever you want."), PROGRAM_NAME));
4863         Gtk::Label subscribe_label (_("Better yet become a subscriber - subscriptions start at US$1 per month."));
4864         Gtk::Button pay_button (_("Pay for a copy (via the web)"));
4865         Gtk::Button subscribe_button (_("Become a subscriber (via the web)"));
4866         Gtk::HBox pay_button_box;
4867         Gtk::HBox subscribe_button_box;
4868
4869         pay_button_box.pack_start (pay_button, true, false);
4870         subscribe_button_box.pack_start (subscribe_button, true, false);
4871
4872         bool (*openuri)(const char*) = PBD::open_uri; /* this forces selection of the const char* variant of PBD::open_uri(), which we need to avoid ambiguity below */
4873         
4874         pay_button.signal_clicked().connect (sigc::hide_return (sigc::bind (sigc::ptr_fun (openuri), (const char*) "https://ardour.org/download")));
4875         subscribe_button.signal_clicked().connect (sigc::hide_return (sigc::bind (sigc::ptr_fun (openuri), (const char*) "https://community.ardour.org/s/subscribe")));
4876         
4877         msg.get_vbox()->pack_start (pay_label);
4878         msg.get_vbox()->pack_start (pay_button_box);
4879         msg.get_vbox()->pack_start (subscribe_label);
4880         msg.get_vbox()->pack_start (subscribe_button_box);
4881
4882         msg.get_vbox()->show_all ();
4883         
4884         msg.add_button (_("Remain silent"), Gtk::RESPONSE_CANCEL);
4885         msg.add_button (_("Save and quit"), Gtk::RESPONSE_NO);
4886         msg.add_button (_("Give me more time"), Gtk::RESPONSE_YES);
4887         
4888         int r = msg.run ();
4889
4890         switch (r) {
4891         case Gtk::RESPONSE_YES:
4892                 AudioEngine::instance()->reset_silence_countdown ();
4893                 break;
4894
4895         case Gtk::RESPONSE_NO:
4896                 /* save and quit */
4897                 save_state_canfail ("");
4898                 exit (0);
4899                 break;
4900
4901         case Gtk::RESPONSE_CANCEL:
4902         default:
4903                 /* don't reset, save session and exit */
4904                 break;
4905         }
4906 }
4907         
4908 void
4909 ARDOUR_UI::hide_application ()
4910 {
4911     Application::instance ()-> hide ();
4912 }