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