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