Get rid of cursoricon.h.
[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 WORD USER_HeapSel = 0;  /* USER heap selector */
39 HMODULE user32_module = 0;
40
41 static SYSLEVEL USER_SysLevel;
42 static CRITICAL_SECTION_DEBUG critsect_debug =
43 {
44     0, 0, &USER_SysLevel.crst,
45     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
46       0, 0, { 0, (DWORD)(__FILE__ ": USER_SysLevel") }
47 };
48 static SYSLEVEL USER_SysLevel = { { &critsect_debug, -1, 0, 0, 0, 0 }, 2 };
49
50 static HPALETTE (WINAPI *pfnGDISelectPalette)( HDC hdc, HPALETTE hpal, WORD bkgnd );
51 static UINT (WINAPI *pfnGDIRealizePalette)( HDC hdc );
52 static HPALETTE hPrimaryPalette;
53
54 static DWORD exiting_thread_id;
55
56 extern void WDML_NotifyThreadDetach(void);
57
58
59 /***********************************************************************
60  *           USER_Lock
61  */
62 void USER_Lock(void)
63 {
64     _EnterSysLevel( &USER_SysLevel );
65 }
66
67
68 /***********************************************************************
69  *           USER_Unlock
70  */
71 void USER_Unlock(void)
72 {
73     _LeaveSysLevel( &USER_SysLevel );
74 }
75
76
77 /***********************************************************************
78  *           USER_CheckNotLock
79  *
80  * Make sure that we don't hold the user lock.
81  */
82 void USER_CheckNotLock(void)
83 {
84     _CheckNotSysLevel( &USER_SysLevel );
85 }
86
87
88 /***********************************************************************
89  *              UserSelectPalette (Not a Windows API)
90  */
91 static HPALETTE WINAPI UserSelectPalette( HDC hDC, HPALETTE hPal, BOOL bForceBackground )
92 {
93     WORD wBkgPalette = 1;
94
95     if (!bForceBackground && (hPal != GetStockObject(DEFAULT_PALETTE)))
96     {
97         HWND hwnd = WindowFromDC( hDC );
98         if (hwnd)
99         {
100             HWND hForeground = GetForegroundWindow();
101             /* set primary palette if it's related to current active */
102             if (hForeground == hwnd || IsChild(hForeground,hwnd))
103             {
104                 wBkgPalette = 0;
105                 hPrimaryPalette = hPal;
106             }
107         }
108     }
109     return pfnGDISelectPalette( hDC, hPal, wBkgPalette);
110 }
111
112
113 /***********************************************************************
114  *              UserRealizePalette (USER32.@)
115  */
116 UINT WINAPI UserRealizePalette( HDC hDC )
117 {
118     UINT realized = pfnGDIRealizePalette( hDC );
119
120     /* do not send anything if no colors were changed */
121     if (realized && GetCurrentObject( hDC, OBJ_PAL ) == hPrimaryPalette)
122     {
123         /* send palette change notification */
124         HWND hWnd = WindowFromDC( hDC );
125         if (hWnd) SendMessageTimeoutW( HWND_BROADCAST, WM_PALETTECHANGED, (WPARAM)hWnd, 0,
126                                        SMTO_ABORTIFHUNG, 2000, NULL );
127     }
128     return realized;
129 }
130
131
132 /***********************************************************************
133  *           palette_init
134  *
135  * Patch the function pointers in GDI for SelectPalette and RealizePalette
136  */
137 static void palette_init(void)
138 {
139     void **ptr;
140     HMODULE module = GetModuleHandleA( "gdi32" );
141     if (!module)
142     {
143         ERR( "cannot get GDI32 handle\n" );
144         return;
145     }
146     if ((ptr = (void**)GetProcAddress( module, "pfnSelectPalette" )))
147         pfnGDISelectPalette = InterlockedExchangePointer( ptr, UserSelectPalette );
148     else ERR( "cannot find pfnSelectPalette in GDI32\n" );
149     if ((ptr = (void**)GetProcAddress( module, "pfnRealizePalette" )))
150         pfnGDIRealizePalette = InterlockedExchangePointer( ptr, UserRealizePalette );
151     else ERR( "cannot find pfnRealizePalette in GDI32\n" );
152 }
153
154
155 /***********************************************************************
156  *           USER initialisation routine
157  */
158 static BOOL process_attach(void)
159 {
160     HINSTANCE16 instance;
161
162     /* Create USER heap */
163     if ((instance = LoadLibrary16( "USER.EXE" )) >= 32) USER_HeapSel = instance | 7;
164     else
165     {
166         USER_HeapSel = GlobalAlloc16( GMEM_FIXED, 65536 );
167         LocalInit16( USER_HeapSel, 32, 65534 );
168     }
169
170     /* some Win9x dlls expect keyboard to be loaded */
171     if (GetVersion() & 0x80000000) LoadLibrary16( "keyboard.drv" );
172
173     /* Initialize system colors and metrics */
174     SYSPARAMS_Init();
175
176     /* Setup palette function pointers */
177     palette_init();
178
179     /* Initialize built-in window classes */
180     CLASS_RegisterBuiltinClasses();
181
182     /* Initialize message spying */
183     if (!SPY_Init()) return FALSE;
184
185     return TRUE;
186 }
187
188
189 /**********************************************************************
190  *           USER_IsExitingThread
191  */
192 BOOL USER_IsExitingThread( DWORD tid )
193 {
194     return (tid == exiting_thread_id);
195 }
196
197
198 /**********************************************************************
199  *           thread_detach
200  */
201 static void thread_detach(void)
202 {
203     exiting_thread_id = GetCurrentThreadId();
204
205     WDML_NotifyThreadDetach();
206
207     WIN_DestroyThreadWindows( GetDesktopWindow() );
208     CloseHandle( get_user_thread_info()->server_queue );
209
210     exiting_thread_id = 0;
211 }
212
213
214 /***********************************************************************
215  *           UserClientDllInitialize  (USER32.@)
216  *
217  * USER dll initialisation routine (exported as UserClientDllInitialize for compatibility).
218  */
219 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
220 {
221     BOOL ret = TRUE;
222     switch(reason)
223     {
224     case DLL_PROCESS_ATTACH:
225         user32_module = inst;
226         ret = process_attach();
227         break;
228     case DLL_THREAD_DETACH:
229         thread_detach();
230         break;
231     }
232     return ret;
233 }
234
235
236 /***********************************************************************
237  *           USER_GetProcessHandleList(Internal)
238  */
239 static HANDLE *USER_GetProcessHandleList(void)
240 {
241     DWORD count, i, n;
242     HANDLE *list;
243     PROCESSENTRY32 pe;
244     HANDLE hSnapshot;
245     BOOL r;
246
247     hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
248     if (!hSnapshot)
249     {
250         ERR("cannot create snapshot\n");
251         return FALSE;
252     }
253
254     /* count the number of processes plus one */
255     for (count=0; ;count++)
256     {
257         pe.dwSize = sizeof pe;
258         if (count)
259             r = Process32Next( hSnapshot, &pe );
260         else
261             r = Process32First( hSnapshot, &pe );
262         if (!r)
263             break;
264     }
265
266     /* allocate memory make a list of the process handles */
267     list = HeapAlloc( GetProcessHeap(), 0, (count+1)*sizeof(HANDLE) );
268     n=0;
269     for (i=0; i<count; i++)
270     {
271         pe.dwSize = sizeof pe;
272         if (i)
273             r = Process32Next( hSnapshot, &pe );
274         else
275             r = Process32First( hSnapshot, &pe );
276         if (!r)
277             break;
278
279         /* don't kill ourselves */
280         if (GetCurrentProcessId() == pe.th32ProcessID )
281             continue;
282
283         /* open the process so we don't can track it */
284         list[n] = OpenProcess( PROCESS_QUERY_INFORMATION|
285                                   PROCESS_TERMINATE,
286                                   FALSE, pe.th32ProcessID );
287
288         /* check it didn't terminate already */
289         if( list[n] )
290             n++;
291     }
292     list[n]=0;
293     CloseHandle( hSnapshot );
294
295     if (!r)
296         ERR("Error enumerating processes\n");
297
298     TRACE("return %lu processes\n", n);
299
300     return list;
301 }
302
303
304 /***********************************************************************
305  *              USER_KillProcesses (Internal)
306  */
307 static DWORD USER_KillProcesses(void)
308 {
309     DWORD n, r, i;
310     HANDLE *handles;
311     const DWORD dwShutdownTimeout = 10000;
312
313     TRACE("terminating other processes\n");
314
315     /* kill it and add it to our list of object to wait on */
316     handles = USER_GetProcessHandleList();
317     for (n=0; handles && handles[n]; n++)
318         TerminateProcess( handles[n], 0 );
319
320     /* wait for processes to exit */
321     for (i=0; i<n; i+=MAXIMUM_WAIT_OBJECTS)
322     {
323         int n_objs = ((n-i)>MAXIMUM_WAIT_OBJECTS) ? MAXIMUM_WAIT_OBJECTS : (n-i);
324         r = WaitForMultipleObjects( n_objs, &handles[i], TRUE, dwShutdownTimeout );
325         if (r==WAIT_TIMEOUT)
326             ERR("wait failed!\n");
327     }
328
329     /* close the handles */
330     for (i=0; i<n; i++)
331         CloseHandle( handles[i] );
332
333     HeapFree( GetProcessHeap(), 0, handles );
334
335     return n;
336 }
337
338
339 /***********************************************************************
340  *              USER_DoShutdown (Internal)
341  */
342 static void USER_DoShutdown(void)
343 {
344     DWORD i, n;
345     const DWORD nRetries = 10;
346
347     for (i=0; i<nRetries; i++)
348     {
349         n = USER_KillProcesses();
350         TRACE("Killed %ld processes, attempt %ld\n", n, i);
351         if(!n)
352             break;
353     }
354 }
355
356
357 /***********************************************************************
358  *              ExitWindowsEx (USER32.@)
359  */
360 BOOL WINAPI ExitWindowsEx( UINT flags, DWORD reserved )
361 {
362     int i;
363     BOOL result = FALSE;
364     HWND *list, *phwnd;
365
366     /* We have to build a list of all windows first, as in EnumWindows */
367     TRACE("(%x,%lx)\n", flags, reserved);
368
369     list = WIN_ListChildren( GetDesktopWindow() );
370     if (list)
371     {
372         /* Send a WM_QUERYENDSESSION message to every window */
373
374         for (i = 0; list[i]; i++)
375         {
376             /* Make sure that the window still exists */
377             if (!IsWindow( list[i] )) continue;
378             if (!SendMessageW( list[i], WM_QUERYENDSESSION, 0, 0 )) break;
379         }
380         result = !list[i];
381
382         /* Now notify all windows that got a WM_QUERYENDSESSION of the result */
383
384         for (phwnd = list; i > 0; i--, phwnd++)
385         {
386             if (!IsWindow( *phwnd )) continue;
387             SendMessageW( *phwnd, WM_ENDSESSION, result, 0 );
388         }
389         HeapFree( GetProcessHeap(), 0, list );
390
391         if ( !(result || (flags & EWX_FORCE) ))
392             return FALSE;
393     }
394
395     /* USER_DoShutdown will kill all processes except the current process */
396     USER_DoShutdown();
397
398     if (flags & EWX_REBOOT)
399     {
400         WCHAR winebootW[] = { 'w','i','n','e','b','o','o','t',0 };
401         PROCESS_INFORMATION pi;
402         STARTUPINFOW si;
403
404         memset( &si, 0, sizeof si );
405         si.cb = sizeof si;
406         if (CreateProcessW( NULL, winebootW, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
407         {
408             CloseHandle( pi.hProcess );
409             CloseHandle( pi.hThread );
410         }
411         else
412             MESSAGE("wine: Failed to start wineboot\n");
413     }
414
415     if (result) ExitProcess(0);
416     return TRUE;
417 }