access: linsys: clear some warnings
[vlc.git] / bin / darwinvlc.m
blob826d60a5ae4048372123d6b7be507c7eac8e1546
1 /*****************************************************************************
2  * darwinvlc.m: OS X specific main executable for VLC media player
3  *****************************************************************************
4  * Copyright (C) 2013-2015 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Felix Paul Kühne <fkuehne at videolan dot org>
8  *          David Fuhrmann <dfuhrmann at videolan dot org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
25 #ifdef HAVE_CONFIG_H
26 # include "config.h"
27 #endif
29 #include <vlc/vlc.h>
30 #include <vlc_common.h>
31 #include <vlc_charset.h>
33 #include <stdlib.h>
34 #include <locale.h>
35 #include <signal.h>
36 #include <string.h>
38 #import <CoreFoundation/CoreFoundation.h>
39 #import <Cocoa/Cocoa.h>
41 #ifdef HAVE_BREAKPAD
42 #import <Breakpad/Breakpad.h>
43 #endif
46 /**
47  * Handler called when VLC asks to terminate the program.
48  */
49 static void vlc_terminate(void *data)
51     (void)data;
53     dispatch_async(dispatch_get_main_queue(), ^{
54         /*
55          * Stop the main loop. When using the CoreFoundation mainloop, simply
56          * CFRunLoopStop can be used.
57          *
58          * But this does not work when having an interface.
59          * In this case, [NSApp stop:nil] needs to be used, but the used flag is only
60          * evaluated at the end of main loop event processing. This is always true
61          * in the case of code inside a action method. But here, this is
62          * not true and thus we need to send an dummy event to make sure the stop
63          * flag is actually processed by the main loop.
64          */
65         if (NSApp == nil) {
66             CFRunLoopStop(CFRunLoopGetCurrent());
67         } else {
69             [NSApp stop:nil];
70             NSEvent* event = [NSEvent otherEventWithType:NSApplicationDefined
71                                                 location:NSMakePoint(0,0)
72                                            modifierFlags:0
73                                                timestamp:0.0
74                                             windowNumber:0
75                                                  context:nil
76                                                  subtype:0
77                                                    data1:0
78                                                    data2:0];
79             [NSApp postEvent:event atStart:YES];
80         }
82     });
85 #ifdef HAVE_BREAKPAD
86 BreakpadRef initBreakpad()
88     BreakpadRef bp = nil;
90     /* Create caches directory in case it does not exist */
91     NSFileManager *fileManager = [NSFileManager defaultManager];
92     NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
93     NSString *bundleName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
94     NSString *cacheAppPath = [cachePath stringByAppendingPathComponent:bundleName];
95     if (![fileManager fileExistsAtPath:cacheAppPath]) {
96         [fileManager createDirectoryAtPath:cacheAppPath withIntermediateDirectories:NO attributes:nil error:nil];
97     }
99     /* Get Info.plist config */
100     NSMutableDictionary *breakpad_config = [[[NSBundle mainBundle] infoDictionary] mutableCopy];
102     /* Use in-process reporting */
103     [breakpad_config setObject:[NSNumber numberWithBool:YES]
104                         forKey:@BREAKPAD_IN_PROCESS];
106     /* Set dump location */
107     [breakpad_config setObject:cacheAppPath
108                         forKey:@BREAKPAD_DUMP_DIRECTORY];
110     bp = BreakpadCreate(breakpad_config);
111     return bp;
113 #endif
115 /*****************************************************************************
116  * main: parse command line, start interface and spawn threads.
117  *****************************************************************************/
118 int main(int i_argc, const char *ppsz_argv[])
120     /* The so-called POSIX-compliant MacOS X reportedly processes SIGPIPE even
121      * if it is blocked in all thread.
122      * Note: this is NOT an excuse for not protecting against SIGPIPE. If
123      * LibVLC runs outside of VLC, we cannot rely on this code snippet. */
124     signal(SIGPIPE, SIG_IGN);
125     /* Restore SIGCHLD in case our parent process ignores it. */
126     signal(SIGCHLD, SIG_DFL);
128 #ifndef NDEBUG
129     /* Activate malloc checking routines to detect heap corruptions. */
130     setenv("MALLOC_CHECK_", "2", 1);
131 #endif
133 #ifdef TOP_BUILDDIR
134     setenv("VLC_PLUGIN_PATH", TOP_BUILDDIR"/modules", 1);
135     setenv("VLC_DATA_PATH", TOP_SRCDIR"/share", 1);
136 #endif
138 #ifndef ALLOW_RUN_AS_ROOT
139     if (geteuid() == 0)
140     {
141         fprintf(stderr, "VLC is not supposed to be run as root. Sorry.\n"
142         "If you need to use real-time priorities and/or privileged TCP ports\n"
143         "you can use %s-wrapper (make sure it is Set-UID root and\n"
144         "cannot be run by non-trusted users first).\n", ppsz_argv[0]);
145         return 1;
146     }
147 #endif
149     setlocale(LC_ALL, "");
151     if (isatty(STDERR_FILENO))
152         /* This message clutters error logs. It is printed only on a TTY.
153          * Fortunately, LibVLC prints version info with -vv anyway. */
154         fprintf(stderr, "VLC media player %s (revision %s)\n",
155                  libvlc_get_version(), libvlc_get_changeset());
157     sigset_t set;
159     sigemptyset(&set);
160     /*
161      * The darwin version of VLC used GCD to dequeue interesting signals.
162      * For this to work, those signals must be blocked.
163      *
164      * There are two advantages over traditional signal handlers:
165      *  - handling is done on a separate thread: no need to worry about async-safety,
166      *  - EINTR is not generated: other threads need not handle that error.
167      * That being said, some LibVLC programs do not use sigwait(). Therefore
168      * EINTR must still be handled cleanly, notably from poll() calls.
169      *
170      * Signals that request a clean shutdown.
171      * We have to handle SIGTERM cleanly because of daemon mode. */
172     sigaddset(&set, SIGINT);
173     sigaddset(&set, SIGTERM);
175     /* SIGPIPE can happen and would crash the process. On modern systems,
176      * the MSG_NOSIGNAL flag protects socket write operations against SIGPIPE.
177      * But we still need to block SIGPIPE when:
178      *  - writing to pipes,
179      *  - using write() instead of send() for code not specific to sockets.
180      * LibVLC code assumes that SIGPIPE is blocked. Other LibVLC applications
181      * shall block it (or handle it somehow) too.
182      */
183     sigaddset(&set, SIGPIPE);
185     /* SIGCHLD must be dequeued to clean up zombie child processes.
186      * Furthermore the handler must not be set to SIG_IGN (see above).
187      * We cannot pragmatically handle EINTR, short reads and short writes
188      * in every code paths (including underlying libraries). So we just
189      * block SIGCHLD in all threads, and dequeue it below. */
190     sigaddset(&set, SIGCHLD);
192     /* Block all these signals */
193     pthread_sigmask(SIG_SETMASK, &set, NULL);
195     /* Handle signals with GCD */
196     dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
197     dispatch_source_t sigIntSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGINT, 0, queue);
198     dispatch_source_t sigTermSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGTERM, 0, queue);
199     dispatch_source_t sigChldSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_SIGNAL, SIGCHLD, 0, queue);
201     if (!sigIntSource || !sigTermSource || !sigChldSource)
202         abort();
204     dispatch_source_set_event_handler(sigIntSource, ^{
205         vlc_terminate(nil);
206     });
207     dispatch_source_set_event_handler(sigTermSource, ^{
208         vlc_terminate(nil);
209     });
211     dispatch_source_set_event_handler(sigChldSource, ^{
212         int status;
213         while(waitpid(-1, &status, WNOHANG) > 0)
214             ;
215     });
217     dispatch_resume(sigIntSource);
218     dispatch_resume(sigTermSource);
219     dispatch_resume(sigChldSource);
222     /* Handle parameters */
223     const char *argv[i_argc + 2];
224     int argc = 0;
226     argv[argc++] = "--no-ignore-config";
227     argv[argc++] = "--media-library";
229     /* overwrite system language on Mac */
230     char *lang = NULL;
232     for (int i = 0; i < i_argc; i++) {
233         if (!strncmp(ppsz_argv[i], "--language", 10)) {
234             lang = strstr(ppsz_argv[i], "=");
235             ppsz_argv++, i_argc--;
236             continue;
237         }
238     }
239     if (lang && strncmp( lang, "auto", 4 )) {
240         char tmp[11];
241         snprintf(tmp, 11, "LANG%s", lang);
242         putenv(tmp);
243     }
245     if (!lang) {
246         CFStringRef language;
247         language = (CFStringRef)CFPreferencesCopyAppValue(CFSTR("language"),
248                                                           kCFPreferencesCurrentApplication);
249         if (language) {
250             lang = FromCFString(language, kCFStringEncodingUTF8);
251             if (strncmp( lang, "auto", 4 )) {
252                 char tmp[11];
253                 snprintf(tmp, 11, "LANG=%s", lang);
254                 putenv(tmp);
255             }
256             free(lang);
257             CFRelease(language);
258         }
259     }
261     ppsz_argv++; i_argc--; /* skip executable path */
263     /* When VLC.app is run by double clicking in Mac OS X < 10.9, the 2nd arg
264      * is the PSN - process serial number (a unique PID-ish thingie)
265      * still ok for real Darwin & when run from command line
266      * for example -psn_0_9306113 */
267     if (i_argc >= 1 && !strncmp(*ppsz_argv, "-psn" , 4))
268         ppsz_argv++, i_argc--;
270     memcpy (argv + argc, ppsz_argv, i_argc * sizeof(*argv));
271     argc += i_argc;
272     argv[argc] = NULL;
274     /* Initialize libvlc */
275     libvlc_instance_t *vlc = libvlc_new(argc, argv);
276     if (vlc == NULL)
277         return 1;
279     int ret = 1;
280     libvlc_set_exit_handler(vlc, vlc_terminate, NULL);
281     libvlc_set_app_id(vlc, "org.VideoLAN.VLC", PACKAGE_VERSION, PACKAGE_NAME);
282     libvlc_set_user_agent(vlc, "VLC media player", "VLC/"PACKAGE_VERSION);
284     libvlc_add_intf(vlc, "hotkeys,none");
286     if (libvlc_add_intf(vlc, NULL)) {
287         fprintf(stderr, "VLC cannot start any interface. Exiting.\n");
288         goto out;
289     }
290     libvlc_playlist_play(vlc);
292     /*
293      * Run the main loop. If the mac interface is not initialized, only the CoreFoundation
294      * runloop is used. Otherwise, [NSApp run] needs to be called, which setups more stuff
295      * before actually starting the loop.
296      */
297 #ifdef HAVE_BREAKPAD
298     BreakpadRef breakpad;
299     breakpad = initBreakpad();
300 #endif
301     @autoreleasepool {
302         if(NSApp == nil) {
303             CFRunLoopRun();
305         } else {
306             [NSApp run];
307         }
308     }
310     ret = 0;
311     /* Cleanup */
312 out:
313     dispatch_release(sigIntSource);
314     dispatch_release(sigTermSource);
315     dispatch_release(sigChldSource);
317     libvlc_release(vlc);
319 #ifdef HAVE_BREAKPAD
320     BreakpadRelease(breakpad);
321 #endif
323     return ret;