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