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