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