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