Load the USER driver on demand instead of at user32 load time.
[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 menus */
183     if (!MENU_Init()) return FALSE;
184
185     /* Initialize message spying */
186     if (!SPY_Init()) return FALSE;
187
188     return TRUE;
189 }
190
191
192 /**********************************************************************
193  *           USER_IsExitingThread
194  */
195 BOOL USER_IsExitingThread( DWORD tid )
196 {
197     return (tid == exiting_thread_id);
198 }
199
200
201 /**********************************************************************
202  *           thread_detach
203  */
204 static void thread_detach(void)
205 {
206     exiting_thread_id = GetCurrentThreadId();
207
208     WDML_NotifyThreadDetach();
209
210     WIN_DestroyThreadWindows( GetDesktopWindow() );
211     CloseHandle( get_user_thread_info()->server_queue );
212
213     exiting_thread_id = 0;
214 }
215
216
217 /***********************************************************************
218  *           UserClientDllInitialize  (USER32.@)
219  *
220  * USER dll initialisation routine (exported as UserClientDllInitialize for compatibility).
221  */
222 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
223 {
224     BOOL ret = TRUE;
225     switch(reason)
226     {
227     case DLL_PROCESS_ATTACH:
228         user32_module = inst;
229         ret = process_attach();
230         break;
231     case DLL_THREAD_DETACH:
232         thread_detach();
233         break;
234     }
235     return ret;
236 }
237
238
239 /***********************************************************************
240  *           USER_GetProcessHandleList(Internal)
241  */
242 static HANDLE *USER_GetProcessHandleList(void)
243 {
244     DWORD count, i, n;
245     HANDLE *list;
246     PROCESSENTRY32 pe;
247     HANDLE hSnapshot;
248     BOOL r;
249
250     hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
251     if (!hSnapshot)
252     {
253         ERR("cannot create snapshot\n");
254         return FALSE;
255     }
256
257     /* count the number of processes plus one */
258     for (count=0; ;count++)
259     {
260         pe.dwSize = sizeof pe;
261         if (count)
262             r = Process32Next( hSnapshot, &pe );
263         else
264             r = Process32First( hSnapshot, &pe );
265         if (!r)
266             break;
267     }
268
269     /* allocate memory make a list of the process handles */
270     list = HeapAlloc( GetProcessHeap(), 0, (count+1)*sizeof(HANDLE) );
271     n=0;
272     for (i=0; i<count; i++)
273     {
274         pe.dwSize = sizeof pe;
275         if (i)
276             r = Process32Next( hSnapshot, &pe );
277         else
278             r = Process32First( hSnapshot, &pe );
279         if (!r)
280             break;
281
282         /* don't kill ourselves */
283         if (GetCurrentProcessId() == pe.th32ProcessID )
284             continue;
285
286         /* open the process so we don't can track it */
287         list[n] = OpenProcess( PROCESS_QUERY_INFORMATION|
288                                   PROCESS_TERMINATE,
289                                   FALSE, pe.th32ProcessID );
290
291         /* check it didn't terminate already */
292         if( list[n] )
293             n++;
294     }
295     list[n]=0;
296     CloseHandle( hSnapshot );
297
298     if (!r)
299         ERR("Error enumerating processes\n");
300
301     TRACE("return %lu processes\n", n);
302
303     return list;
304 }
305
306
307 /***********************************************************************
308  *              USER_KillProcesses (Internal)
309  */
310 static DWORD USER_KillProcesses(void)
311 {
312     DWORD n, r, i;
313     HANDLE *handles;
314     const DWORD dwShutdownTimeout = 10000;
315
316     TRACE("terminating other processes\n");
317
318     /* kill it and add it to our list of object to wait on */
319     handles = USER_GetProcessHandleList();
320     for (n=0; handles && handles[n]; n++)
321         TerminateProcess( handles[n], 0 );
322
323     /* wait for processes to exit */
324     for (i=0; i<n; i+=MAXIMUM_WAIT_OBJECTS)
325     {
326         int n_objs = ((n-i)>MAXIMUM_WAIT_OBJECTS) ? MAXIMUM_WAIT_OBJECTS : (n-i);
327         r = WaitForMultipleObjects( n_objs, &handles[i], TRUE, dwShutdownTimeout );
328         if (r==WAIT_TIMEOUT)
329             ERR("wait failed!\n");
330     }
331
332     /* close the handles */
333     for (i=0; i<n; i++)
334         CloseHandle( handles[i] );
335
336     HeapFree( GetProcessHeap(), 0, handles );
337
338     return n;
339 }
340
341
342 /***********************************************************************
343  *              USER_DoShutdown (Internal)
344  */
345 static void USER_DoShutdown(void)
346 {
347     DWORD i, n;
348     const DWORD nRetries = 10;
349
350     for (i=0; i<nRetries; i++)
351     {
352         n = USER_KillProcesses();
353         TRACE("Killed %ld processes, attempt %ld\n", n, i);
354         if(!n)
355             break;
356     }
357 }
358
359
360 /***********************************************************************
361  *              ExitWindowsEx (USER32.@)
362  */
363 BOOL WINAPI ExitWindowsEx( UINT flags, DWORD reserved )
364 {
365     int i;
366     BOOL result = FALSE;
367     HWND *list, *phwnd;
368
369     /* We have to build a list of all windows first, as in EnumWindows */
370     TRACE("(%x,%lx)\n", flags, reserved);
371
372     list = WIN_ListChildren( GetDesktopWindow() );
373     if (list)
374     {
375         /* Send a WM_QUERYENDSESSION message to every window */
376
377         for (i = 0; list[i]; i++)
378         {
379             /* Make sure that the window still exists */
380             if (!IsWindow( list[i] )) continue;
381             if (!SendMessageW( list[i], WM_QUERYENDSESSION, 0, 0 )) break;
382         }
383         result = !list[i];
384
385         /* Now notify all windows that got a WM_QUERYENDSESSION of the result */
386
387         for (phwnd = list; i > 0; i--, phwnd++)
388         {
389             if (!IsWindow( *phwnd )) continue;
390             SendMessageW( *phwnd, WM_ENDSESSION, result, 0 );
391         }
392         HeapFree( GetProcessHeap(), 0, list );
393
394         if ( !(result || (flags & EWX_FORCE) ))
395             return FALSE;
396     }
397
398     /* USER_DoShutdown will kill all processes except the current process */
399     USER_DoShutdown();
400
401     if (flags & EWX_REBOOT)
402     {
403         WCHAR winebootW[] = { 'w','i','n','e','b','o','o','t',0 };
404         PROCESS_INFORMATION pi;
405         STARTUPINFOW si;
406
407         memset( &si, 0, sizeof si );
408         si.cb = sizeof si;
409         if (CreateProcessW( NULL, winebootW, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi ))
410         {
411             CloseHandle( pi.hProcess );
412             CloseHandle( pi.hThread );
413         }
414         else
415             MESSAGE("wine: Failed to start wineboot\n");
416     }
417
418     if (result) ExitProcess(0);
419     return TRUE;
420 }