More fun with LinuxVSTs & threading
[ardour.git] / gtk2_ardour / main.cc
1 /*
2     Copyright (C) 2001-2012 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 #include <cstdlib>
21 #include <cerrno>
22 #include <vector>
23
24 #include <signal.h>
25 #include <locale.h>
26
27 #include <sigc++/bind.h>
28 #include <gtkmm/settings.h>
29
30 #ifdef HAVE_FFTW35F
31 #include <fftw3.h>
32 #endif
33
34 #include "pbd/error.h"
35 #include "pbd/file_utils.h"
36 #include "pbd/textreceiver.h"
37 #include "pbd/failed_constructor.h"
38 #include "pbd/pathexpand.h"
39 #include "pbd/pthread_utils.h"
40 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
41 #include "pbd/boost_debug.h"
42 #endif
43
44 #include "ardour/revision.h"
45 #include "ardour/ardour.h"
46 #include "ardour/audioengine.h"
47 #include "ardour/session_utils.h"
48 #include "ardour/filesystem_paths.h"
49
50 #include <gtkmm/main.h>
51 #include <gtkmm2ext/application.h>
52 #include <gtkmm2ext/popup.h>
53 #include <gtkmm2ext/utils.h>
54
55 #include "ardour_ui.h"
56 #include "ui_config.h"
57 #include "opts.h"
58 #include "enums.h"
59 #include "bundle_env.h"
60
61 #include "pbd/i18n.h"
62
63 #ifdef PLATFORM_WINDOWS
64 #include <fcntl.h> // Needed for '_fmode'
65 #include <shellapi.h> // console
66 #endif
67
68 #ifdef WAF_BUILD
69 #include "gtk2ardour-version.h"
70 #endif
71
72 #ifdef LXVST_SUPPORT
73 #include <gdk/gdkx.h>
74 #endif
75
76 using namespace std;
77 using namespace Gtk;
78 using namespace ARDOUR_COMMAND_LINE;
79 using namespace ARDOUR;
80 using namespace PBD;
81
82 TextReceiver text_receiver ("ardour");
83
84 extern int curvetest (string);
85
86 static ARDOUR_UI  *ui = 0;
87 static string localedir (LOCALEDIR);
88
89 void
90 gui_jack_error ()
91 {
92         MessageDialog win (string_compose (_("%1 could not connect to the audio backend."), PROGRAM_NAME),
93                            false,
94                            Gtk::MESSAGE_INFO,
95                            Gtk::BUTTONS_NONE);
96
97         win.add_button (Stock::QUIT, RESPONSE_CLOSE);
98         win.set_default_response (RESPONSE_CLOSE);
99
100         win.show_all ();
101         win.set_position (Gtk::WIN_POS_CENTER);
102
103         if (!no_splash) {
104                 ui->hide_splash ();
105         }
106
107         /* we just don't care about the result, but we want to block */
108
109         win.run ();
110 }
111
112 #ifndef NDEBUG
113 static void ardour_g_log (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) {
114         switch (log_level) {
115                 case G_LOG_FLAG_FATAL:
116                 case G_LOG_LEVEL_CRITICAL:
117                         fatal << "g_log: " << message << endmsg;
118                         break;
119                 case G_LOG_LEVEL_ERROR:
120                         error << "g_log: " << message << endmsg;
121                         break;
122                 case G_LOG_LEVEL_WARNING:
123                         warning << "g_log: " << message << endmsg;
124                         break;
125                 case G_LOG_LEVEL_MESSAGE:
126                 case G_LOG_LEVEL_INFO:
127                 default:
128                         info << "g_log: " << message << endmsg;
129                         break;
130         }
131 }
132 #endif
133
134 static gboolean
135 tell_about_backend_death (void* /* ignored */)
136 {
137         if (AudioEngine::instance()->processed_frames() == 0) {
138                 /* died during startup */
139                 MessageDialog msg (string_compose (_("The audio backend (%1) has failed, or terminated"), AudioEngine::instance()->current_backend_name()), false);
140                 msg.set_position (Gtk::WIN_POS_CENTER);
141                 msg.set_secondary_text (string_compose (_(
142 "%2 exited unexpectedly, and without notifying %1.\n\
143 \n\
144 This could be due to misconfiguration or to an error inside %2.\n\
145 \n\
146 Click OK to exit %1."), PROGRAM_NAME, AudioEngine::instance()->current_backend_name()));
147
148                 msg.run ();
149                 _exit (0);
150
151         } else {
152
153                 /* engine has already run, so this is a mid-session backend death */
154
155                 MessageDialog msg (string_compose (_("The audio backend (%1) has failed, or terminated"), AudioEngine::instance()->current_backend_name()), false);
156                 msg.set_secondary_text (string_compose (_("%2 exited unexpectedly, and without notifying %1."),
157                                                          PROGRAM_NAME, AudioEngine::instance()->current_backend_name()));
158                 msg.present ();
159         }
160         return false; /* do not call again */
161 }
162
163 #ifndef PLATFORM_WINDOWS
164 static void
165 sigpipe_handler (int /*signal*/)
166 {
167         /* XXX fix this so that we do this again after a reconnect to the backend */
168
169         static bool done_the_backend_thing = false;
170
171         if (!done_the_backend_thing) {
172                 AudioEngine::instance()->died ();
173                 g_idle_add (tell_about_backend_death, 0);
174                 done_the_backend_thing =  true;
175         }
176 }
177 #endif
178
179 #if (!defined COMPILER_MSVC && defined PLATFORM_WINDOWS)
180
181 static FILE* pStdOut = 0;
182 static FILE* pStdErr = 0;
183 static BOOL  bConsole;
184 static HANDLE hStdOut;
185
186 static bool
187 IsAConsolePort (HANDLE handle)
188 {
189         DWORD mode;
190         return (GetConsoleMode(handle, &mode) != 0);
191 }
192
193 static void
194 console_madness_begin ()
195 {
196         bConsole = AttachConsole(ATTACH_PARENT_PROCESS);
197         hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
198
199         /* re-attach to the console so we can see 'printf()' output etc.
200          * for MSVC see  gtk2_ardour/msvc/winmain.cc
201          */
202
203         if ((bConsole) && (IsAConsolePort(hStdOut))) {
204                 pStdOut = freopen( "CONOUT$", "w", stdout );
205                 pStdErr = freopen( "CONOUT$", "w", stderr );
206         }
207 }
208
209 static void
210 console_madness_end ()
211 {
212         if (pStdOut) {
213                 fclose (pStdOut);
214         }
215         if (pStdErr) {
216                 fclose (pStdErr);
217         }
218
219         if (bConsole) {
220                 // Detach and free the console from our application
221                 INPUT_RECORD input_record;
222
223                 input_record.EventType = KEY_EVENT;
224                 input_record.Event.KeyEvent.bKeyDown = TRUE;
225                 input_record.Event.KeyEvent.dwControlKeyState = 0;
226                 input_record.Event.KeyEvent.uChar.UnicodeChar = VK_RETURN;
227                 input_record.Event.KeyEvent.wRepeatCount      = 1;
228                 input_record.Event.KeyEvent.wVirtualKeyCode   = VK_RETURN;
229                 input_record.Event.KeyEvent.wVirtualScanCode  = MapVirtualKey( VK_RETURN, 0 );
230
231                 DWORD written = 0;
232                 WriteConsoleInput( GetStdHandle( STD_INPUT_HANDLE ), &input_record, 1, &written );
233
234                 FreeConsole();
235         }
236 }
237
238 static void command_line_parse_error (int *argc, char** argv[]) {}
239
240 #elif (defined(COMPILER_MSVC) && defined(NDEBUG) && !defined(RDC_BUILD))
241
242 // these are not used here. for MSVC see  gtk2_ardour/msvc/winmain.cc
243 static void console_madness_begin () {}
244 static void console_madness_end () {}
245
246 static void command_line_parse_error (int *argc, char** argv[]) {
247         // Since we don't ordinarily have access to stdout and stderr with
248         // an MSVC app, let the user know we encountered a parsing error.
249         Gtk::Main app(argc, argv); // Calls 'gtk_init()'
250
251         Gtk::MessageDialog dlgReportParseError (string_compose (_("\n   %1 could not understand your command line      "), PROGRAM_NAME),
252                         false, MESSAGE_ERROR, BUTTONS_CLOSE, true);
253         dlgReportParseError.set_title (string_compose (_("An error was encountered while launching %1"), PROGRAM_NAME));
254         dlgReportParseError.run ();
255 }
256
257 #else
258 static void console_madness_begin () {}
259 static void console_madness_end () {}
260 static void command_line_parse_error (int *argc, char** argv[]) {}
261 #endif
262
263 #if (defined(COMPILER_MSVC) && defined(NDEBUG) && !defined(RDC_BUILD))
264 /*
265  *  Release build with MSVC uses ardour_main()
266  */
267 int ardour_main (int argc, char *argv[])
268
269 #elif (defined WINDOWS_VST_SUPPORT && !defined PLATFORM_WINDOWS)
270
271 // prototype for function in windows_vst_plugin_ui.cc
272 extern int windows_vst_gui_init (int* argc, char** argv[]);
273
274 /* this is called from the entry point of a wine-compiled
275    executable that is linked against gtk2_ardour built
276    as a shared library.
277 */
278 extern "C" {
279
280 int ardour_main (int argc, char *argv[])
281
282 #elif defined NOMAIN
283 int nomain (int argc, char *argv[])
284 #else
285 int main (int argc, char *argv[])
286 #endif
287 {
288         ARDOUR::check_for_old_configuration_files();
289
290         fixup_bundle_environment (argc, argv, localedir);
291
292         load_custom_fonts(); /* needs to happen before any gtk and pango init calls */
293
294         if (!Glib::thread_supported()) {
295                 Glib::thread_init();
296         }
297
298 #ifdef LXVST_SUPPORT
299         XInitThreads ();
300 #endif
301
302 #ifdef HAVE_FFTW35F
303         fftwf_make_planner_thread_safe ();
304 #endif
305
306 #ifdef ENABLE_NLS
307         /* initialize C and C++ locales to user preference */
308         char* l_msg = NULL;
309         char* l_num = NULL;
310         if (ARDOUR::translations_are_enabled ()) {
311                 setlocale (LC_ALL, "");
312                 try {
313                         std::locale::global (std::locale (setlocale (LC_ALL, 0)));
314                 } catch (...) {
315                         std::cerr << "Cannot set C++ locale\n";
316                 }
317 #ifndef COMPILER_MSVC
318                 // LC_MESSAGES isn't a supported locale setting when building
319                 // with MSVC (in fact, I doubt if it's valid for Windows at all)
320                 l_msg = setlocale (LC_MESSAGES, NULL);
321 #endif
322                 l_num = setlocale (LC_NUMERIC, NULL);
323                 if (l_msg) { l_msg = strdup (l_msg); }
324                 if (l_num) { l_num = strdup (l_num); }
325         }
326 #endif
327
328         console_madness_begin();
329
330 #if (defined WINDOWS_VST_SUPPORT && !defined PLATFORM_WINDOWS)
331         /* this does some magic that is needed to make GTK and X11 client interact properly.
332          * the platform dependent code is in windows_vst_plugin_ui.cc
333          */
334         windows_vst_gui_init (&argc, &argv);
335 #endif
336
337 #ifdef ENABLE_NLS
338         cerr << "bind txt domain [" << PACKAGE << "] to " << localedir << endl;
339
340         (void) bindtextdomain (PACKAGE, localedir.c_str());
341         /* our i18n translations are all in UTF-8, so make sure
342            that even if the user locale doesn't specify UTF-8,
343            we use that when handling them.
344         */
345         (void) bind_textdomain_codeset (PACKAGE,"UTF-8");
346 #endif
347
348         pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, 0);
349
350         // catch error message system signals ();
351
352         text_receiver.listen_to (error);
353         text_receiver.listen_to (info);
354         text_receiver.listen_to (fatal);
355         text_receiver.listen_to (warning);
356
357 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
358         if (g_getenv ("BOOST_DEBUG")) {
359                 boost_debug_shared_ptr_show_live_debugging (true);
360         }
361 #endif
362
363         if (parse_opts (argc, argv)) {
364                 command_line_parse_error (&argc, &argv);
365                 exit (1);
366         }
367
368         cout << PROGRAM_NAME
369              << VERSIONSTRING
370              << _(" (built using ")
371              << revision
372 #ifdef __GNUC__
373              << _(" and GCC version ") << __VERSION__
374 #endif
375              << ')'
376              << endl;
377
378         if (just_version) {
379                 exit (0);
380         }
381
382         if (no_splash) {
383                 cerr << _("Copyright (C) 1999-2015 Paul Davis") << endl
384                      << _("Some portions Copyright (C) Steve Harris, Ari Johnson, Brett Viren, Joel Baker, Robin Gareus") << endl
385                      << endl
386                      << string_compose (_("%1 comes with ABSOLUTELY NO WARRANTY"), PROGRAM_NAME) << endl
387                      << _("not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.") << endl
388                      << _("This is free software, and you are welcome to redistribute it ") << endl
389                      << _("under certain conditions; see the source for copying conditions.")
390                      << endl;
391         }
392
393         if (!ARDOUR::init (ARDOUR_COMMAND_LINE::use_vst, ARDOUR_COMMAND_LINE::try_hw_optimization, localedir.c_str())) {
394                 error << string_compose (_("could not initialize %1."), PROGRAM_NAME) << endmsg;
395                 exit (1);
396         }
397
398         if (curvetest_file) {
399                 return curvetest (curvetest_file);
400         }
401
402 #ifdef ENABLE_NLS
403         ARDOUR::LocaleMode locale_mode = UIConfiguration::instance().get_locale_mode ();
404         if (l_msg && l_num && locale_mode != ARDOUR::SET_LC_ALL) {
405                 try {
406                         std::locale cpp_locale (std::locale::classic ());
407                         cpp_locale = std::locale (cpp_locale, l_msg, std::locale::messages);
408                         if (ARDOUR::SET_LC_MESSAGES_AND_LC_NUMERIC == locale_mode) {
409                                 cpp_locale = std::locale (cpp_locale, l_num, std::locale::numeric);
410                         }
411                         std::locale::global (cpp_locale);
412                 } catch (...) {
413                         std::cerr << "Cannot override C++ locale\n";
414                 }
415                 info << "LC_ALL: " << setlocale (LC_ALL, NULL) << endmsg;
416         }
417         free (l_msg);
418         free (l_num);
419 #endif
420
421 #ifndef PLATFORM_WINDOWS
422         if (::signal (SIGPIPE, sigpipe_handler)) {
423                 cerr << _("Cannot xinstall SIGPIPE error handler") << endl;
424         }
425 #endif
426
427         DEBUG_TRACE (DEBUG::Locale, string_compose ("main() locale '%1'\n", setlocale (LC_NUMERIC, NULL)));
428
429         if (UIConfiguration::instance().pre_gui_init ()) {
430                 error << _("Could not complete pre-GUI initialization") << endmsg;
431                 exit (1);
432         }
433
434         try {
435                 ui = new ARDOUR_UI (&argc, &argv, localedir.c_str());
436         } catch (failed_constructor& err) {
437                 error << string_compose (_("could not create %1 GUI"), PROGRAM_NAME) << endmsg;
438                 exit (1);
439         }
440
441 #ifndef NDEBUG
442         g_log_set_handler (NULL,
443                         GLogLevelFlags (G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL |  G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_RECURSION),
444                         &ardour_g_log, NULL);
445 #endif
446
447         ui->run (text_receiver);
448         Gtkmm2ext::Application::instance()->cleanup();
449         delete ui;
450         ui = 0;
451
452         ARDOUR::cleanup ();
453 #ifndef NDEBUG
454         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
455                 Glib::usleep(100000);
456                 sched_yield();
457         }
458 #endif
459
460         pthread_cancel_all ();
461
462 #ifndef NDEBUG
463         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
464                 Glib::usleep(100000);
465                 sched_yield();
466         }
467 #endif
468
469         console_madness_end ();
470
471         return 0;
472 }
473 #if (defined WINDOWS_VST_SUPPORT && !defined PLATFORM_WINDOWS)
474 } // end of extern "C" block
475 #endif