Add stub for SetLayeredWindowAttributes.
[wine] / dlls / user / user_main.c
1 /*
2  * USER initialization code
3  *
4  * Copyright 2000 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include <stdarg.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include "windef.h"
25 #include "winbase.h"
26 #include "wingdi.h"
27 #include "winuser.h"
28 #include "winreg.h"
29 #include "tlhelp32.h"
30
31 #include "controls.h"
32 #include "user_private.h"
33 #include "win.h"
34 #include "wine/debug.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(graphics);
37
38 USER_DRIVER USER_Driver;
39
40 WORD USER_HeapSel = 0;  /* USER heap selector */
41 HMODULE user32_module = 0;
42
43 static SYSLEVEL USER_SysLevel;
44 static CRITICAL_SECTION_DEBUG critsect_debug =
45 {
46     0, 0, &USER_SysLevel.crst,
47     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
48       0, 0, { 0, (DWORD)(__FILE__ ": USER_SysLevel") }
49 };
50 static SYSLEVEL USER_SysLevel = { { &critsect_debug, -1, 0, 0, 0, 0 }, 2 };
51
52 static HPALETTE (WINAPI *pfnGDISelectPalette)( HDC hdc, HPALETTE hpal, WORD bkgnd );
53 static UINT (WINAPI *pfnGDIRealizePalette)( HDC hdc );
54 static HPALETTE hPrimaryPalette;
55
56 static HMODULE graphics_driver;
57 static DWORD exiting_thread_id;
58
59 extern void WDML_NotifyThreadDetach(void);
60
61 #define GET_USER_FUNC(name) USER_Driver.p##name = (void*)GetProcAddress( graphics_driver, #name )
62
63 /* load the graphics driver */
64 static BOOL load_driver(void)
65 {
66     char buffer[MAX_PATH], libname[32], *name, *next;
67     HKEY hkey;
68
69     strcpy( buffer, "x11,tty" );  /* default value */
70     /* @@ Wine registry key: HKCU\Software\Wine\Drivers */
71     if (!RegOpenKeyA( HKEY_CURRENT_USER, "Software\\Wine\\Drivers", &hkey ))
72     {
73         DWORD type, count = sizeof(buffer);
74         RegQueryValueExA( hkey, "Graphics", 0, &type, (LPBYTE) buffer, &count );
75         RegCloseKey( hkey );
76     }
77
78     name = buffer;
79     while (name)
80     {
81         next = strchr( name, ',' );
82         if (next) *next++ = 0;
83
84         snprintf( libname, sizeof(libname), "wine%s.drv", name );
85         if ((graphics_driver = LoadLibraryA( libname )) != 0) break;
86         name = next;
87     }
88     if (!graphics_driver)
89     {
90         MESSAGE( "wine: Could not load graphics driver '%s'.\n", buffer );
91         if (!strcasecmp( buffer, "x11" ))
92             MESSAGE( "Make sure that your X server is running and that $DISPLAY is set correctly.\n" );
93         ExitProcess(1);
94     }
95
96     GET_USER_FUNC(ActivateKeyboardLayout);
97     GET_USER_FUNC(Beep);
98     GET_USER_FUNC(GetAsyncKeyState);
99     GET_USER_FUNC(GetKeyNameText);
100     GET_USER_FUNC(GetKeyboardLayout);
101     GET_USER_FUNC(GetKeyboardLayoutList);
102     GET_USER_FUNC(GetKeyboardLayoutName);
103     GET_USER_FUNC(LoadKeyboardLayout);
104     GET_USER_FUNC(MapVirtualKeyEx);
105     GET_USER_FUNC(SendInput);
106     GET_USER_FUNC(ToUnicodeEx);
107     GET_USER_FUNC(UnloadKeyboardLayout);
108     GET_USER_FUNC(VkKeyScanEx);
109     GET_USER_FUNC(SetCursor);
110     GET_USER_FUNC(GetCursorPos);
111     GET_USER_FUNC(SetCursorPos);
112     GET_USER_FUNC(GetScreenSaveActive);
113     GET_USER_FUNC(SetScreenSaveActive);
114     GET_USER_FUNC(AcquireClipboard);
115     GET_USER_FUNC(EmptyClipboard);
116     GET_USER_FUNC(SetClipboardData);
117     GET_USER_FUNC(GetClipboardData);
118     GET_USER_FUNC(CountClipboardFormats);
119     GET_USER_FUNC(EnumClipboardFormats);
120     GET_USER_FUNC(IsClipboardFormatAvailable);
121     GET_USER_FUNC(RegisterClipboardFormat);
122     GET_USER_FUNC(GetClipboardFormatName);
123     GET_USER_FUNC(EndClipboardUpdate);
124     GET_USER_FUNC(ResetSelectionOwner);
125     GET_USER_FUNC(ChangeDisplaySettingsExW);
126     GET_USER_FUNC(EnumDisplaySettingsExW);
127     GET_USER_FUNC(CreateDesktopWindow);
128     GET_USER_FUNC(CreateWindow);
129     GET_USER_FUNC(DestroyWindow);
130     GET_USER_FUNC(GetDCEx);
131     GET_USER_FUNC(MsgWaitForMultipleObjectsEx);
132     GET_USER_FUNC(ReleaseDC);
133     GET_USER_FUNC(ScrollDC);
134     GET_USER_FUNC(SetFocus);
135     GET_USER_FUNC(SetParent);
136     GET_USER_FUNC(SetWindowPos);
137     GET_USER_FUNC(SetWindowRgn);
138     GET_USER_FUNC(SetWindowIcon);
139     GET_USER_FUNC(SetWindowStyle);
140     GET_USER_FUNC(SetWindowText);
141     GET_USER_FUNC(ShowWindow);
142     GET_USER_FUNC(SysCommandSizeMove);
143     GET_USER_FUNC(WindowFromDC);
144     GET_USER_FUNC(WindowMessage);
145
146     return TRUE;
147 }
148
149
150 /***********************************************************************
151  *           USER_Lock
152  */
153 void USER_Lock(void)
154 {
155     _EnterSysLevel( &USER_SysLevel );
156 }
157
158
159 /***********************************************************************
160  *           USER_Unlock
161  */
162 void USER_Unlock(void)
163 {
164     _LeaveSysLevel( &USER_SysLevel );
165 }
166
167
168 /***********************************************************************
169  *           USER_CheckNotLock
170  *
171  * Make sure that we don't hold the user lock.
172  */
173 void USER_CheckNotLock(void)
174 {
175     _CheckNotSysLevel( &USER_SysLevel );
176 }
177
178
179 /***********************************************************************
180  *              UserSelectPalette (Not a Windows API)
181  */
182 static HPALETTE WINAPI UserSelectPalette( HDC hDC, HPALETTE hPal, BOOL bForceBackground )
183 {
184     WORD wBkgPalette = 1;
185
186     if (!bForceBackground && (hPal != GetStockObject(DEFAULT_PALETTE)))
187     {
188         HWND hwnd = WindowFromDC( hDC );
189         if (hwnd)
190         {
191             HWND hForeground = GetForegroundWindow();
192             /* set primary palette if it's related to current active */
193             if (hForeground == hwnd || IsChild(hForeground,hwnd))
194             {
195                 wBkgPalette = 0;
196                 hPrimaryPalette = hPal;
197             }
198         }
199     }
200     return pfnGDISelectPalette( hDC, hPal, wBkgPalette);
201 }
202
203
204 /***********************************************************************
205  *              UserRealizePalette (USER32.@)
206  */
207 UINT WINAPI UserRealizePalette( HDC hDC )
208 {
209     UINT realized = pfnGDIRealizePalette( hDC );
210
211     /* do not send anything if no colors were changed */
212     if (realized && GetCurrentObject( hDC, OBJ_PAL ) == hPrimaryPalette)
213     {
214         /* send palette change notification */
215         HWND hWnd = WindowFromDC( hDC );
216         if (hWnd) SendMessageTimeoutW( HWND_BROADCAST, WM_PALETTECHANGED, (WPARAM)hWnd, 0,
217                                        SMTO_ABORTIFHUNG, 2000, NULL );
218     }
219     return realized;
220 }
221
222
223 /***********************************************************************
224  *           palette_init
225  *
226  * Patch the function pointers in GDI for SelectPalette and RealizePalette
227  */
228 static void palette_init(void)
229 {
230     void **ptr;
231     HMODULE module = GetModuleHandleA( "gdi32" );
232     if (!module)
233     {
234         ERR( "cannot get GDI32 handle\n" );
235         return;
236     }
237     if ((ptr = (void**)GetProcAddress( module, "pfnSelectPalette" )))
238         pfnGDISelectPalette = InterlockedExchangePointer( ptr, UserSelectPalette );
239     else ERR( "cannot find pfnSelectPalette in GDI32\n" );
240     if ((ptr = (void**)GetProcAddress( module, "pfnRealizePalette" )))
241         pfnGDIRealizePalette = InterlockedExchangePointer( ptr, UserRealizePalette );
242     else ERR( "cannot find pfnRealizePalette in GDI32\n" );
243 }
244
245
246 /***********************************************************************
247  *           USER initialisation routine
248  */
249 static BOOL process_attach(void)
250 {
251     HINSTANCE16 instance;
252
253     /* Create USER heap */
254     if ((instance = LoadLibrary16( "USER.EXE" )) >= 32) USER_HeapSel = instance | 7;
255     else
256     {
257         USER_HeapSel = GlobalAlloc16( GMEM_FIXED, 65536 );
258         LocalInit16( USER_HeapSel, 32, 65534 );
259     }
260
261     /* some Win9x dlls expect keyboard to be loaded */
262     if (GetVersion() & 0x80000000) LoadLibrary16( "keyboard.drv" );
263
264     /* Load the graphics driver */
265     if (!load_driver()) return FALSE;
266
267     /* Initialize system colors and metrics */
268     SYSPARAMS_Init();
269
270     /* Setup palette function pointers */
271     palette_init();
272
273     /* Initialize built-in window classes */
274     CLASS_RegisterBuiltinClasses();
275
276     /* Initialize menus */
277     if (!MENU_Init()) return FALSE;
278
279     /* Initialize message spying */
280     if (!SPY_Init()) return FALSE;
281
282     return TRUE;
283 }
284
285
286 /**********************************************************************
287  *           USER_IsExitingThread
288  */
289 BOOL USER_IsExitingThread( DWORD tid )
290 {
291     return (tid == exiting_thread_id);
292 }
293
294
295 /**********************************************************************
296  *           thread_detach
297  */
298 static void thread_detach(void)
299 {
300     exiting_thread_id = GetCurrentThreadId();
301
302     WDML_NotifyThreadDetach();
303
304     WIN_DestroyThreadWindows( GetDesktopWindow() );
305     CloseHandle( get_user_thread_info()->server_queue );
306
307     exiting_thread_id = 0;
308 }
309
310
311 /**********************************************************************
312  *           process_detach
313  */
314 static void process_detach(void)
315 {
316     memset(&USER_Driver, 0, sizeof(USER_Driver));
317     FreeLibrary(graphics_driver);
318 }
319
320 /***********************************************************************
321  *           UserClientDllInitialize  (USER32.@)
322  *
323  * USER dll initialisation routine (exported as UserClientDllInitialize for compatibility).
324  */
325 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
326 {
327     BOOL ret = TRUE;
328     switch(reason)
329     {
330     case DLL_PROCESS_ATTACH:
331         user32_module = inst;
332         ret = process_attach();
333         break;
334     case DLL_PROCESS_DETACH:
335         process_detach();
336         break;
337     case DLL_THREAD_DETACH:
338         thread_detach();
339         break;
340     }
341     return ret;
342 }
343
344
345 /***********************************************************************
346  *           USER_GetProcessHandleList(Internal)
347  */
348 static HANDLE *USER_GetProcessHandleList(void)
349 {
350     DWORD count, i, n;
351     HANDLE *list;
352     PROCESSENTRY32 pe;
353     HANDLE hSnapshot;
354     BOOL r;
355
356     hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
357     if (!hSnapshot)
358     {
359         ERR("cannot create snapshot\n");
360         return FALSE;
361     }
362
363     /* count the number of processes plus one */
364     for (count=0; ;count++)
365     {
366         pe.dwSize = sizeof pe;
367         if (count)
368             r = Process32Next( hSnapshot, &pe );
369         else
370             r = Process32First( hSnapshot, &pe );
371         if (!r)
372             break;
373     }
374
375     /* allocate memory make a list of the process handles */
376     list = HeapAlloc( GetProcessHeap(), 0, (count+1)*sizeof(HANDLE) );
377     n=0;
378     for (i=0; i<count; i++)
379     {
380         pe.dwSize = sizeof pe;
381         if (i)
382             r = Process32Next( hSnapshot, &pe );
383         else
384             r = Process32First( hSnapshot, &pe );
385         if (!r)
386             break;
387
388         /* don't kill ourselves */
389         if (GetCurrentProcessId() == pe.th32ProcessID )
390             continue;
391
392         /* open the process so we don't can track it */
393         list[n] = OpenProcess( PROCESS_QUERY_INFORMATION|
394                                   PROCESS_TERMINATE,
395                                   FALSE, pe.th32ProcessID );
396
397         /* check it didn't terminate already */
398         if( list[n] )
399             n++;
400     }
401     list[n]=0;
402     CloseHandle( hSnapshot );
403
404     if (!r)
405         ERR("Error enumerating processes\n");
406
407     TRACE("return %lu processes\n", n);
408
409     return list;
410 }
411
412
413 /***********************************************************************
414  *              USER_KillProcesses (Internal)
415  */
416 static DWORD USER_KillProcesses(void)
417 {
418     DWORD n, r, i;
419     HANDLE *handles;
420     const DWORD dwShutdownTimeout = 10000;
421
422     TRACE("terminating other processes\n");
423
424     /* kill it and add it to our list of object to wait on */
425     handles = USER_GetProcessHandleList();
426     for (n=0; handles && handles[n]; n++)
427         TerminateProcess( handles[n], 0 );
428
429     /* wait for processes to exit */
430     for (i=0; i<n; i+=MAXIMUM_WAIT_OBJECTS)
431     {
432         int n_objs = ((n-i)>MAXIMUM_WAIT_OBJECTS) ? MAXIMUM_WAIT_OBJECTS : (n-i);
433         r = WaitForMultipleObjects( n_objs, &handles[i], TRUE, dwShutdownTimeout );
434         if (r==WAIT_TIMEOUT)
435             ERR("wait failed!\n");
436     }
437
438     /* close the handles */
439     for (i=0; i<n; i++)
440         CloseHandle( handles[i] );
441
442     HeapFree( GetProcessHeap(), 0, handles );
443
444     return n;
445 }
446
447
448 /***********************************************************************
449  *              USER_DoShutdown (Internal)
450  */
451 static void USER_DoShutdown(void)
452 {
453     DWORD i, n;
454     const DWORD nRetries = 10;
455
456     for (i=0; i<nRetries; i++)
457     {
458         n = USER_KillProcesses();
459         TRACE("Killed %ld processes, attempt %ld\n", n, i);
460         if(!n)
461             break;
462     }
463 }
464
465
466 /***********************************************************************
467  *              ExitWindowsEx (USER32.@)
468  */
469 BOOL WINAPI ExitWindowsEx( UINT flags, DWORD reserved )
470 {
471     int i;
472     BOOL result = FALSE;
473     HWND *list, *phwnd;
474
475     /* We have to build a list of all windows first, as in EnumWindows */
476     TRACE("(%x,%lx)\n", flags, reserved);
477
478     list = WIN_ListChildren( GetDesktopWindow() );
479     if (list)
480     {
481         /* Send a WM_QUERYENDSESSION message to every window */
482
483         for (i = 0; list[i]; i++)
484         {
485             /* Make sure that the window still exists */
486             if (!IsWindow( list[i] )) continue;
487             if (!SendMessageW( list[i], WM_QUERYENDSESSION, 0, 0 )) break;
488         }
489         result = !list[i];
490
491         /* Now notify all windows that got a WM_QUERYENDSESSION of the result */
492
493         for (phwnd = list; i > 0; i--, phwnd++)
494         {
495             if (!IsWindow( *phwnd )) continue;
496             SendMessageW( *phwnd, WM_ENDSESSION, result, 0 );
497         }
498         HeapFree( GetProcessHeap(), 0, list );
499
500         if ( !(result || (flags & EWX_FORCE) ))
501             return FALSE;
502     }
503
504     /* USER_DoShutdown will kill all processes except the current process */
505     USER_DoShutdown();
506
507     if (flags & EWX_REBOOT)
508     {
509         WCHAR winebootW[] = { 'w','i','n','e','b','o','o','t',0 };
510         PROCESS_INFORMATION pi;
511         STARTUPINFOW si;
512
513         memset( &si, 0, sizeof si );
514         si.cb = sizeof si;
515         if (CreateProcessW( NULL, winebootW, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
516         {
517             CloseHandle( pi.hProcess );
518             CloseHandle( pi.hThread );
519         }
520         else
521             MESSAGE("wine: Failed to start wineboot\n");
522     }
523
524     if (result) ExitProcess(0);
525     return TRUE;
526 }