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