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