Handle WM_CHARs and pass them to TREEVIEW_ProcessLetterKeys. See also
[wine] / dlls / x11drv / x11drv_main.c
1 /*
2  * X11DRV initialization code
3  *
4  * Copyright 1998 Patrik Stridvall
5  * Copyright 2000 Alexandre Julliard
6  */
7
8 #include "config.h"
9
10 #ifdef NO_REENTRANT_X11
11 /* Get pointers to the static errno and h_errno variables used by Xlib. This
12    must be done before including <errno.h> makes the variables invisible.  */
13 extern int errno;
14 static int *perrno = &errno;
15 extern int h_errno;
16 static int *ph_errno = &h_errno;
17 #endif  /* NO_REENTRANT_X11 */
18
19 #include <fcntl.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/time.h>
24 #include <unistd.h>
25 #include <X11/cursorfont.h>
26 #include "ts_xlib.h"
27 #include "ts_xutil.h"
28 #include "ts_shape.h"
29
30 #include "winbase.h"
31 #include "wine/winbase16.h"
32 #include "winreg.h"
33
34 #include "debugtools.h"
35 #include "gdi.h"
36 #include "options.h"
37 #include "user.h"
38 #include "win.h"
39 #include "wine_gl.h"
40 #include "x11drv.h"
41
42 DEFAULT_DEBUG_CHANNEL(x11drv);
43
44 static XKeyboardState keyboard_state;
45 static void (*old_tsx11_lock)(void);
46 static void (*old_tsx11_unlock)(void);
47
48 static CRITICAL_SECTION X11DRV_CritSection = CRITICAL_SECTION_INIT;
49
50 Display *display;
51 Screen *screen;
52 Visual *visual;
53 unsigned int screen_width;
54 unsigned int screen_height;
55 unsigned int screen_depth;
56 Window root_window;
57
58 unsigned int X11DRV_server_startticks;
59
60 #ifdef NO_REENTRANT_X11
61 static int* (*old_errno_location)(void);
62 static int* (*old_h_errno_location)(void);
63
64 /***********************************************************************
65  *           x11_errno_location
66  *
67  * Get the per-thread errno location.
68  */
69 static int *x11_errno_location(void)
70 {
71     /* Use static libc errno while running in Xlib. */
72     if (X11DRV_CritSection.OwningThread == GetCurrentThreadId()) return perrno;
73     return old_errno_location();
74 }
75
76 /***********************************************************************
77  *           x11_h_errno_location
78  *
79  * Get the per-thread h_errno location.
80  */
81 static int *x11_h_errno_location(void)
82 {
83     /* Use static libc h_errno while running in Xlib. */
84     if (X11DRV_CritSection.OwningThread == GetCurrentThreadId()) return ph_errno;
85     return old_h_errno_location();
86 }
87 #endif /* NO_REENTRANT_X11 */
88
89 /***********************************************************************
90  *              error_handler
91  */
92 static int error_handler(Display *display, XErrorEvent *error_evt)
93 {
94     DebugBreak();  /* force an entry in the debugger */
95     return 0;
96 }
97
98 /***********************************************************************
99  *              lock_tsx11
100  */
101 static void lock_tsx11(void)
102 {
103     RtlEnterCriticalSection( &X11DRV_CritSection );
104 }
105
106 /***********************************************************************
107  *              unlock_tsx11
108  */
109 static void unlock_tsx11(void)
110 {
111     RtlLeaveCriticalSection( &X11DRV_CritSection );
112 }
113
114 /***********************************************************************
115  *              get_server_startup
116  *
117  * Get the server startup time 
118  * Won't be exact, but should be sufficient
119  */
120 static void get_server_startup(void)
121 {
122     struct timeval t;
123     gettimeofday( &t, NULL );
124     X11DRV_server_startticks = ((t.tv_sec * 1000) + (t.tv_usec / 1000)) - GetTickCount();
125 }
126
127
128 /***********************************************************************
129  *              setup_options
130  *
131  * Setup the x11drv options.
132  */
133 static void setup_options(void)
134 {
135     char buffer[256];
136     HKEY hkey;
137     DWORD type, count;
138
139     if (RegCreateKeyExA( HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\x11drv", 0, NULL,
140                          REG_OPTION_VOLATILE, KEY_ALL_ACCESS, NULL, &hkey, NULL ))
141     {
142         ERR("Cannot create config registry key\n" );
143         ExitProcess(1);
144     }
145
146     /* --display option */
147
148     count = sizeof(buffer);
149     if (!RegQueryValueExA( hkey, "display", 0, &type, buffer, &count ))
150     {
151         if (Options.display)
152         {
153             if (strcmp( buffer, Options.display ))
154                 MESSAGE( "%s: warning: --display option ignored, using '%s'\n", argv0, buffer );
155         }
156         else if ((Options.display = getenv( "DISPLAY" )))
157         {
158             if (strcmp( buffer, Options.display ))
159                 MESSAGE( "%s: warning: $DISPLAY variable ignored, using '%s'\n", argv0, buffer );
160         }
161         Options.display = strdup(buffer);
162     }
163     else
164     {
165         if (!Options.display && !(Options.display = getenv( "DISPLAY" )))
166         {
167             MESSAGE( "%s: no display specified\n", argv0 );
168             ExitProcess(1);
169         }
170         RegSetValueExA( hkey, "display", 0, REG_SZ, Options.display, strlen(Options.display)+1 );
171     }
172
173     /* check and set --managed and --desktop options in wine config file
174      * if it was not set on command line */
175
176     if ((!Options.managed) && (Options.desktopGeometry == NULL))
177     {
178         count = sizeof(buffer);
179         if (!RegQueryValueExA( hkey, "managed", 0, &type, buffer, &count ))
180             Options.managed = IS_OPTION_TRUE( buffer[0] );
181
182         count = sizeof(buffer);
183         if (!RegQueryValueExA( hkey, "Desktop", 0, &type, buffer, &count ))
184             /* Imperfect validation:  If Desktop=N, then we don't turn on
185             ** the --desktop option.  We should really validate for a correct
186             ** sizing entry */
187             if (! IS_OPTION_FALSE(buffer[0]))
188                 Options.desktopGeometry = strdup(buffer);
189     }
190
191     if (Options.managed)
192         RegSetValueExA( hkey, "managed", 0, REG_SZ, "y", 2 );
193
194     if (Options.desktopGeometry)
195         RegSetValueExA( hkey, "desktop", 0, REG_SZ, Options.desktopGeometry, strlen(Options.desktopGeometry)+1 );
196     
197     RegCloseKey( hkey );
198 }
199
200    
201 /***********************************************************************
202  *              create_desktop
203  *
204  * Create the desktop window for the --desktop mode.
205  */
206 static void create_desktop( const char *geometry )
207 {
208     int x = 0, y = 0, flags;
209     unsigned int width = 640, height = 480;  /* Default size = 640x480 */
210     char *name = "Wine desktop";
211     XSizeHints *size_hints;
212     XWMHints   *wm_hints;
213     XClassHint *class_hints;
214     XSetWindowAttributes win_attr;
215     XTextProperty window_name;
216     Atom XA_WM_DELETE_WINDOW;
217     /* Used to create the desktop window with a good visual */
218     XVisualInfo *vi = NULL;
219 #ifdef HAVE_OPENGL
220     BOOL dblbuf_visual;
221     int err_base, evt_base;
222     
223     /* Get in wine.ini if the desktop window should have a double-buffered visual or not.
224        But first, test if OpenGL is even supported on the display ! */
225     if (glXQueryExtension(display, &err_base, &evt_base) == True) {
226       dblbuf_visual = PROFILE_GetWineIniBool( "x11drv", "DesktopDoubleBuffered", 0 );
227       if (dblbuf_visual)  {
228         int dblBuf[]={GLX_RGBA,GLX_DEPTH_SIZE,16,GLX_DOUBLEBUFFER,None};
229         
230         ENTER_GL();
231         vi = glXChooseVisual(display, DefaultScreen(display), dblBuf);
232         win_attr.colormap = XCreateColormap(display, RootWindow(display,vi->screen),
233                                             vi->visual, AllocNone);
234         LEAVE_GL();
235       }
236     }
237 #endif /* HAVE_OPENGL */    
238
239     flags = TSXParseGeometry( geometry, &x, &y, &width, &height );
240     screen_width  = width;
241     screen_height = height;
242
243     /* Create window */
244     win_attr.background_pixel = BlackPixel(display, 0);
245     win_attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask |
246                           PointerMotionMask | ButtonPressMask |
247                           ButtonReleaseMask | EnterWindowMask;
248     win_attr.cursor = TSXCreateFontCursor( display, XC_top_left_arrow );
249
250     if (vi != NULL) {
251       visual       = vi->visual;
252       screen       = ScreenOfDisplay(display, vi->screen);
253       screen_depth = vi->depth;
254     }
255     root_window = TSXCreateWindow( display,
256                                    (vi == NULL ? DefaultRootWindow(display) : RootWindow(display, vi->screen)),
257                                    x, y, width, height, 0,
258                                    (vi == NULL ? CopyFromParent : vi->depth),
259                                    InputOutput,
260                                    (vi == NULL ? CopyFromParent : vi->visual),
261                                    CWBackPixel | CWEventMask | CWCursor | (vi == NULL ? 0 : CWColormap),
262                                    &win_attr );
263   
264     /* Set window manager properties */
265     size_hints  = TSXAllocSizeHints();
266     wm_hints    = TSXAllocWMHints();
267     class_hints = TSXAllocClassHint();
268     if (!size_hints || !wm_hints || !class_hints)
269     {
270         MESSAGE("Not enough memory for window manager hints.\n" );
271         ExitProcess(1);
272     }
273     size_hints->min_width = size_hints->max_width = width;
274     size_hints->min_height = size_hints->max_height = height;
275     size_hints->flags = PMinSize | PMaxSize;
276     if (flags & (XValue | YValue)) size_hints->flags |= USPosition;
277     if (flags & (WidthValue | HeightValue)) size_hints->flags |= USSize;
278     else size_hints->flags |= PSize;
279
280     wm_hints->flags = InputHint | StateHint;
281     wm_hints->input = True;
282     wm_hints->initial_state = NormalState;
283     class_hints->res_name = (char *)argv0;
284     class_hints->res_class = "Wine";
285
286     TSXStringListToTextProperty( &name, 1, &window_name );
287     TSXSetWMProperties( display, root_window, &window_name, &window_name,
288                         NULL, 0, size_hints, wm_hints, class_hints );
289     XA_WM_DELETE_WINDOW = TSXInternAtom( display, "WM_DELETE_WINDOW", False );
290     TSXSetWMProtocols( display, root_window, &XA_WM_DELETE_WINDOW, 1 );
291     TSXFree( size_hints );
292     TSXFree( wm_hints );
293     TSXFree( class_hints );
294
295     /* Map window */
296     TSXMapWindow( display, root_window );
297 }
298
299
300 /***********************************************************************
301  *           X11DRV process initialisation routine
302  */
303 static void process_attach(void)
304 {
305     WND_Driver       = &X11DRV_WND_Driver;
306
307     get_server_startup();
308     setup_options();
309
310     /* setup TSX11 locking */
311 #ifdef NO_REENTRANT_X11
312     old_errno_location = (void *)InterlockedExchange( (PLONG)&wine_errno_location,
313                                                       (LONG)x11_errno_location );
314     old_h_errno_location = (void *)InterlockedExchange( (PLONG)&wine_h_errno_location,
315                                                         (LONG)x11_h_errno_location );
316 #endif /* NO_REENTRANT_X11 */
317     old_tsx11_lock    = wine_tsx11_lock;
318     old_tsx11_unlock  = wine_tsx11_unlock;
319     wine_tsx11_lock   = lock_tsx11;
320     wine_tsx11_unlock = unlock_tsx11;
321
322     /* Open display */
323
324     if (!(display = TSXOpenDisplay( Options.display )))
325     {
326         MESSAGE( "%s: Can't open display: %s\n", argv0, Options.display );
327         ExitProcess(1);
328     }
329     fcntl( ConnectionNumber(display), F_SETFD, 1 ); /* set close on exec flag */
330     screen = DefaultScreenOfDisplay( display );
331     visual = DefaultVisual( display, DefaultScreen(display) );
332     root_window = DefaultRootWindow( display );
333
334     /* Initialize screen depth */
335
336     screen_depth = PROFILE_GetWineIniInt( "x11drv", "ScreenDepth", 0 );
337     if (screen_depth)  /* depth specified */
338     {
339         int depth_count, i;
340         int *depth_list = TSXListDepths(display, DefaultScreen(display), &depth_count);
341         for (i = 0; i < depth_count; i++)
342             if (depth_list[i] == screen_depth) break;
343         TSXFree( depth_list );
344         if (i >= depth_count)
345         {
346             MESSAGE( "%s: Depth %d not supported on this screen.\n", argv0, screen_depth );
347             ExitProcess(1);
348         }
349     }
350     else screen_depth = DefaultDepthOfScreen( screen );
351
352     /* tell the libX11 that we will do input method handling ourselves
353      * that keep libX11 from doing anything whith dead keys, allowing Wine
354      * to have total control over dead keys, that is this line allows
355      * them to work in Wine, even whith a libX11 including the dead key
356      * patches from Th.Quinot (http://Web.FdN.FR/~tquinot/dead-keys.en.html)
357      */
358     TSXOpenIM( display, NULL, NULL, NULL);
359
360     if (Options.synchronous) XSetErrorHandler( error_handler );
361
362     screen_width  = WidthOfScreen( screen );
363     screen_height = HeightOfScreen( screen );
364
365     if (Options.desktopGeometry)
366     {
367         Options.managed = FALSE;
368         create_desktop( Options.desktopGeometry );
369     }
370
371     /* initialize GDI */
372     if(!X11DRV_GDI_Initialize())
373     {
374         MESSAGE( "%s: X11DRV Couldn't Initialize GDI.\n", argv0 );
375         ExitProcess(1);
376     }
377
378
379     /* save keyboard setup */
380     TSXGetKeyboardControl(display, &keyboard_state);
381
382     /* initialize event handling */
383     X11DRV_EVENT_Init();
384
385     /* load display.dll */
386     LoadLibrary16( "display" );
387 }
388
389
390 /***********************************************************************
391  *           X11DRV process termination routine
392  */
393 static void process_detach(void)
394 {
395     /* restore keyboard setup */
396     XKeyboardControl keyboard_value;
397   
398     keyboard_value.key_click_percent = keyboard_state.key_click_percent;
399     keyboard_value.bell_percent      = keyboard_state.bell_percent;
400     keyboard_value.bell_pitch        = keyboard_state.bell_pitch;
401     keyboard_value.bell_duration     = keyboard_state.bell_duration;
402     keyboard_value.auto_repeat_mode  = keyboard_state.global_auto_repeat;
403   
404     XChangeKeyboardControl(display, KBKeyClickPercent | KBBellPercent | 
405                            KBBellPitch | KBBellDuration | KBAutoRepeatMode, &keyboard_value);
406
407     /* cleanup GDI */
408     X11DRV_GDI_Finalize();
409
410     /* restore TSX11 locking */
411     wine_tsx11_lock = old_tsx11_lock;
412     wine_tsx11_unlock = old_tsx11_unlock;
413 #ifdef NO_REENTRANT_X11
414     wine_errno_location = old_errno_location;
415     wine_h_errno_location = old_h_errno_location;
416 #endif /* NO_REENTRANT_X11 */
417
418 #if 0  /* FIXME */
419     /* close the display */
420     XCloseDisplay( display );
421     display = NULL;
422
423     WND_Driver       = NULL;
424 #endif
425 }
426
427
428 /***********************************************************************
429  *           X11DRV initialisation routine
430  */
431 BOOL WINAPI X11DRV_Init( HINSTANCE hinst, DWORD reason, LPVOID reserved )
432 {
433     switch(reason)
434     {
435     case DLL_PROCESS_ATTACH:
436         process_attach();
437         break;
438     case DLL_PROCESS_DETACH:
439         process_detach();
440         break;
441     }
442     return TRUE;
443 }
444
445 /***********************************************************************
446  *              X11DRV_GetScreenSaveActive
447  *
448  * Returns the active status of the screen saver
449  */
450 BOOL X11DRV_GetScreenSaveActive(void)
451 {
452     int timeout, temp;
453     TSXGetScreenSaver(display, &timeout, &temp, &temp, &temp);
454     return timeout != 0;
455 }
456
457 /***********************************************************************
458  *              X11DRV_SetScreenSaveActive
459  *
460  * Activate/Deactivate the screen saver
461  */
462 void X11DRV_SetScreenSaveActive(BOOL bActivate)
463 {
464     if(bActivate)
465         TSXActivateScreenSaver(display);
466     else
467         TSXResetScreenSaver(display);
468 }
469
470 /***********************************************************************
471  *              X11DRV_GetScreenSaveTimeout
472  *
473  * Return the screen saver timeout
474  */
475 int X11DRV_GetScreenSaveTimeout(void)
476 {
477     int timeout, temp;
478     TSXGetScreenSaver(display, &timeout, &temp, &temp, &temp);
479     return timeout;
480 }
481
482 /***********************************************************************
483  *              X11DRV_SetScreenSaveTimeout
484  *
485  * Set the screen saver timeout
486  */
487 void X11DRV_SetScreenSaveTimeout(int nTimeout)
488 {
489     /* timeout is a 16bit entity (CARD16) in the protocol, so it should
490      * not get over 32767 or it will get negative. */
491     if (nTimeout>32767) nTimeout = 32767;
492     TSXSetScreenSaver(display, nTimeout, 60, DefaultBlanking, DefaultExposures);
493 }
494
495 /***********************************************************************
496  *              X11DRV_IsSingleWindow
497  */
498 BOOL X11DRV_IsSingleWindow(void)
499 {
500     return (root_window != DefaultRootWindow(display));
501 }