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