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