user: Prefer SendMessageW over SendMessageA where possible.
[wine] / dlls / uxtheme / system.c
1 /*
2  * Win32 5.1 Theme system
3  *
4  * Copyright (C) 2003 Kevin Koltzau
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 "config.h"
22
23 #include <stdarg.h>
24 #include <stdio.h>
25
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winuser.h"
29 #include "wingdi.h"
30 #include "winreg.h"
31 #include "uxtheme.h"
32 #include "tmschema.h"
33
34 #include "uxthemedll.h"
35 #include "msstyles.h"
36
37 #include "wine/debug.h"
38
39 WINE_DEFAULT_DEBUG_CHANNEL(uxtheme);
40
41 /***********************************************************************
42  * Defines and global variables
43  */
44
45 static const WCHAR szThemeManager[] = {
46     'S','o','f','t','w','a','r','e','\\',
47     'M','i','c','r','o','s','o','f','t','\\',
48     'W','i','n','d','o','w','s','\\',
49     'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
50     'T','h','e','m','e','M','a','n','a','g','e','r','\0'
51 };
52 static const WCHAR szThemeActive[] = {'T','h','e','m','e','A','c','t','i','v','e','\0'};
53 static const WCHAR szSizeName[] = {'S','i','z','e','N','a','m','e','\0'};
54 static const WCHAR szColorName[] = {'C','o','l','o','r','N','a','m','e','\0'};
55 static const WCHAR szDllName[] = {'D','l','l','N','a','m','e','\0'};
56
57 static const WCHAR szIniDocumentation[] = {'d','o','c','u','m','e','n','t','a','t','i','o','n','\0'};
58
59 HINSTANCE hDllInst;
60
61 DWORD dwThemeAppProperties = STAP_ALLOW_NONCLIENT | STAP_ALLOW_CONTROLS;
62 ATOM atWindowTheme;
63 ATOM atSubAppName;
64 ATOM atSubIdList;
65 ATOM atDialogThemeEnabled;
66
67 BOOL bThemeActive = FALSE;
68 WCHAR szCurrentTheme[MAX_PATH];
69 WCHAR szCurrentColor[64];
70 WCHAR szCurrentSize[64];
71
72 /***********************************************************************/
73
74 static BOOL CALLBACK UXTHEME_broadcast_msg_enumchild (HWND hWnd, LPARAM msg)
75 {
76     PostMessageW(hWnd, msg, 0, 0);
77     return TRUE;
78 }
79
80 /* Broadcast a message to *all* windows, including children */
81 static BOOL CALLBACK UXTHEME_broadcast_msg (HWND hWnd, LPARAM msg)
82 {
83     if (hWnd == NULL)
84     {
85         EnumWindows (UXTHEME_broadcast_msg, msg);
86     }
87     else
88     {
89         PostMessageW(hWnd, msg, 0, 0);
90         EnumChildWindows (hWnd, UXTHEME_broadcast_msg_enumchild, msg);
91     }
92     return TRUE;
93 }
94
95 /* At the end of the day this is a subset of what SHRegGetPath() does - copied
96  * here to avoid linking against shlwapi. */
97 static DWORD query_reg_path (HKEY hKey, LPCWSTR lpszValue,
98                              LPVOID pvData)
99 {
100   DWORD dwRet, dwType, dwUnExpDataLen = MAX_PATH, dwExpDataLen;
101
102   TRACE("(hkey=%p,%s,%p)\n", hKey, debugstr_w(lpszValue),
103         pvData);
104
105   dwRet = RegQueryValueExW(hKey, lpszValue, 0, &dwType, pvData, &dwUnExpDataLen);
106   if (dwRet!=ERROR_SUCCESS && dwRet!=ERROR_MORE_DATA)
107       return dwRet;
108
109   if (dwType == REG_EXPAND_SZ)
110   {
111     DWORD nBytesToAlloc;
112
113     /* Expand type REG_EXPAND_SZ into REG_SZ */
114     LPWSTR szData;
115
116     /* If the caller didn't supply a buffer or the buffer is too small we have
117      * to allocate our own
118      */
119     if (dwRet == ERROR_MORE_DATA)
120     {
121       WCHAR cNull = '\0';
122       nBytesToAlloc = dwUnExpDataLen;
123
124       szData = (LPWSTR) LocalAlloc(LMEM_ZEROINIT, nBytesToAlloc);
125       RegQueryValueExW (hKey, lpszValue, 0, NULL, (LPBYTE)szData, &nBytesToAlloc);
126       dwExpDataLen = ExpandEnvironmentStringsW(szData, &cNull, 1);
127       dwUnExpDataLen = max(nBytesToAlloc, dwExpDataLen);
128       LocalFree((HLOCAL) szData);
129     }
130     else
131     {
132       nBytesToAlloc = (lstrlenW(pvData) + 1) * sizeof(WCHAR);
133       szData = (LPWSTR) LocalAlloc(LMEM_ZEROINIT, nBytesToAlloc );
134       lstrcpyW(szData, pvData);
135       dwExpDataLen = ExpandEnvironmentStringsW(szData, pvData, MAX_PATH );
136       if (dwExpDataLen > MAX_PATH) dwRet = ERROR_MORE_DATA;
137       dwUnExpDataLen = max(nBytesToAlloc, dwExpDataLen);
138       LocalFree((HLOCAL) szData);
139     }
140   }
141
142   RegCloseKey(hKey);
143   return dwRet;
144 }
145
146 /***********************************************************************
147  *      UXTHEME_LoadTheme
148  *
149  * Set the current active theme from the registry
150  */
151 static void UXTHEME_LoadTheme(void)
152 {
153     HKEY hKey;
154     DWORD buffsize;
155     HRESULT hr;
156     WCHAR tmp[10];
157     PTHEME_FILE pt;
158
159     /* Get current theme configuration */
160     if(!RegOpenKeyW(HKEY_CURRENT_USER, szThemeManager, &hKey)) {
161         TRACE("Loading theme config\n");
162         buffsize = sizeof(tmp)/sizeof(tmp[0]);
163         if(!RegQueryValueExW(hKey, szThemeActive, NULL, NULL, (LPBYTE)tmp, &buffsize)) {
164             bThemeActive = (tmp[0] != '0');
165         }
166         else {
167             bThemeActive = FALSE;
168             TRACE("Failed to get ThemeActive: %ld\n", GetLastError());
169         }
170         buffsize = sizeof(szCurrentColor)/sizeof(szCurrentColor[0]);
171         if(RegQueryValueExW(hKey, szColorName, NULL, NULL, (LPBYTE)szCurrentColor, &buffsize))
172             szCurrentColor[0] = '\0';
173         buffsize = sizeof(szCurrentSize)/sizeof(szCurrentSize[0]);
174         if(RegQueryValueExW(hKey, szSizeName, NULL, NULL, (LPBYTE)szCurrentSize, &buffsize))
175             szCurrentSize[0] = '\0';
176         if (query_reg_path (hKey, szDllName, szCurrentTheme))
177             szCurrentTheme[0] = '\0';
178         RegCloseKey(hKey);
179     }
180     else
181         TRACE("Failed to open theme registry key\n");
182
183     if(bThemeActive) {
184         /* Make sure the theme requested is actually valid */
185         hr = MSSTYLES_OpenThemeFile(szCurrentTheme,
186                                     szCurrentColor[0]?szCurrentColor:NULL,
187                                     szCurrentSize[0]?szCurrentSize:NULL,
188                                     &pt);
189         if(FAILED(hr)) {
190             bThemeActive = FALSE;
191             szCurrentTheme[0] = '\0';
192             szCurrentColor[0] = '\0';
193             szCurrentSize[0] = '\0';
194         }
195         else {
196             /* Make sure the global color & size match the theme */
197             lstrcpynW(szCurrentColor, pt->pszSelectedColor, sizeof(szCurrentColor)/sizeof(szCurrentColor[0]));
198             lstrcpynW(szCurrentSize, pt->pszSelectedSize, sizeof(szCurrentSize)/sizeof(szCurrentSize[0]));
199
200             MSSTYLES_SetActiveTheme(pt, FALSE);
201             TRACE("Theme active: %s %s %s\n", debugstr_w(szCurrentTheme),
202                 debugstr_w(szCurrentColor), debugstr_w(szCurrentSize));
203             MSSTYLES_CloseThemeFile(pt);
204         }
205     }
206     if(!bThemeActive) {
207         MSSTYLES_SetActiveTheme(NULL, FALSE);
208         TRACE("Themeing not active\n");
209     }
210 }
211
212 /***********************************************************************/
213
214 static const char * const SysColorsNames[] =
215 {
216     "Scrollbar",                /* COLOR_SCROLLBAR */
217     "Background",               /* COLOR_BACKGROUND */
218     "ActiveTitle",              /* COLOR_ACTIVECAPTION */
219     "InactiveTitle",            /* COLOR_INACTIVECAPTION */
220     "Menu",                     /* COLOR_MENU */
221     "Window",                   /* COLOR_WINDOW */
222     "WindowFrame",              /* COLOR_WINDOWFRAME */
223     "MenuText",                 /* COLOR_MENUTEXT */
224     "WindowText",               /* COLOR_WINDOWTEXT */
225     "TitleText",                /* COLOR_CAPTIONTEXT */
226     "ActiveBorder",             /* COLOR_ACTIVEBORDER */
227     "InactiveBorder",           /* COLOR_INACTIVEBORDER */
228     "AppWorkSpace",             /* COLOR_APPWORKSPACE */
229     "Hilight",                  /* COLOR_HIGHLIGHT */
230     "HilightText",              /* COLOR_HIGHLIGHTTEXT */
231     "ButtonFace",               /* COLOR_BTNFACE */
232     "ButtonShadow",             /* COLOR_BTNSHADOW */
233     "GrayText",                 /* COLOR_GRAYTEXT */
234     "ButtonText",               /* COLOR_BTNTEXT */
235     "InactiveTitleText",        /* COLOR_INACTIVECAPTIONTEXT */
236     "ButtonHilight",            /* COLOR_BTNHIGHLIGHT */
237     "ButtonDkShadow",           /* COLOR_3DDKSHADOW */
238     "ButtonLight",              /* COLOR_3DLIGHT */
239     "InfoText",                 /* COLOR_INFOTEXT */
240     "InfoWindow",               /* COLOR_INFOBK */
241     "ButtonAlternateFace",      /* COLOR_ALTERNATEBTNFACE */
242     "HotTrackingColor",         /* COLOR_HOTLIGHT */
243     "GradientActiveTitle",      /* COLOR_GRADIENTACTIVECAPTION */
244     "GradientInactiveTitle",    /* COLOR_GRADIENTINACTIVECAPTION */
245     "MenuHilight",              /* COLOR_MENUHILIGHT */
246     "MenuBar",                  /* COLOR_MENUBAR */
247 };
248 static const WCHAR strColorKey[] = 
249     { 'C','o','n','t','r','o','l',' ','P','a','n','e','l','\\',
250       'C','o','l','o','r','s',0 };
251 static const WCHAR keyFlatMenus[] = { 'F','l','a','t','M','e','n','u', 0};
252
253 static const struct BackupSysParam
254 {
255     int spiGet, spiSet;
256     const WCHAR* keyName;
257 } backupSysParams[] = 
258 {
259     {SPI_GETFLATMENU, SPI_SETFLATMENU, keyFlatMenus},
260     {-1, -1, 0}
261 };
262
263 #define NUM_SYS_COLORS     (COLOR_MENUBAR+1)
264
265 static void save_sys_colors (HKEY baseKey)
266 {
267     char colorStr[13];
268     HKEY hKey;
269     int i;
270
271     if (RegCreateKeyExW( baseKey, strColorKey,
272                          0, 0, 0, KEY_ALL_ACCESS,
273                          0, &hKey, 0 ) == ERROR_SUCCESS)
274     {
275         for (i = 0; i < NUM_SYS_COLORS; i++)
276         {
277             COLORREF col = GetSysColor (i);
278         
279             sprintf (colorStr, "%d %d %d", 
280                 GetRValue (col), GetGValue (col), GetBValue (col));
281
282             RegSetValueExA (hKey, SysColorsNames[i], 0, REG_SZ, 
283                 (BYTE*)colorStr, strlen (colorStr)+1);
284         }
285         RegCloseKey (hKey);
286     }
287 }
288
289 /* Before activating a theme, query current system colors, certain settings 
290  * and backup them in the registry, so they can be restored when the theme 
291  * is deactivated */
292 static void UXTHEME_BackupSystemMetrics(void)
293 {
294     HKEY hKey;
295     const struct BackupSysParam* bsp = backupSysParams;
296
297     if (RegCreateKeyExW( HKEY_CURRENT_USER, szThemeManager,
298                          0, 0, 0, KEY_ALL_ACCESS,
299                          0, &hKey, 0) == ERROR_SUCCESS)
300     {
301         save_sys_colors (hKey);
302     
303         while (bsp->spiGet >= 0)
304         {
305             DWORD value;
306             
307             SystemParametersInfoW (bsp->spiGet, 0, &value, 0);
308             RegSetValueExW (hKey, bsp->keyName, 0, REG_DWORD, 
309                 (LPBYTE)&value, sizeof (value));
310         
311             bsp++;
312         }
313     
314         RegCloseKey (hKey);
315     }
316 }
317
318 /* Read back old settings after a theme was deactivated */
319 static void UXTHEME_RestoreSystemMetrics(void)
320 {
321     HKEY hKey;
322     const struct BackupSysParam* bsp = backupSysParams;
323
324     if (RegOpenKeyExW (HKEY_CURRENT_USER, szThemeManager,
325                        0, KEY_QUERY_VALUE, &hKey) == ERROR_SUCCESS) 
326     {
327         HKEY colorKey;
328     
329         /* read backed-up colors */
330         if (RegOpenKeyExW (hKey, strColorKey,
331                            0, KEY_QUERY_VALUE, &colorKey) == ERROR_SUCCESS) 
332         {
333             int i;
334             COLORREF sysCols[NUM_SYS_COLORS];
335             int sysColsIndices[NUM_SYS_COLORS];
336             int sysColCount = 0;
337         
338             for (i = 0; i < NUM_SYS_COLORS; i++)
339             {
340                 DWORD type;
341                 char colorStr[13];
342                 DWORD count = sizeof(colorStr);
343             
344                 if (RegQueryValueExA (colorKey, SysColorsNames[i], 0,
345                     &type, (LPBYTE) colorStr, &count) == ERROR_SUCCESS)
346                 {
347                     int r, g, b;
348                     if (sscanf (colorStr, "%d %d %d", &r, &g, &b) == 3)
349                     {
350                         sysColsIndices[sysColCount] = i;
351                         sysCols[sysColCount] = RGB(r, g, b);
352                         sysColCount++;
353                     }
354                 }
355             }
356             RegCloseKey (colorKey);
357           
358             SetSysColors (sysColCount, sysColsIndices, sysCols);
359         }
360     
361         /* read backed-up other settings */
362         while (bsp->spiGet >= 0)
363         {
364             DWORD value;
365             DWORD count = sizeof(value);
366             DWORD type;
367             
368             if (RegQueryValueExW (hKey, bsp->keyName, 0,
369                 &type, (LPBYTE)&value, &count) == ERROR_SUCCESS)
370             {
371                 SystemParametersInfoW (bsp->spiSet, 0, (LPVOID)value,
372                     SPIF_UPDATEINIFILE);
373             }
374         
375             bsp++;
376         }
377     
378       
379         RegCloseKey (hKey);
380     }
381 }
382
383 /* Make system settings persistent, so they're in effect even w/o uxtheme 
384  * loaded */
385 static void UXTHEME_SaveSystemMetrics(void)
386 {
387     const struct BackupSysParam* bsp = backupSysParams;
388
389     save_sys_colors (HKEY_CURRENT_USER);
390
391     while (bsp->spiGet >= 0)
392     {
393         DWORD value;
394         
395         SystemParametersInfoW (bsp->spiGet, 0, &value, 0);
396         SystemParametersInfoW (bsp->spiSet, 0, (LPVOID)value,
397             SPIF_UPDATEINIFILE);
398     
399         bsp++;
400     }
401
402 }
403
404 /***********************************************************************
405  *      UXTHEME_SetActiveTheme
406  *
407  * Change the current active theme
408  */
409 HRESULT UXTHEME_SetActiveTheme(PTHEME_FILE tf)
410 {
411     HKEY hKey;
412     WCHAR tmp[2];
413     HRESULT hr;
414
415     if(tf) UXTHEME_BackupSystemMetrics();
416     hr = MSSTYLES_SetActiveTheme(tf, TRUE);
417     if(FAILED(hr))
418         return hr;
419     if(tf) {
420         bThemeActive = TRUE;
421         lstrcpynW(szCurrentTheme, tf->szThemeFile, sizeof(szCurrentTheme)/sizeof(szCurrentTheme[0]));
422         lstrcpynW(szCurrentColor, tf->pszSelectedColor, sizeof(szCurrentColor)/sizeof(szCurrentColor[0]));
423         lstrcpynW(szCurrentSize, tf->pszSelectedSize, sizeof(szCurrentSize)/sizeof(szCurrentSize[0]));
424     }
425     else {
426         UXTHEME_RestoreSystemMetrics();
427         bThemeActive = FALSE;
428         szCurrentTheme[0] = '\0';
429         szCurrentColor[0] = '\0';
430         szCurrentSize[0] = '\0';
431     }
432
433     TRACE("Writing theme config to registry\n");
434     if(!RegCreateKeyW(HKEY_CURRENT_USER, szThemeManager, &hKey)) {
435         tmp[0] = bThemeActive?'1':'0';
436         tmp[1] = '\0';
437         RegSetValueExW(hKey, szThemeActive, 0, REG_SZ, (const BYTE*)tmp, sizeof(WCHAR)*2);
438         if(bThemeActive) {
439             RegSetValueExW(hKey, szColorName, 0, REG_SZ, (const BYTE*)szCurrentColor, 
440                 (lstrlenW(szCurrentColor)+1)*sizeof(WCHAR));
441             RegSetValueExW(hKey, szSizeName, 0, REG_SZ, (const BYTE*)szCurrentSize, 
442                 (lstrlenW(szCurrentSize)+1)*sizeof(WCHAR));
443             RegSetValueExW(hKey, szDllName, 0, REG_SZ, (const BYTE*)szCurrentTheme, 
444                 (lstrlenW(szCurrentTheme)+1)*sizeof(WCHAR));
445         }
446         else {
447             RegDeleteValueW(hKey, szColorName);
448             RegDeleteValueW(hKey, szSizeName);
449             RegDeleteValueW(hKey, szDllName);
450
451         }
452         RegCloseKey(hKey);
453     }
454     else
455         TRACE("Failed to open theme registry key\n");
456     
457     UXTHEME_SaveSystemMetrics ();
458     
459     return hr;
460 }
461
462 /***********************************************************************
463  *      UXTHEME_InitSystem
464  */
465 void UXTHEME_InitSystem(HINSTANCE hInst)
466 {
467     static const WCHAR szWindowTheme[] = {
468         'u','x','_','t','h','e','m','e','\0'
469     };
470     static const WCHAR szSubAppName[] = {
471         'u','x','_','s','u','b','a','p','p','\0'
472     };
473     static const WCHAR szSubIdList[] = {
474         'u','x','_','s','u','b','i','d','l','s','t','\0'
475     };
476     static const WCHAR szDialogThemeEnabled[] = {
477         'u','x','_','d','i','a','l','o','g','t','h','e','m','e','\0'
478     };
479
480     hDllInst = hInst;
481
482     atWindowTheme        = GlobalAddAtomW(szWindowTheme);
483     atSubAppName         = GlobalAddAtomW(szSubAppName);
484     atSubIdList          = GlobalAddAtomW(szSubIdList);
485     atDialogThemeEnabled = GlobalAddAtomW(szDialogThemeEnabled);
486
487     UXTHEME_LoadTheme();
488 }
489
490 /***********************************************************************
491  *      IsAppThemed                                         (UXTHEME.@)
492  */
493 BOOL WINAPI IsAppThemed(void)
494 {
495     return IsThemeActive();
496 }
497
498 /***********************************************************************
499  *      IsThemeActive                                       (UXTHEME.@)
500  */
501 BOOL WINAPI IsThemeActive(void)
502 {
503     TRACE("\n");
504     return bThemeActive;
505 }
506
507 /***********************************************************************
508  *      EnableTheming                                       (UXTHEME.@)
509  *
510  * NOTES
511  * This is a global and persistent change
512  */
513 HRESULT WINAPI EnableTheming(BOOL fEnable)
514 {
515     HKEY hKey;
516     WCHAR szEnabled[] = {'0','\0'};
517
518     TRACE("(%d)\n", fEnable);
519
520     if(fEnable != bThemeActive) {
521         if(fEnable) 
522             UXTHEME_BackupSystemMetrics();
523         else
524             UXTHEME_RestoreSystemMetrics();
525         UXTHEME_SaveSystemMetrics ();
526         bThemeActive = fEnable;
527         if(bThemeActive) szEnabled[0] = '1';
528         if(!RegOpenKeyW(HKEY_CURRENT_USER, szThemeManager, &hKey)) {
529             RegSetValueExW(hKey, szThemeActive, 0, REG_SZ, (LPBYTE)szEnabled, sizeof(WCHAR));
530             RegCloseKey(hKey);
531         }
532         UXTHEME_broadcast_msg (NULL, WM_THEMECHANGED);
533     }
534     return S_OK;
535 }
536
537 /***********************************************************************
538  *      UXTHEME_SetWindowProperty
539  *
540  * I'm using atoms as there may be large numbers of duplicated strings
541  * and they do the work of keeping memory down as a cause of that quite nicely
542  */
543 HRESULT UXTHEME_SetWindowProperty(HWND hwnd, ATOM aProp, LPCWSTR pszValue)
544 {
545     ATOM oldValue = (ATOM)(size_t)RemovePropW(hwnd, MAKEINTATOMW(aProp));
546     if(oldValue)
547         DeleteAtom(oldValue);
548     if(pszValue) {
549         ATOM atValue = AddAtomW(pszValue);
550         if(!atValue
551            || !SetPropW(hwnd, MAKEINTATOMW(aProp), (LPWSTR)MAKEINTATOMW(atValue))) {
552             HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
553             if(atValue) DeleteAtom(atValue);
554             return hr;
555         }
556     }
557     return S_OK;
558 }
559
560 LPWSTR UXTHEME_GetWindowProperty(HWND hwnd, ATOM aProp, LPWSTR pszBuffer, int dwLen)
561 {
562     ATOM atValue = (ATOM)(size_t)GetPropW(hwnd, MAKEINTATOMW(aProp));
563     if(atValue) {
564         if(GetAtomNameW(atValue, pszBuffer, dwLen))
565             return pszBuffer;
566         TRACE("property defined, but unable to get value\n");
567     }
568     return NULL;
569 }
570
571 /***********************************************************************
572  *      OpenThemeData                                       (UXTHEME.@)
573  */
574 HTHEME WINAPI OpenThemeData(HWND hwnd, LPCWSTR pszClassList)
575 {
576     WCHAR szAppBuff[256];
577     WCHAR szClassBuff[256];
578     LPCWSTR pszAppName;
579     LPCWSTR pszUseClassList;
580     HTHEME hTheme = NULL;
581     TRACE("(%p,%s)", hwnd, debugstr_w(pszClassList));
582
583     if(bThemeActive)
584     {
585         pszAppName = UXTHEME_GetWindowProperty(hwnd, atSubAppName, szAppBuff, sizeof(szAppBuff)/sizeof(szAppBuff[0]));
586         /* If SetWindowTheme was used on the window, that overrides the class list passed to this function */
587         pszUseClassList = UXTHEME_GetWindowProperty(hwnd, atSubIdList, szClassBuff, sizeof(szClassBuff)/sizeof(szClassBuff[0]));
588         if(!pszUseClassList)
589             pszUseClassList = pszClassList;
590
591         if (pszUseClassList)
592             hTheme = MSSTYLES_OpenThemeClass(pszAppName, pszUseClassList);
593     }
594     if(IsWindow(hwnd))
595         SetPropW(hwnd, MAKEINTATOMW(atWindowTheme), hTheme);
596     TRACE(" = %p\n", hTheme);
597     return hTheme;
598 }
599
600 /***********************************************************************
601  *      GetWindowTheme                                      (UXTHEME.@)
602  *
603  * Retrieve the last theme opened for a window.
604  *
605  * PARAMS
606  *  hwnd  [I] window to retrieve the theme for
607  *
608  * RETURNS
609  *  The most recent theme.
610  */
611 HTHEME WINAPI GetWindowTheme(HWND hwnd)
612 {
613     TRACE("(%p)\n", hwnd);
614     return GetPropW(hwnd, MAKEINTATOMW(atWindowTheme));
615 }
616
617 /***********************************************************************
618  *      SetWindowTheme                                      (UXTHEME.@)
619  *
620  * Persistent through the life of the window, even after themes change
621  */
622 HRESULT WINAPI SetWindowTheme(HWND hwnd, LPCWSTR pszSubAppName,
623                               LPCWSTR pszSubIdList)
624 {
625     HRESULT hr;
626     TRACE("(%p,%s,%s)\n", hwnd, debugstr_w(pszSubAppName),
627           debugstr_w(pszSubIdList));
628     hr = UXTHEME_SetWindowProperty(hwnd, atSubAppName, pszSubAppName);
629     if(SUCCEEDED(hr))
630         hr = UXTHEME_SetWindowProperty(hwnd, atSubIdList, pszSubIdList);
631     if(SUCCEEDED(hr))
632         UXTHEME_broadcast_msg (hwnd, WM_THEMECHANGED);
633     return hr;
634 }
635
636 /***********************************************************************
637  *      GetCurrentThemeName                                 (UXTHEME.@)
638  */
639 HRESULT WINAPI GetCurrentThemeName(LPWSTR pszThemeFileName, int dwMaxNameChars,
640                                    LPWSTR pszColorBuff, int cchMaxColorChars,
641                                    LPWSTR pszSizeBuff, int cchMaxSizeChars)
642 {
643     if(!bThemeActive)
644         return E_PROP_ID_UNSUPPORTED;
645     if(pszThemeFileName) lstrcpynW(pszThemeFileName, szCurrentTheme, dwMaxNameChars);
646     if(pszColorBuff) lstrcpynW(pszColorBuff, szCurrentColor, cchMaxColorChars);
647     if(pszSizeBuff) lstrcpynW(pszSizeBuff, szCurrentSize, cchMaxSizeChars);
648     return S_OK;
649 }
650
651 /***********************************************************************
652  *      GetThemeAppProperties                               (UXTHEME.@)
653  */
654 DWORD WINAPI GetThemeAppProperties(void)
655 {
656     return dwThemeAppProperties;
657 }
658
659 /***********************************************************************
660  *      SetThemeAppProperties                               (UXTHEME.@)
661  */
662 void WINAPI SetThemeAppProperties(DWORD dwFlags)
663 {
664     TRACE("(0x%08lx)\n", dwFlags);
665     dwThemeAppProperties = dwFlags;
666 }
667
668 /***********************************************************************
669  *      CloseThemeData                                      (UXTHEME.@)
670  */
671 HRESULT WINAPI CloseThemeData(HTHEME hTheme)
672 {
673     TRACE("(%p)\n", hTheme);
674     if(!hTheme)
675         return E_HANDLE;
676     return MSSTYLES_CloseThemeClass(hTheme);
677 }
678
679 /***********************************************************************
680  *      HitTestThemeBackground                              (UXTHEME.@)
681  */
682 HRESULT WINAPI HitTestThemeBackground(HTHEME hTheme, HDC hdc, int iPartId,
683                                      int iStateId, DWORD dwOptions,
684                                      const RECT *pRect, HRGN hrgn,
685                                      POINT ptTest, WORD *pwHitTestCode)
686 {
687     FIXME("%d %d 0x%08lx: stub\n", iPartId, iStateId, dwOptions);
688     if(!hTheme)
689         return E_HANDLE;
690     return ERROR_CALL_NOT_IMPLEMENTED;
691 }
692
693 /***********************************************************************
694  *      IsThemePartDefined                                  (UXTHEME.@)
695  */
696 BOOL WINAPI IsThemePartDefined(HTHEME hTheme, int iPartId, int iStateId)
697 {
698     TRACE("(%p,%d,%d)\n", hTheme, iPartId, iStateId);
699     if(!hTheme) {
700         SetLastError(E_HANDLE);
701         return FALSE;
702     }
703     if(MSSTYLES_FindPartState(hTheme, iPartId, iStateId, NULL))
704         return TRUE;
705     return FALSE;
706 }
707
708 /***********************************************************************
709  *      GetThemeDocumentationProperty                       (UXTHEME.@)
710  *
711  * Try and retrieve the documentation property from string resources
712  * if that fails, get it from the [documentation] section of themes.ini
713  */
714 HRESULT WINAPI GetThemeDocumentationProperty(LPCWSTR pszThemeName,
715                                              LPCWSTR pszPropertyName,
716                                              LPWSTR pszValueBuff,
717                                              int cchMaxValChars)
718 {
719     const WORD wDocToRes[] = {
720         TMT_DISPLAYNAME,5000,
721         TMT_TOOLTIP,5001,
722         TMT_COMPANY,5002,
723         TMT_AUTHOR,5003,
724         TMT_COPYRIGHT,5004,
725         TMT_URL,5005,
726         TMT_VERSION,5006,
727         TMT_DESCRIPTION,5007
728     };
729
730     PTHEME_FILE pt;
731     HRESULT hr;
732     unsigned int i;
733     int iDocId;
734     TRACE("(%s,%s,%p,%d)\n", debugstr_w(pszThemeName), debugstr_w(pszPropertyName),
735           pszValueBuff, cchMaxValChars);
736
737     hr = MSSTYLES_OpenThemeFile(pszThemeName, NULL, NULL, &pt);
738     if(FAILED(hr)) return hr;
739
740     /* Try to load from string resources */
741     hr = E_PROP_ID_UNSUPPORTED;
742     if(MSSTYLES_LookupProperty(pszPropertyName, NULL, &iDocId)) {
743         for(i=0; i<sizeof(wDocToRes)/sizeof(wDocToRes[0]); i+=2) {
744             if(wDocToRes[i] == iDocId) {
745                 if(LoadStringW(pt->hTheme, wDocToRes[i+1], pszValueBuff, cchMaxValChars)) {
746                     hr = S_OK;
747                     break;
748                 }
749             }
750         }
751     }
752     /* If loading from string resource failed, try getting it from the theme.ini */
753     if(FAILED(hr)) {
754         PUXINI_FILE uf = MSSTYLES_GetThemeIni(pt);
755         if(UXINI_FindSection(uf, szIniDocumentation)) {
756             LPCWSTR lpValue;
757             DWORD dwLen;
758             if(UXINI_FindValue(uf, pszPropertyName, &lpValue, &dwLen)) {
759                 lstrcpynW(pszValueBuff, lpValue, min(dwLen+1,cchMaxValChars));
760                 hr = S_OK;
761             }
762         }
763         UXINI_CloseINI(uf);
764     }
765
766     MSSTYLES_CloseThemeFile(pt);
767     return hr;
768 }
769
770 /**********************************************************************
771  *      Undocumented functions
772  */
773
774 /**********************************************************************
775  *      QueryThemeServices                                 (UXTHEME.1)
776  *
777  * RETURNS
778  *     some kind of status flag
779  */
780 DWORD WINAPI QueryThemeServices()
781 {
782     FIXME("stub\n");
783     return 3; /* This is what is returned under XP in most cases */
784 }
785
786
787 /**********************************************************************
788  *      OpenThemeFile                                      (UXTHEME.2)
789  *
790  * Opens a theme file, which can be used to change the current theme, etc
791  *
792  * PARAMS
793  *     pszThemeFileName    Path to a msstyles theme file
794  *     pszColorName        Color defined in the theme, eg. NormalColor
795  *     pszSizeName         Size defined in the theme, eg. NormalSize
796  *     hThemeFile          Handle to theme file
797  *
798  * RETURNS
799  *     Success: S_OK
800  *     Failure: HRESULT error-code
801  */
802 HRESULT WINAPI OpenThemeFile(LPCWSTR pszThemeFileName, LPCWSTR pszColorName,
803                              LPCWSTR pszSizeName, HTHEMEFILE *hThemeFile,
804                              DWORD unknown)
805 {
806     TRACE("(%s,%s,%s,%p,%ld)\n", debugstr_w(pszThemeFileName),
807           debugstr_w(pszColorName), debugstr_w(pszSizeName),
808           hThemeFile, unknown);
809     return MSSTYLES_OpenThemeFile(pszThemeFileName, pszColorName, pszSizeName, (PTHEME_FILE*)hThemeFile);
810 }
811
812 /**********************************************************************
813  *      CloseThemeFile                                     (UXTHEME.3)
814  *
815  * Releases theme file handle returned by OpenThemeFile
816  *
817  * PARAMS
818  *     hThemeFile           Handle to theme file
819  *
820  * RETURNS
821  *     Success: S_OK
822  *     Failure: HRESULT error-code
823  */
824 HRESULT WINAPI CloseThemeFile(HTHEMEFILE hThemeFile)
825 {
826     TRACE("(%p)\n", hThemeFile);
827     MSSTYLES_CloseThemeFile(hThemeFile);
828     return S_OK;
829 }
830
831 /**********************************************************************
832  *      ApplyTheme                                         (UXTHEME.4)
833  *
834  * Set a theme file to be the currently active theme
835  *
836  * PARAMS
837  *     hThemeFile           Handle to theme file
838  *     unknown              See notes
839  *     hWnd                 Window requesting the theme change
840  *
841  * RETURNS
842  *     Success: S_OK
843  *     Failure: HRESULT error-code
844  *
845  * NOTES
846  * I'm not sure what the second parameter is (the datatype is likely wrong), other then this:
847  * Under XP if I pass
848  * char b[] = "";
849  *   the theme is applied with the screen redrawing really badly (flickers)
850  * char b[] = "\0"; where \0 can be one or more of any character, makes no difference
851  *   the theme is applied smoothly (screen does not flicker)
852  * char *b = "\0" or NULL; where \0 can be zero or more of any character, makes no difference
853  *   the function fails returning invalid parameter...very strange
854  */
855 HRESULT WINAPI ApplyTheme(HTHEMEFILE hThemeFile, char *unknown, HWND hWnd)
856 {
857     HRESULT hr;
858     TRACE("(%p,%s,%p)\n", hThemeFile, unknown, hWnd);
859     hr = UXTHEME_SetActiveTheme(hThemeFile);
860     UXTHEME_broadcast_msg (NULL, WM_THEMECHANGED);
861     return hr;
862 }
863
864 /**********************************************************************
865  *      GetThemeDefaults                                   (UXTHEME.7)
866  *
867  * Get the default color & size for a theme
868  *
869  * PARAMS
870  *     pszThemeFileName    Path to a msstyles theme file
871  *     pszColorName        Buffer to receive the default color name
872  *     dwColorNameLen      Length, in characters, of color name buffer
873  *     pszSizeName         Buffer to receive the default size name
874  *     dwSizeNameLen       Length, in characters, of size name buffer
875  *
876  * RETURNS
877  *     Success: S_OK
878  *     Failure: HRESULT error-code
879  */
880 HRESULT WINAPI GetThemeDefaults(LPCWSTR pszThemeFileName, LPWSTR pszColorName,
881                                 DWORD dwColorNameLen, LPWSTR pszSizeName,
882                                 DWORD dwSizeNameLen)
883 {
884     PTHEME_FILE pt;
885     HRESULT hr;
886     TRACE("(%s,%p,%ld,%p,%ld)\n", debugstr_w(pszThemeFileName),
887           pszColorName, dwColorNameLen,
888           pszSizeName, dwSizeNameLen);
889
890     hr = MSSTYLES_OpenThemeFile(pszThemeFileName, NULL, NULL, &pt);
891     if(FAILED(hr)) return hr;
892
893     lstrcpynW(pszColorName, pt->pszSelectedColor, dwColorNameLen);
894     lstrcpynW(pszSizeName, pt->pszSelectedSize, dwSizeNameLen);
895
896     MSSTYLES_CloseThemeFile(pt);
897     return S_OK;
898 }
899
900 /**********************************************************************
901  *      EnumThemes                                         (UXTHEME.8)
902  *
903  * Enumerate available themes, calls specified EnumThemeProc for each
904  * theme found. Passes lpData through to callback function.
905  *
906  * PARAMS
907  *     pszThemePath        Path containing themes
908  *     callback            Called for each theme found in path
909  *     lpData              Passed through to callback
910  *
911  * RETURNS
912  *     Success: S_OK
913  *     Failure: HRESULT error-code
914  */
915 HRESULT WINAPI EnumThemes(LPCWSTR pszThemePath, EnumThemeProc callback,
916                           LPVOID lpData)
917 {
918     WCHAR szDir[MAX_PATH];
919     WCHAR szPath[MAX_PATH];
920     static const WCHAR szStar[] = {'*','.','*','\0'};
921     static const WCHAR szFormat[] = {'%','s','%','s','\\','%','s','.','m','s','s','t','y','l','e','s','\0'};
922     static const WCHAR szDisplayName[] = {'d','i','s','p','l','a','y','n','a','m','e','\0'};
923     static const WCHAR szTooltip[] = {'t','o','o','l','t','i','p','\0'};
924     WCHAR szName[60];
925     WCHAR szTip[60];
926     HANDLE hFind;
927     WIN32_FIND_DATAW wfd;
928     HRESULT hr;
929     size_t pathLen;
930
931     TRACE("(%s,%p,%p)\n", debugstr_w(pszThemePath), callback, lpData);
932
933     if(!pszThemePath || !callback)
934         return E_POINTER;
935
936     lstrcpyW(szDir, pszThemePath);
937     pathLen = lstrlenW (szDir);
938     if ((pathLen > 0) && (pathLen < MAX_PATH-1) && (szDir[pathLen - 1] != '\\'))
939     {
940         szDir[pathLen] = '\\';
941         szDir[pathLen+1] = 0;
942     }
943
944     lstrcpyW(szPath, szDir);
945     lstrcatW(szPath, szStar);
946     TRACE("searching %s\n", debugstr_w(szPath));
947
948     hFind = FindFirstFileW(szPath, &wfd);
949     if(hFind != INVALID_HANDLE_VALUE) {
950         do {
951             if(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
952                && !(wfd.cFileName[0] == '.' && ((wfd.cFileName[1] == '.' && wfd.cFileName[2] == 0) || wfd.cFileName[1] == 0))) {
953                 wsprintfW(szPath, szFormat, szDir, wfd.cFileName, wfd.cFileName);
954
955                 hr = GetThemeDocumentationProperty(szPath, szDisplayName, szName, sizeof(szName)/sizeof(szName[0]));
956                 if(SUCCEEDED(hr))
957                     hr = GetThemeDocumentationProperty(szPath, szTooltip, szTip, sizeof(szTip)/sizeof(szTip[0]));
958                 if(SUCCEEDED(hr)) {
959                     TRACE("callback(%s,%s,%s,%p)\n", debugstr_w(szPath), debugstr_w(szName), debugstr_w(szTip), lpData);
960                     if(!callback(NULL, szPath, szName, szTip, NULL, lpData)) {
961                         TRACE("callback ended enum\n");
962                         break;
963                     }
964                 }
965             }
966         } while(FindNextFileW(hFind, &wfd));
967         FindClose(hFind);
968     }
969     return S_OK;
970 }
971
972
973 /**********************************************************************
974  *      EnumThemeColors                                    (UXTHEME.9)
975  *
976  * Enumerate theme colors available with a particular size
977  *
978  * PARAMS
979  *     pszThemeFileName    Path to a msstyles theme file
980  *     pszSizeName         Theme size to enumerate available colors
981  *                         If NULL the default theme size is used
982  *     dwColorNum          Color index to retrieve, increment from 0
983  *     pszColorNames       Output color names
984  *
985  * RETURNS
986  *     S_OK on success
987  *     E_PROP_ID_UNSUPPORTED when dwColorName does not refer to a color
988  *          or when pszSizeName does not refer to a valid size
989  *
990  * NOTES
991  * XP fails with E_POINTER when pszColorNames points to a buffer smaller than 
992  * sizeof(THEMENAMES).
993  *
994  * Not very efficient that I'm opening & validating the theme every call, but
995  * this is undocumented and almost never called..
996  * (and this is how windows works too)
997  */
998 HRESULT WINAPI EnumThemeColors(LPWSTR pszThemeFileName, LPWSTR pszSizeName,
999                                DWORD dwColorNum, PTHEMENAMES pszColorNames)
1000 {
1001     PTHEME_FILE pt;
1002     HRESULT hr;
1003     LPWSTR tmp;
1004     UINT resourceId = dwColorNum + 1000;
1005     TRACE("(%s,%s,%ld)\n", debugstr_w(pszThemeFileName),
1006           debugstr_w(pszSizeName), dwColorNum);
1007
1008     hr = MSSTYLES_OpenThemeFile(pszThemeFileName, NULL, pszSizeName, &pt);
1009     if(FAILED(hr)) return hr;
1010
1011     tmp = pt->pszAvailColors;
1012     while(dwColorNum && *tmp) {
1013         dwColorNum--;
1014         tmp += lstrlenW(tmp)+1;
1015     }
1016     if(!dwColorNum && *tmp) {
1017         TRACE("%s\n", debugstr_w(tmp));
1018         lstrcpyW(pszColorNames->szName, tmp);
1019         LoadStringW (pt->hTheme, resourceId,
1020             pszColorNames->szDisplayName,
1021             sizeof (pszColorNames->szDisplayName) / sizeof (WCHAR));
1022         LoadStringW (pt->hTheme, resourceId+1000,
1023             pszColorNames->szTooltip,
1024             sizeof (pszColorNames->szTooltip) / sizeof (WCHAR));
1025     }
1026     else
1027         hr = E_PROP_ID_UNSUPPORTED;
1028
1029     MSSTYLES_CloseThemeFile(pt);
1030     return hr;
1031 }
1032
1033 /**********************************************************************
1034  *      EnumThemeSizes                                     (UXTHEME.10)
1035  *
1036  * Enumerate theme colors available with a particular size
1037  *
1038  * PARAMS
1039  *     pszThemeFileName    Path to a msstyles theme file
1040  *     pszColorName        Theme color to enumerate available sizes
1041  *                         If NULL the default theme color is used
1042  *     dwSizeNum           Size index to retrieve, increment from 0
1043  *     pszSizeNames        Output size names
1044  *
1045  * RETURNS
1046  *     S_OK on success
1047  *     E_PROP_ID_UNSUPPORTED when dwSizeName does not refer to a size
1048  *          or when pszColorName does not refer to a valid color
1049  *
1050  * NOTES
1051  * XP fails with E_POINTER when pszSizeNames points to a buffer smaller than 
1052  * sizeof(THEMENAMES).
1053  *
1054  * Not very efficient that I'm opening & validating the theme every call, but
1055  * this is undocumented and almost never called..
1056  * (and this is how windows works too)
1057  */
1058 HRESULT WINAPI EnumThemeSizes(LPWSTR pszThemeFileName, LPWSTR pszColorName,
1059                               DWORD dwSizeNum, PTHEMENAMES pszSizeNames)
1060 {
1061     PTHEME_FILE pt;
1062     HRESULT hr;
1063     LPWSTR tmp;
1064     UINT resourceId = dwSizeNum + 3000;
1065     TRACE("(%s,%s,%ld)\n", debugstr_w(pszThemeFileName),
1066           debugstr_w(pszColorName), dwSizeNum);
1067
1068     hr = MSSTYLES_OpenThemeFile(pszThemeFileName, pszColorName, NULL, &pt);
1069     if(FAILED(hr)) return hr;
1070
1071     tmp = pt->pszAvailSizes;
1072     while(dwSizeNum && *tmp) {
1073         dwSizeNum--;
1074         tmp += lstrlenW(tmp)+1;
1075     }
1076     if(!dwSizeNum && *tmp) {
1077         TRACE("%s\n", debugstr_w(tmp));
1078         lstrcpyW(pszSizeNames->szName, tmp);
1079         LoadStringW (pt->hTheme, resourceId,
1080             pszSizeNames->szDisplayName,
1081             sizeof (pszSizeNames->szDisplayName) / sizeof (WCHAR));
1082         LoadStringW (pt->hTheme, resourceId+1000,
1083             pszSizeNames->szTooltip,
1084             sizeof (pszSizeNames->szTooltip) / sizeof (WCHAR));
1085     }
1086     else
1087         hr = E_PROP_ID_UNSUPPORTED;
1088
1089     MSSTYLES_CloseThemeFile(pt);
1090     return hr;
1091 }
1092
1093 /**********************************************************************
1094  *      ParseThemeIniFile                                  (UXTHEME.11)
1095  *
1096  * Enumerate data in a theme INI file.
1097  *
1098  * PARAMS
1099  *     pszIniFileName      Path to a theme ini file
1100  *     pszUnknown          Cannot be NULL, L"" is valid
1101  *     callback            Called for each found entry
1102  *     lpData              Passed through to callback
1103  *
1104  * RETURNS
1105  *     S_OK on success
1106  *     0x800706488 (Unknown property) when enumeration is canceled from callback
1107  *
1108  * NOTES
1109  * When pszUnknown is NULL the callback is never called, the value does not seem to surve
1110  * any other purpose
1111  */
1112 HRESULT WINAPI ParseThemeIniFile(LPCWSTR pszIniFileName, LPWSTR pszUnknown,
1113                                  ParseThemeIniFileProc callback, LPVOID lpData)
1114 {
1115     FIXME("%s %s: stub\n", debugstr_w(pszIniFileName), debugstr_w(pszUnknown));
1116     return ERROR_CALL_NOT_IMPLEMENTED;
1117 }
1118
1119 /**********************************************************************
1120  *      CheckThemeSignature                                (UXTHEME.29)
1121  *
1122  * Validates the signature of a theme file
1123  *
1124  * PARAMS
1125  *     pszIniFileName      Path to a theme file
1126  *
1127  * RETURNS
1128  *     Success: S_OK
1129  *     Failure: HRESULT error-code
1130  */
1131 HRESULT WINAPI CheckThemeSignature(LPCWSTR pszThemeFileName)
1132 {
1133     PTHEME_FILE pt;
1134     HRESULT hr;
1135     TRACE("(%s)\n", debugstr_w(pszThemeFileName));
1136     hr = MSSTYLES_OpenThemeFile(pszThemeFileName, NULL, NULL, &pt);
1137     if(FAILED(hr))
1138         return hr;
1139     MSSTYLES_CloseThemeFile(pt);
1140     return S_OK;
1141 }