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