1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: msw/registry.cpp
3 // Purpose: implementation of registry classes and functions
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 // TODO: - parsing of registry key names
11 // - support of other (than REG_SZ/REG_DWORD) registry types
12 // - add high level functions (RegisterOleServer, ...)
13 ///////////////////////////////////////////////////////////////////////////////
15 // ============================================================================
17 // ============================================================================
19 // ----------------------------------------------------------------------------
21 // ----------------------------------------------------------------------------
23 // for compilers that support precompilation, includes "wx.h".
24 #include "wx/wxprec.h"
30 // other wxWindows headers
31 #include "wx/string.h"
35 #include "wx/config.h" // for wxExpandEnvVars
40 #define WIN32_LEAN_AND_MEAN
46 #include <stdlib.h> // for _MAX_PATH
53 #define HKEY_DEFINED // already defined in windows.h
54 #include "wx/msw/registry.h"
56 // some registry functions don't like signed chars
57 typedef unsigned char *RegString
;
59 // ----------------------------------------------------------------------------
61 // ----------------------------------------------------------------------------
63 // the standard key names, short names and handles all bundled together for
69 const char *szShortName
;
73 { HKEY_CLASSES_ROOT
, "HKEY_CLASSES_ROOT", "HKCR" },
75 { HKEY_CURRENT_USER
, "HKEY_CURRENT_USER", "HKCU" },
76 { HKEY_LOCAL_MACHINE
, "HKEY_LOCAL_MACHINE", "HKLM" },
77 { HKEY_USERS
, "HKEY_USERS", "HKU" }, // short name?
78 { HKEY_PERFORMANCE_DATA
, "HKEY_PERFORMANCE_DATA", "HKPD" },
80 { HKEY_CURRENT_CONFIG
, "HKEY_CURRENT_CONFIG", "HKCC" },
82 { HKEY_DYN_DATA
, "HKEY_DYN_DATA", "HKDD" }, // short name?
84 #endif //WINVER >= 4.0
88 // the registry name separator (perhaps one day MS will change it to '/' ;-)
89 #define REG_SEPARATOR '\\'
91 // useful for Windows programmers: makes somewhat more clear all these zeroes
92 // being passed to Windows APIs
93 #define RESERVED (NULL)
95 // ----------------------------------------------------------------------------
97 // ----------------------------------------------------------------------------
98 // @ const_cast<> is not yet supported by all compilers
99 #define CONST_CAST ((wxRegKey *)this)->
102 #define m_dwLastError CONST_CAST m_dwLastError
105 // ----------------------------------------------------------------------------
106 // non member functions
107 // ----------------------------------------------------------------------------
109 // removes the trailing backslash from the string if it has one
110 static inline void RemoveTrailingSeparator(wxString
& str
);
112 // returns TRUE if given registry key exists
113 static bool KeyExists(HKEY hRootKey
, const char *szKey
);
115 // combines value and key name (uses static buffer!)
116 static const char *GetFullName(const wxRegKey
*pKey
,
117 const char *szValue
= NULL
);
119 // ============================================================================
120 // implementation of wxRegKey class
121 // ============================================================================
123 // ----------------------------------------------------------------------------
124 // static functions and variables
125 // ----------------------------------------------------------------------------
127 const size_t wxRegKey::nStdKeys
= WXSIZEOF(aStdKeys
);
129 // @@ should take a `StdKey key', but as it's often going to be used in loops
130 // it would require casts in user code.
131 const char *wxRegKey::GetStdKeyName(size_t key
)
133 // return empty string if key is invalid
134 wxCHECK_MSG( key
< nStdKeys
, "", "invalid key in wxRegKey::GetStdKeyName" );
136 return aStdKeys
[key
].szName
;
139 const char *wxRegKey::GetStdKeyShortName(size_t key
)
141 // return empty string if key is invalid
142 wxCHECK( key
< nStdKeys
, "" );
144 return aStdKeys
[key
].szShortName
;
147 wxRegKey::StdKey
wxRegKey::ExtractKeyName(wxString
& strKey
)
149 wxString strRoot
= strKey
.Left(REG_SEPARATOR
);
153 for ( ui
= 0; ui
< nStdKeys
; ui
++ ) {
154 if ( strRoot
.CmpNoCase(aStdKeys
[ui
].szName
) == 0 ||
155 strRoot
.CmpNoCase(aStdKeys
[ui
].szShortName
) == 0 ) {
156 hRootKey
= aStdKeys
[ui
].hkey
;
161 if ( ui
== nStdKeys
) {
162 wxFAIL_MSG("invalid key prefix in wxRegKey::ExtractKeyName.");
164 hRootKey
= HKEY_CLASSES_ROOT
;
167 strKey
= strKey
.After(REG_SEPARATOR
);
168 if ( !strKey
.IsEmpty() && strKey
.Last() == REG_SEPARATOR
)
169 strKey
.Truncate(strKey
.Len() - 1);
172 return (wxRegKey::StdKey
)(int)hRootKey
;
175 wxRegKey::StdKey
wxRegKey::GetStdKeyFromHkey(HKEY hkey
)
177 for ( size_t ui
= 0; ui
< nStdKeys
; ui
++ ) {
178 if ( aStdKeys
[ui
].hkey
== hkey
)
182 wxFAIL_MSG("non root hkey passed to wxRegKey::GetStdKeyFromHkey.");
187 // ----------------------------------------------------------------------------
189 // ----------------------------------------------------------------------------
194 m_hRootKey
= aStdKeys
[HKCR
].hkey
;
198 wxRegKey::wxRegKey(const wxString
& strKey
) : m_strKey(strKey
)
200 m_hRootKey
= aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
205 // parent is a predefined (and preopened) key
206 wxRegKey::wxRegKey(StdKey keyParent
, const wxString
& strKey
) : m_strKey(strKey
)
208 RemoveTrailingSeparator(m_strKey
);
209 m_hRootKey
= aStdKeys
[keyParent
].hkey
;
214 // parent is a normal regkey
215 wxRegKey::wxRegKey(const wxRegKey
& keyParent
, const wxString
& strKey
)
216 : m_strKey(keyParent
.m_strKey
)
218 // combine our name with parent's to get the full name
219 if ( !m_strKey
.IsEmpty() &&
220 (strKey
.IsEmpty() || strKey
[0] != REG_SEPARATOR
) ) {
221 m_strKey
+= REG_SEPARATOR
;
225 RemoveTrailingSeparator(m_strKey
);
227 m_hRootKey
= keyParent
.m_hRootKey
;
232 // dtor closes the key releasing system resource
233 wxRegKey::~wxRegKey()
238 // ----------------------------------------------------------------------------
239 // change the key name/hkey
240 // ----------------------------------------------------------------------------
242 // set the full key name
243 void wxRegKey::SetName(const wxString
& strKey
)
248 m_hRootKey
= aStdKeys
[ExtractKeyName(m_strKey
)].hkey
;
251 // the name is relative to the parent key
252 void wxRegKey::SetName(StdKey keyParent
, const wxString
& strKey
)
257 RemoveTrailingSeparator(m_strKey
);
258 m_hRootKey
= aStdKeys
[keyParent
].hkey
;
261 // the name is relative to the parent key
262 void wxRegKey::SetName(const wxRegKey
& keyParent
, const wxString
& strKey
)
266 // combine our name with parent's to get the full name
267 m_strKey
= keyParent
.m_strKey
;
268 if ( !strKey
.IsEmpty() && strKey
[0] != REG_SEPARATOR
)
269 m_strKey
+= REG_SEPARATOR
;
272 RemoveTrailingSeparator(m_strKey
);
274 m_hRootKey
= keyParent
.m_hRootKey
;
277 // hKey should be opened and will be closed in wxRegKey dtor
278 void wxRegKey::SetHkey(HKEY hKey
)
285 // ----------------------------------------------------------------------------
286 // info about the key
287 // ----------------------------------------------------------------------------
289 // returns TRUE if the key exists
290 bool wxRegKey::Exists() const
292 // opened key has to exist, try to open it if not done yet
293 return IsOpened() ? TRUE
: KeyExists(m_hRootKey
, m_strKey
);
296 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
297 wxString
wxRegKey::GetName(bool bShortPrefix
) const
299 StdKey key
= GetStdKeyFromHkey(m_hRootKey
);
300 wxString str
= bShortPrefix
? aStdKeys
[key
].szShortName
301 : aStdKeys
[key
].szName
;
302 if ( !m_strKey
.IsEmpty() )
303 str
<< "\\" << m_strKey
;
309 bool wxRegKey::GetKeyInfo(size_t* pnSubKeys
,
312 size_t* pnMaxValueLen
) const
314 bool wxRegKey::GetKeyInfo(ulong
*pnSubKeys
,
317 ulong
*pnMaxValueLen
) const
321 m_dwLastError
= ::RegQueryInfoKey
325 NULL
, // (ptr to) size of class name buffer
327 pnSubKeys
, // [out] number of subkeys
328 pnMaxKeyLen
, // [out] max length of a subkey name
329 NULL
, // longest subkey class name
330 pnValues
, // [out] number of values
331 pnMaxValueLen
, // [out] max length of a value name
332 NULL
, // longest value data
333 NULL
, // security descriptor
334 NULL
// time of last modification
337 if ( m_dwLastError
!= ERROR_SUCCESS
) {
338 wxLogSysError(m_dwLastError
, _("can't get info about registry key '%s'"),
345 wxFAIL_MSG("GetKeyInfo() not implemented");
351 // ----------------------------------------------------------------------------
353 // ----------------------------------------------------------------------------
355 // opens key (it's not an error to call Open() on an already opened key)
356 bool wxRegKey::Open()
361 m_dwLastError
= RegOpenKey(m_hRootKey
, m_strKey
, &m_hKey
);
362 if ( m_dwLastError
!= ERROR_SUCCESS
) {
363 wxLogSysError(m_dwLastError
, _("can't open registry key '%s'"),
371 // creates key, failing if it exists and !bOkIfExists
372 bool wxRegKey::Create(bool bOkIfExists
)
374 // check for existence only if asked (i.e. order is important!)
375 if ( !bOkIfExists
&& Exists() ) {
382 m_dwLastError
= RegCreateKey(m_hRootKey
, m_strKey
, &m_hKey
);
383 if ( m_dwLastError
!= ERROR_SUCCESS
) {
384 wxLogSysError(m_dwLastError
, _("can't create registry key '%s'"),
392 // close the key, it's not an error to call it when not opened
393 bool wxRegKey::Close()
396 m_dwLastError
= RegCloseKey(m_hKey
);
397 if ( m_dwLastError
!= ERROR_SUCCESS
) {
398 wxLogSysError(m_dwLastError
, _("can't close registry key '%s'"),
412 // ----------------------------------------------------------------------------
413 // delete keys/values
414 // ----------------------------------------------------------------------------
415 bool wxRegKey::DeleteSelf()
420 // it already doesn't exist - ok!
425 // we can't delete keys while enumerating because it confuses GetNextKey, so
426 // we first save the key names and then delete them all
427 wxArrayString astrSubkeys
;
431 bool bCont
= GetFirstKey(strKey
, lIndex
);
433 astrSubkeys
.Add(strKey
);
435 bCont
= GetNextKey(strKey
, lIndex
);
438 size_t nKeyCount
= astrSubkeys
.Count();
439 for ( size_t nKey
= 0; nKey
< nKeyCount
; nKey
++ ) {
440 wxRegKey
key(*this, astrSubkeys
[nKey
]);
441 if ( !key
.DeleteSelf() )
445 // now delete this key itself
448 m_dwLastError
= RegDeleteKey(m_hRootKey
, m_strKey
);
449 if ( m_dwLastError
!= ERROR_SUCCESS
) {
450 wxLogSysError(m_dwLastError
, _("can't delete key '%s'"),
458 bool wxRegKey::DeleteKey(const char *szKey
)
463 wxRegKey
key(*this, szKey
);
464 return key
.DeleteSelf();
467 bool wxRegKey::DeleteValue(const char *szValue
)
473 m_dwLastError
= RegDeleteValue(m_hKey
, szValue
);
474 if ( m_dwLastError
!= ERROR_SUCCESS
) {
475 wxLogSysError(m_dwLastError
, _("can't delete value '%s' from key '%s'"),
476 szValue
, GetName().c_str());
480 // named registry values don't exist in Win16 world
481 wxASSERT( IsEmpty(szValue
) );
483 // just set the (default and unique) value of the key to ""
484 m_dwLastError
= RegSetValue(m_hKey
, NULL
, REG_SZ
, "", RESERVED
);
485 if ( m_dwLastError
!= ERROR_SUCCESS
) {
486 wxLogSysError(m_dwLastError
, _("can't delete value of key '%s'"),
495 // ----------------------------------------------------------------------------
496 // access to values and subkeys
497 // ----------------------------------------------------------------------------
499 // return TRUE if value exists
500 bool wxRegKey::HasValue(const char *szValue
) const
502 // this function should be silent, so suppress possible messages from Open()
506 if ( CONST_CAST
Open() ) {
507 return RegQueryValueEx(m_hKey
, szValue
, RESERVED
,
508 NULL
, NULL
, NULL
) == ERROR_SUCCESS
;
513 // only unnamed value exists
514 return IsEmpty(szValue
);
518 // returns TRUE if this key has any subkeys
519 bool wxRegKey::HasSubkeys() const
521 // just call GetFirstKey with dummy parameters
524 return CONST_CAST
GetFirstKey(str
, l
);
527 // returns TRUE if given subkey exists
528 bool wxRegKey::HasSubKey(const char *szKey
) const
530 if ( CONST_CAST
Open() )
531 return KeyExists(m_hKey
, szKey
);
536 wxRegKey::ValueType
wxRegKey::GetValueType(const char *szValue
)
543 m_dwLastError
= RegQueryValueEx(m_hKey
, szValue
, RESERVED
,
544 &dwType
, NULL
, NULL
);
545 if ( m_dwLastError
!= ERROR_SUCCESS
) {
546 wxLogSysError(m_dwLastError
, _("can't read value of key '%s'"),
551 return (ValueType
)dwType
;
553 return IsEmpty(szValue
) ? Type_String
: Type_None
;
558 bool wxRegKey::SetValue(const char *szValue
, long lValue
)
560 if ( CONST_CAST
Open() ) {
561 m_dwLastError
= RegSetValueEx(m_hKey
, szValue
, RESERVED
, REG_DWORD
,
562 (RegString
)&lValue
, sizeof(lValue
));
563 if ( m_dwLastError
== ERROR_SUCCESS
)
567 wxLogSysError(m_dwLastError
, _("can't set value of '%s'"),
568 GetFullName(this, szValue
));
572 bool wxRegKey::QueryValue(const char *szValue
, long *plValue
) const
574 if ( CONST_CAST
Open() ) {
575 DWORD dwType
, dwSize
= sizeof(DWORD
);
576 RegString pBuf
= (RegString
)plValue
;
577 m_dwLastError
= RegQueryValueEx(m_hKey
, szValue
, RESERVED
,
578 &dwType
, pBuf
, &dwSize
);
579 if ( m_dwLastError
!= ERROR_SUCCESS
) {
580 wxLogSysError(m_dwLastError
, _("can't read value of key '%s'"),
585 // check that we read the value of right type
586 wxASSERT_MSG( dwType
== REG_DWORD
,
587 "Type mismatch in wxRegKey::QueryValue()." );
598 bool wxRegKey::QueryValue(const char *szValue
, wxString
& strValue
) const
600 if ( CONST_CAST
Open() ) {
602 // first get the type and size of the data
603 DWORD dwType
, dwSize
;
604 m_dwLastError
= RegQueryValueEx(m_hKey
, szValue
, RESERVED
,
605 &dwType
, NULL
, &dwSize
);
606 if ( m_dwLastError
== ERROR_SUCCESS
) {
607 RegString pBuf
= (RegString
)strValue
.GetWriteBuf(dwSize
);
608 m_dwLastError
= RegQueryValueEx(m_hKey
, szValue
, RESERVED
,
609 &dwType
, pBuf
, &dwSize
);
610 strValue
.UngetWriteBuf();
611 if ( m_dwLastError
== ERROR_SUCCESS
) {
612 // check that it was the right type
613 wxASSERT_MSG( dwType
== REG_SZ
,
614 "Type mismatch in wxRegKey::QueryValue()." );
620 // named registry values don't exist in Win16
621 wxASSERT( IsEmpty(szValue
) );
623 m_dwLastError
= RegQueryValue(m_hKey
, 0, strValue
.GetWriteBuf(256), &l
);
624 strValue
.UngetWriteBuf();
625 if ( m_dwLastError
== ERROR_SUCCESS
)
630 wxLogSysError(m_dwLastError
, _("can't read value of '%s'"),
631 GetFullName(this, szValue
));
635 bool wxRegKey::SetValue(const char *szValue
, const wxString
& strValue
)
637 if ( CONST_CAST
Open() ) {
639 m_dwLastError
= RegSetValueEx(m_hKey
, szValue
, RESERVED
, REG_SZ
,
640 (RegString
)strValue
.c_str(),
642 if ( m_dwLastError
== ERROR_SUCCESS
)
645 // named registry values don't exist in Win16
646 wxASSERT( IsEmpty(szValue
) );
648 m_dwLastError
= RegSetValue(m_hKey
, NULL
, REG_SZ
, strValue
, NULL
);
649 if ( m_dwLastError
== ERROR_SUCCESS
)
654 wxLogSysError(m_dwLastError
, _("can't set value of '%s'"),
655 GetFullName(this, szValue
));
659 wxRegKey::operator wxString() const
662 QueryValue(NULL
, str
);
666 // ----------------------------------------------------------------------------
668 // NB: all these functions require an index variable which allows to have
669 // several concurrently running indexations on the same key
670 // ----------------------------------------------------------------------------
672 bool wxRegKey::GetFirstValue(wxString
& strValueName
, long& lIndex
)
678 return GetNextValue(strValueName
, lIndex
);
681 bool wxRegKey::GetNextValue(wxString
& strValueName
, long& lIndex
) const
683 wxASSERT( IsOpened() );
685 // are we already at the end of enumeration?
690 char szValueName
[1024]; // @@ use RegQueryInfoKey...
691 DWORD dwValueLen
= WXSIZEOF(szValueName
);
694 m_dwLastError
= RegEnumValue(m_hKey
, lIndex
,
695 szValueName
, &dwValueLen
,
698 NULL
, // [out] buffer for value
699 NULL
); // [i/o] it's length
701 if ( m_dwLastError
!= ERROR_SUCCESS
) {
702 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
703 m_dwLastError
= ERROR_SUCCESS
;
707 wxLogSysError(m_dwLastError
, _("can't enumerate values of key '%s'"),
714 strValueName
= szValueName
;
716 // only one unnamed value
717 wxASSERT( lIndex
== 0 );
720 strValueName
.Empty();
726 bool wxRegKey::GetFirstKey(wxString
& strKeyName
, long& lIndex
)
732 return GetNextKey(strKeyName
, lIndex
);
735 bool wxRegKey::GetNextKey(wxString
& strKeyName
, long& lIndex
) const
737 wxASSERT( IsOpened() );
739 // are we already at the end of enumeration?
743 char szKeyName
[_MAX_PATH
+ 1];
744 m_dwLastError
= RegEnumKey(m_hKey
, lIndex
++, szKeyName
, WXSIZEOF(szKeyName
));
746 if ( m_dwLastError
!= ERROR_SUCCESS
) {
747 if ( m_dwLastError
== ERROR_NO_MORE_ITEMS
) {
748 m_dwLastError
= ERROR_SUCCESS
;
752 wxLogSysError(m_dwLastError
, _("can't enumerate subkeys of key '%s'"),
759 strKeyName
= szKeyName
;
763 // ============================================================================
764 // implementation of global private functions
765 // ============================================================================
766 bool KeyExists(HKEY hRootKey
, const char *szKey
)
769 if ( RegOpenKey(hRootKey
, szKey
, &hkeyDummy
) == ERROR_SUCCESS
) {
770 RegCloseKey(hkeyDummy
);
777 const char *GetFullName(const wxRegKey
*pKey
, const char *szValue
)
779 static wxString s_str
;
780 s_str
= pKey
->GetName();
781 if ( !IsEmpty(szValue
) )
782 s_str
<< "\\" << szValue
;
784 return s_str
.c_str();
787 void RemoveTrailingSeparator(wxString
& str
)
789 if ( !str
.IsEmpty() && str
.Last() == REG_SEPARATOR
)
790 str
.Truncate(str
.Len() - 1);
793 // ============================================================================
794 // global public functions
795 // ============================================================================
797 bool GetExtensionFromMimeType(wxString
*pExt
, const wxString
& strMimeType
)
799 // @@@ VZ: I don't know of any official documentation which mentions this
800 // location, but as a matter of fact IE uses it, so why not we?
801 static const char *szMimeDbase
= "MIME\\Database\\Content Type\\";
803 wxString strKey
= szMimeDbase
;
804 strKey
<< strMimeType
;
806 // suppress possible error messages
808 wxRegKey
key(wxRegKey::HKCR
, strKey
);
810 if ( key
.QueryValue("Extension", *pExt
) )
814 // no such MIME type or no extension for it
818 bool GetMimeTypeFromExtension(wxString
*pMimeType
, const wxString
& strExt
)
820 wxCHECK( !strExt
.IsEmpty(), FALSE
);
822 // add the leading point if necessary
824 if ( strExt
[0] != '.' ) {
829 // suppress possible error messages
831 wxRegKey
key(wxRegKey::HKCR
, str
);
833 if ( key
.QueryValue("Content Type", *pMimeType
) )
837 // no such extension or no content-type
841 bool GetFileTypeFromExtension(wxString
*pFileType
, const wxString
& strExt
)
843 wxCHECK( !strExt
.IsEmpty(), FALSE
);
845 // add the leading point if necessary
847 if ( strExt
[0] != '.' ) {
852 // suppress possible error messages
854 wxRegKey
key(wxRegKey::HKCR
, str
);
856 if ( key
.QueryValue("", *pFileType
) ) // it's the default value of the key
860 // no such extension or no value
864 bool GetFileTypeIcon(wxIcon
*pIcon
, const wxString
& strFileType
)
866 wxCHECK( !strFileType
.IsEmpty(), FALSE
);
869 strIconKey
<< strFileType
<< REG_SEPARATOR
<< "DefaultIcon";
871 // suppress possible error messages
873 wxRegKey
key(wxRegKey::HKCR
, strIconKey
);
877 if ( key
.QueryValue("", strIcon
) ) { // it's the default value of the key
878 // the format is the following: <full path to file>, <icon index>
879 // NB: icon index may be negative as well as positive and the full path
880 // may contain the environment variables inside '%'
881 wxString strFullPath
= strIcon
.Before(','),
882 strIndex
= strIcon
.After(',');
884 // unless I misunderstand the format (may be index may be ommited, I
886 wxASSERT( !(strFullPath
.IsEmpty() || strIndex
.IsEmpty()) );
888 wxString strExpPath
= wxExpandEnvVars(strFullPath
);
889 int nIndex
= atoi(strIndex
);
891 HICON hIcon
= ExtractIcon(GetModuleHandle(NULL
), strExpPath
, nIndex
);
892 switch ( (int)hIcon
) {
893 case 0: // means no icons were found
894 case 1: // means no such file or it wasn't a DLL/EXE/OCX/ICO/...
895 wxLogDebug("incorrect registry entry '%s': no such icon.",
900 pIcon
->SetHICON((WXHICON
)hIcon
);
906 // no such file type or no value or incorrect icon entry
910 bool GetFileTypeDescription(wxString
*pDesc
, const wxString
& strFileType
)
912 wxCHECK( !strFileType
.IsEmpty(), FALSE
);
914 // suppress possible error messages
916 wxRegKey
key(wxRegKey::HKCR
, strFileType
);
919 if ( key
.QueryValue("", *pDesc
) ) // it's the default value of the key
923 // no such file type or no value