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