Add support for more than 2 audio channels.
[wine] / dlls / x11drv / x11drv_main.c
1 /*
2  * X11DRV initialization code
3  *
4  * Copyright 1998 Patrik Stridvall
5  * Copyright 2000 Alexandre Julliard
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23
24 #include <fcntl.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #ifdef HAVE_SYS_TIME_H
30 # include <sys/time.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
35 #include <X11/cursorfont.h>
36 #include <X11/Xlib.h>
37 #ifdef HAVE_XKB
38 #include <X11/XKBlib.h>
39 #endif
40
41 #include "windef.h"
42 #include "winbase.h"
43 #include "wine/winbase16.h"
44 #include "winreg.h"
45
46 #include "x11drv.h"
47 #include "xvidmode.h"
48 #include "xrandr.h"
49 #include "dga2.h"
50 #include "wine/server.h"
51 #include "wine/debug.h"
52
53 WINE_DEFAULT_DEBUG_CHANNEL(x11drv);
54
55 static CRITICAL_SECTION X11DRV_CritSection;
56 static CRITICAL_SECTION_DEBUG critsect_debug =
57 {
58     0, 0, &X11DRV_CritSection,
59     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
60       0, 0, { 0, (DWORD)(__FILE__ ": X11DRV_CritSection") }
61 };
62 static CRITICAL_SECTION X11DRV_CritSection = { &critsect_debug, -1, 0, 0, 0, 0 };
63
64 Screen *screen;
65 Visual *visual;
66 unsigned int screen_width;
67 unsigned int screen_height;
68 unsigned int screen_depth;
69 Window root_window;
70 DWORD desktop_tid = 0;
71 int dxgrab = 0;
72 int usedga = 0;
73 int usexvidmode = 0;
74 int usexrandr = 1;
75 int use_xkb = 1;
76 int use_take_focus = 1;
77 int use_primary_selection = 0;
78 int managed_mode = 1;
79 int client_side_with_core = 1;
80 int client_side_with_render = 1;
81 int client_side_antialias_with_core = 1;
82 int client_side_antialias_with_render = 1;
83 int using_wine_desktop = 0;
84
85 static BOOL synchronous;  /* run in synchronous mode? */
86 static BOOL desktop_dbl_buf = TRUE;
87 static char *desktop_geometry;
88 static XVisualInfo *desktop_vi;
89
90 static x11drv_error_callback err_callback;   /* current callback for error */
91 static Display *err_callback_display;        /* display callback is set for */
92 static void *err_callback_arg;               /* error callback argument */
93 static int err_callback_result;              /* error callback result */
94 static unsigned long err_serial;             /* serial number of first request */
95 static int (*old_error_handler)( Display *, XErrorEvent * );
96 static int use_xim = 1;
97 static char input_style[20];
98
99 #define IS_OPTION_TRUE(ch) \
100     ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
101 #define IS_OPTION_FALSE(ch) \
102     ((ch) == 'n' || (ch) == 'N' || (ch) == 'f' || (ch) == 'F' || (ch) == '0')
103
104 /***********************************************************************
105  *              ignore_error
106  *
107  * Check if the X error is one we can ignore.
108  */
109 static inline BOOL ignore_error( Display *display, XErrorEvent *event )
110 {
111     if (event->request_code == X_SetInputFocus && event->error_code == BadMatch) return TRUE;
112     return FALSE;
113 }
114
115
116 /***********************************************************************
117  *              X11DRV_expect_error
118  *
119  * Setup a callback function that will be called on an X error.  The
120  * callback must return non-zero if the error is the one it expected.
121  * This function acquires the x11 lock; X11DRV_check_error must be
122  * called in all cases to release it.
123  */
124 void X11DRV_expect_error( Display *display, x11drv_error_callback callback, void *arg )
125 {
126     wine_tsx11_lock();
127     err_callback         = callback;
128     err_callback_display = display;
129     err_callback_arg     = arg;
130     err_callback_result  = 0;
131     err_serial           = NextRequest(display);
132 }
133
134
135 /***********************************************************************
136  *              X11DRV_check_error
137  *
138  * Check if an expected X11 error occurred; return non-zero if yes.
139  * Also release the x11 lock obtained in X11DRV_expect_error.
140  * The caller is responsible for calling XSync first if necessary.
141  */
142 int X11DRV_check_error(void)
143 {
144     int ret;
145     err_callback = NULL;
146     ret = err_callback_result;
147     wine_tsx11_unlock();
148     return ret;
149 }
150
151
152 /***********************************************************************
153  *              error_handler
154  */
155 static int error_handler( Display *display, XErrorEvent *error_evt )
156 {
157     if (err_callback && display == err_callback_display &&
158         (long)(error_evt->serial - err_serial) >= 0)
159     {
160         if ((err_callback_result = err_callback( display, error_evt, err_callback_arg )))
161         {
162             TRACE( "got expected error %d req %d\n",
163                    error_evt->error_code, error_evt->request_code );
164             return 0;
165         }
166     }
167     if (ignore_error( display, error_evt ))
168     {
169         TRACE( "got ignored error %d req %d\n",
170                error_evt->error_code, error_evt->request_code );
171         return 0;
172     }
173     if (synchronous)
174     {
175         ERR( "X protocol error: serial=%ld, request_code=%d - breaking into debugger\n",
176              error_evt->serial, error_evt->request_code );
177         DebugBreak();  /* force an entry in the debugger */
178     }
179     old_error_handler( display, error_evt );
180     return 0;
181 }
182
183 /***********************************************************************
184  *              wine_tsx11_lock   (X11DRV.@)
185  */
186 void wine_tsx11_lock(void)
187 {
188     EnterCriticalSection( &X11DRV_CritSection );
189 }
190
191 /***********************************************************************
192  *              wine_tsx11_unlock   (X11DRV.@)
193  */
194 void wine_tsx11_unlock(void)
195 {
196     LeaveCriticalSection( &X11DRV_CritSection );
197 }
198
199
200 /***********************************************************************
201  *              get_config_key
202  *
203  * Get a config key from either the app-specific or the default config
204  */
205 inline static DWORD get_config_key( HKEY defkey, HKEY appkey, const char *name,
206                                     char *buffer, DWORD size )
207 {
208     if (appkey && !RegQueryValueExA( appkey, name, 0, NULL, buffer, &size )) return 0;
209     return RegQueryValueExA( defkey, name, 0, NULL, buffer, &size );
210 }
211
212
213 /***********************************************************************
214  *              setup_options
215  *
216  * Setup the x11drv options.
217  */
218 static void setup_options(void)
219 {
220     char buffer[MAX_PATH+16];
221     HKEY hkey, appkey = 0;
222     DWORD len;
223
224     if (RegCreateKeyExA( HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\x11drv", 0, NULL,
225                          REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &hkey, NULL ))
226     {
227         ERR("Cannot create config registry key\n" );
228         ExitProcess(1);
229     }
230
231     /* open the app-specific key */
232
233     len = (GetModuleFileNameA( 0, buffer, MAX_PATH ));
234     if (len && len < MAX_PATH)
235     {
236         HKEY tmpkey;
237         char *p, *appname = buffer;
238         if ((p = strrchr( appname, '/' ))) appname = p + 1;
239         if ((p = strrchr( appname, '\\' ))) appname = p + 1;
240         strcat( appname, "\\x11drv" );
241         if (!RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\AppDefaults", &tmpkey ))
242         {
243             if (RegOpenKeyA( tmpkey, appname, &appkey )) appkey = 0;
244             RegCloseKey( tmpkey );
245         }
246     }
247
248     if (!get_config_key( hkey, appkey, "Desktop", buffer, sizeof(buffer) ))
249     {
250         /* Imperfect validation:  If Desktop=N, then we don't turn on
251         ** the --desktop option.  We should really validate for a correct
252         ** sizing entry */
253         if (!IS_OPTION_FALSE(buffer[0])) desktop_geometry = strdup(buffer);
254     }
255
256     if (!get_config_key( hkey, appkey, "Managed", buffer, sizeof(buffer) ))
257         managed_mode = IS_OPTION_TRUE( buffer[0] );
258
259     if (!get_config_key( hkey, appkey, "DXGrab", buffer, sizeof(buffer) ))
260         dxgrab = IS_OPTION_TRUE( buffer[0] );
261
262     if (!get_config_key( hkey, appkey, "UseDGA", buffer, sizeof(buffer) ))
263         usedga = IS_OPTION_TRUE( buffer[0] );
264
265     if (!get_config_key( hkey, appkey, "UseXVidMode", buffer, sizeof(buffer) ))
266         usexvidmode = IS_OPTION_TRUE( buffer[0] );
267
268     if (!get_config_key( hkey, appkey, "UseXRandR", buffer, sizeof(buffer) ))
269         usexrandr = IS_OPTION_TRUE( buffer[0] );
270
271     if (!get_config_key( hkey, appkey, "UseTakeFocus", buffer, sizeof(buffer) ))
272         use_take_focus = IS_OPTION_TRUE( buffer[0] );
273
274     if (!get_config_key( hkey, appkey, "UsePrimarySelection", buffer, sizeof(buffer) ))
275         use_primary_selection = IS_OPTION_TRUE( buffer[0] );
276
277     screen_depth = 0;
278     if (!get_config_key( hkey, appkey, "ScreenDepth", buffer, sizeof(buffer) ))
279         screen_depth = atoi(buffer);
280
281     if (!get_config_key( hkey, appkey, "Synchronous", buffer, sizeof(buffer) ))
282         synchronous = IS_OPTION_TRUE( buffer[0] );
283
284     if (!get_config_key( hkey, appkey, "ClientSideWithCore", buffer, sizeof(buffer) ))
285         client_side_with_core = IS_OPTION_TRUE( buffer[0] );
286
287     if (!get_config_key( hkey, appkey, "ClientSideWithRender", buffer, sizeof(buffer) ))
288         client_side_with_render = IS_OPTION_TRUE( buffer[0] );
289
290     if (!get_config_key( hkey, appkey, "ClientSideAntiAliasWithCore", buffer, sizeof(buffer) ))
291         client_side_antialias_with_core = IS_OPTION_TRUE( buffer[0] );
292
293     if (!get_config_key( hkey, appkey, "ClientSideAntiAliasWithRender", buffer, sizeof(buffer) ))
294         client_side_antialias_with_render = IS_OPTION_TRUE( buffer[0] );
295
296     if (!get_config_key( hkey, appkey, "DesktopDoubleBuffered", buffer, sizeof(buffer) ))
297         desktop_dbl_buf = IS_OPTION_TRUE( buffer[0] );
298
299     if (!get_config_key( hkey, appkey, "UseXIM", buffer, sizeof(buffer) ))
300         use_xim = IS_OPTION_TRUE( buffer[0] );
301
302     get_config_key( hkey, appkey, "InputStyle", input_style, sizeof(input_style) );
303
304     if (appkey) RegCloseKey( appkey );
305     RegCloseKey( hkey );
306 }
307
308
309 /***********************************************************************
310  *           X11DRV process initialisation routine
311  */
312 static BOOL process_attach(void)
313 {
314     Display *display;
315
316     setup_options();
317
318     /* Open display */
319
320     if (!(display = XOpenDisplay( NULL ))) return FALSE;
321
322     fcntl( ConnectionNumber(display), F_SETFD, 1 ); /* set close on exec flag */
323     screen = DefaultScreenOfDisplay( display );
324     visual = DefaultVisual( display, DefaultScreen(display) );
325     root_window = DefaultRootWindow( display );
326     old_error_handler = XSetErrorHandler( error_handler );
327
328     /* Initialize screen depth */
329
330     if (screen_depth)  /* depth specified */
331     {
332         int depth_count, i;
333         int *depth_list = XListDepths(display, DefaultScreen(display), &depth_count);
334         for (i = 0; i < depth_count; i++)
335             if (depth_list[i] == screen_depth) break;
336         XFree( depth_list );
337         if (i >= depth_count)
338         {
339             WARN( "invalid depth %d, using default\n", screen_depth );
340             screen_depth = 0;
341         }
342     }
343     if (!screen_depth) screen_depth = DefaultDepthOfScreen( screen );
344
345     /* Initialize OpenGL */
346     X11DRV_OpenGL_Init(display);
347
348     /* If OpenGL is available, change the default visual, etc as necessary */
349     if (desktop_dbl_buf && (desktop_vi = X11DRV_setup_opengl_visual( display )))
350     {
351         visual       = desktop_vi->visual;
352         screen       = ScreenOfDisplay(display, desktop_vi->screen);
353         screen_depth = desktop_vi->depth;
354     }
355
356     if (synchronous) XSynchronize( display, True );
357
358     screen_width  = WidthOfScreen( screen );
359     screen_height = HeightOfScreen( screen );
360
361     X11DRV_Settings_Init();
362
363     if (desktop_geometry)
364     {
365         root_window = X11DRV_create_desktop( desktop_vi, desktop_geometry );
366         using_wine_desktop = 1;
367     }
368
369     /* initialize GDI */
370     X11DRV_GDI_Initialize( display );
371
372 #ifdef HAVE_LIBXXF86VM
373     /* initialize XVidMode */
374     X11DRV_XF86VM_Init();
375 #endif
376 #ifdef HAVE_LIBXRANDR
377     /* initialize XRandR */
378     X11DRV_XRandR_Init();
379 #endif
380 #ifdef HAVE_LIBXXF86DGA2
381     /* initialize DGA2 */
382     X11DRV_XF86DGA2_Init();
383 #endif
384
385     X11DRV_InitKeyboard();
386
387     return TRUE;
388 }
389
390
391 /***********************************************************************
392  *           X11DRV thread termination routine
393  */
394 static void thread_detach(void)
395 {
396     struct x11drv_thread_data *data = NtCurrentTeb()->driver_data;
397
398     if (data)
399     {
400         CloseHandle( data->display_fd );
401         wine_tsx11_lock();
402         XCloseDisplay( data->display );
403         /* if (data->xim) XCloseIM( data->xim ); */ /* crashes Xlib */
404         wine_tsx11_unlock();
405         HeapFree( GetProcessHeap(), 0, data );
406     }
407 }
408
409
410 /***********************************************************************
411  *           X11DRV process termination routine
412  */
413 static void process_detach(void)
414 {
415 #ifdef HAVE_LIBXXF86DGA2
416     /* cleanup DGA2 */
417     X11DRV_XF86DGA2_Cleanup();
418 #endif
419 #ifdef HAVE_LIBXXF86VM
420     /* cleanup XVidMode */
421     X11DRV_XF86VM_Cleanup();
422 #endif
423     if(using_client_side_fonts)
424         X11DRV_XRender_Finalize();
425
426     /* cleanup GDI */
427     X11DRV_GDI_Finalize();
428
429     DeleteCriticalSection( &X11DRV_CritSection );
430 }
431
432
433 /***********************************************************************
434  *           X11DRV thread initialisation routine
435  */
436 struct x11drv_thread_data *x11drv_init_thread_data(void)
437 {
438     struct x11drv_thread_data *data;
439
440     if (!(data = HeapAlloc( GetProcessHeap(), 0, sizeof(*data) )))
441     {
442         ERR( "could not create data\n" );
443         ExitProcess(1);
444     }
445     wine_tsx11_lock();
446     if (!(data->display = XOpenDisplay(NULL)))
447     {
448         wine_tsx11_unlock();
449         MESSAGE( "x11drv: Can't open display: %s\n", XDisplayName(NULL) );
450         MESSAGE( "Please ensure that your X server is running and that $DISPLAY is set correctly.\n" );
451         ExitProcess(1);
452     }
453
454     fcntl( ConnectionNumber(data->display), F_SETFD, 1 ); /* set close on exec flag */
455
456 #ifdef HAVE_XKB
457     if (use_xkb)
458     {
459         use_xkb = XkbUseExtension( data->display, NULL, NULL );
460         if (use_xkb) XkbSetDetectableAutoRepeat( data->display, True, NULL );
461     }
462 #endif
463
464     if (synchronous) XSynchronize( data->display, True );
465     wine_tsx11_unlock();
466
467     if (use_xim && !(data->xim = X11DRV_SetupXIM( data->display, input_style )))
468         WARN("Input Method is not available\n");
469
470     if (wine_server_fd_to_handle( ConnectionNumber(data->display), GENERIC_READ | SYNCHRONIZE,
471                                   FALSE, &data->display_fd ))
472     {
473         MESSAGE( "x11drv: Can't allocate handle for display fd\n" );
474         ExitProcess(1);
475     }
476     data->process_event_count = 0;
477     data->cursor = None;
478     data->cursor_window = None;
479     data->grab_window = None;
480     data->last_focus = 0;
481     data->selection_wnd = 0;
482     NtCurrentTeb()->driver_data = data;
483     if (desktop_tid) AttachThreadInput( GetCurrentThreadId(), desktop_tid, TRUE );
484     return data;
485 }
486
487
488 /***********************************************************************
489  *           X11DRV initialisation routine
490  */
491 BOOL WINAPI DllMain( HINSTANCE hinst, DWORD reason, LPVOID reserved )
492 {
493     BOOL ret = TRUE;
494
495     switch(reason)
496     {
497     case DLL_PROCESS_ATTACH:
498         ret = process_attach();
499         break;
500     case DLL_THREAD_DETACH:
501         thread_detach();
502         break;
503     case DLL_PROCESS_DETACH:
504         process_detach();
505         break;
506     }
507     return ret;
508 }
509
510 /***********************************************************************
511  *              GetScreenSaveActive (X11DRV.@)
512  *
513  * Returns the active status of the screen saver
514  */
515 BOOL X11DRV_GetScreenSaveActive(void)
516 {
517     int timeout, temp;
518     wine_tsx11_lock();
519     XGetScreenSaver(gdi_display, &timeout, &temp, &temp, &temp);
520     wine_tsx11_unlock();
521     return timeout != 0;
522 }
523
524 /***********************************************************************
525  *              SetScreenSaveActive (X11DRV.@)
526  *
527  * Activate/Deactivate the screen saver
528  */
529 void X11DRV_SetScreenSaveActive(BOOL bActivate)
530 {
531     int timeout, interval, prefer_blanking, allow_exposures;
532     static int last_timeout = 15 * 60;
533
534     wine_tsx11_lock();
535     XGetScreenSaver(gdi_display, &timeout, &interval, &prefer_blanking,
536                     &allow_exposures);
537     if (timeout) last_timeout = timeout;
538
539     timeout = bActivate ? last_timeout : 0;
540     XSetScreenSaver(gdi_display, timeout, interval, prefer_blanking,
541                     allow_exposures);
542     wine_tsx11_unlock();
543 }