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