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