* add documentation for wxMemoryBuffer
[wxWidgets.git] / src / msw / registry.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: msw/registry.cpp
3 // Purpose: implementation of registry classes and functions
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 03.04.98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows licence
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 ///////////////////////////////////////////////////////////////////////////////
14
15 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
16 #pragma implementation "registry.h"
17 #endif
18
19 // for compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
21
22 #ifdef __BORLANDC__
23 #pragma hdrstop
24 #endif
25
26 // other wxWidgets headers
27 #include "wx/string.h"
28 #include "wx/intl.h"
29 #include "wx/log.h"
30
31 // Windows headers
32 /*
33 #define STRICT
34 #define WIN32_LEAN_AND_MEAN
35 */
36
37 #include "wx/msw/wrapwin.h"
38
39 #ifdef __WXWINCE__
40 #include "wx/msw/private.h"
41 #include <winbase.h>
42 #include <winreg.h>
43 #endif
44
45 // other std headers
46 #include <stdlib.h> // for _MAX_PATH
47
48 #ifndef _MAX_PATH
49 #define _MAX_PATH 512
50 #endif
51
52 // our header
53 #define HKEY_DEFINED // already defined in windows.h
54 #include "wx/msw/registry.h"
55
56 // some registry functions don't like signed chars
57 typedef unsigned char *RegString;
58 typedef BYTE* RegBinary;
59
60 // ----------------------------------------------------------------------------
61 // constants
62 // ----------------------------------------------------------------------------
63
64 // the standard key names, short names and handles all bundled together for
65 // convenient access
66 static struct
67 {
68 HKEY hkey;
69 const wxChar *szName;
70 const wxChar *szShortName;
71 }
72 aStdKeys[] =
73 {
74 { HKEY_CLASSES_ROOT, wxT("HKEY_CLASSES_ROOT"), wxT("HKCR") },
75 #ifdef __WIN32__
76 { HKEY_CURRENT_USER, wxT("HKEY_CURRENT_USER"), wxT("HKCU") },
77 { HKEY_LOCAL_MACHINE, wxT("HKEY_LOCAL_MACHINE"), wxT("HKLM") },
78 { HKEY_USERS, wxT("HKEY_USERS"), wxT("HKU") }, // short name?
79 #ifndef __WXWINCE__
80 { HKEY_PERFORMANCE_DATA, wxT("HKEY_PERFORMANCE_DATA"), wxT("HKPD") },
81 #endif
82 #if WINVER >= 0x0400 && !defined(__WXWINCE__)
83 { HKEY_CURRENT_CONFIG, wxT("HKEY_CURRENT_CONFIG"), wxT("HKCC") },
84 #if !defined(__GNUWIN32__) && !defined(__WXWINCE__)
85 { HKEY_DYN_DATA, wxT("HKEY_DYN_DATA"), wxT("HKDD") }, // short name?
86 #endif //GNUWIN32
87 #endif //WINVER >= 4.0
88 #endif //WIN32
89 };
90
91 // the registry name separator (perhaps one day MS will change it to '/' ;-)
92 #define REG_SEPARATOR wxT('\\')
93
94 // useful for Windows programmers: makes somewhat more clear all these zeroes
95 // being passed to Windows APIs
96 #define RESERVED (0)
97
98 // ----------------------------------------------------------------------------
99 // macros
100 // ----------------------------------------------------------------------------
101
102 // const_cast<> is not yet supported by all compilers
103 #define CONST_CAST ((wxRegKey *)this)->
104
105 // and neither is mutable which m_dwLastError should be
106 #define m_dwLastError CONST_CAST m_dwLastError
107
108 // ----------------------------------------------------------------------------
109 // non member functions
110 // ----------------------------------------------------------------------------
111
112 // removes the trailing backslash from the string if it has one
113 static inline void RemoveTrailingSeparator(wxString& str);
114
115 // returns TRUE if given registry key exists
116 static bool KeyExists(WXHKEY hRootKey, const wxChar *szKey);
117
118 // combines value and key name (uses static buffer!)
119 static const wxChar *GetFullName(const wxRegKey *pKey,
120 const wxChar *szValue = NULL);
121
122 // ============================================================================
123 // implementation of wxRegKey class
124 // ============================================================================
125
126 // ----------------------------------------------------------------------------
127 // static functions and variables
128 // ----------------------------------------------------------------------------
129
130 const size_t wxRegKey::nStdKeys = WXSIZEOF(aStdKeys);
131
132 // @@ should take a `StdKey key', but as it's often going to be used in loops
133 // it would require casts in user code.
134 const wxChar *wxRegKey::GetStdKeyName(size_t key)
135 {
136 // return empty string if key is invalid
137 wxCHECK_MSG( key < nStdKeys, wxEmptyString, wxT("invalid key in wxRegKey::GetStdKeyName") );
138
139 return aStdKeys[key].szName;
140 }
141
142 const wxChar *wxRegKey::GetStdKeyShortName(size_t key)
143 {
144 // return empty string if key is invalid
145 wxCHECK( key < nStdKeys, wxEmptyString );
146
147 return aStdKeys[key].szShortName;
148 }
149
150 wxRegKey::StdKey wxRegKey::ExtractKeyName(wxString& strKey)
151 {
152 wxString strRoot = strKey.BeforeFirst(REG_SEPARATOR);
153
154 HKEY hRootKey = 0;
155 size_t ui;
156 for ( ui = 0; ui < nStdKeys; ui++ ) {
157 if ( strRoot.CmpNoCase(aStdKeys[ui].szName) == 0 ||
158 strRoot.CmpNoCase(aStdKeys[ui].szShortName) == 0 ) {
159 hRootKey = aStdKeys[ui].hkey;
160 break;
161 }
162 }
163
164 if ( ui == nStdKeys ) {
165 wxFAIL_MSG(wxT("invalid key prefix in wxRegKey::ExtractKeyName."));
166
167 hRootKey = HKEY_CLASSES_ROOT;
168 }
169 else {
170 strKey = strKey.After(REG_SEPARATOR);
171 if ( !strKey.IsEmpty() && strKey.Last() == REG_SEPARATOR )
172 strKey.Truncate(strKey.Len() - 1);
173 }
174
175 return (wxRegKey::StdKey)(int)hRootKey;
176 }
177
178 wxRegKey::StdKey wxRegKey::GetStdKeyFromHkey(WXHKEY hkey)
179 {
180 for ( size_t ui = 0; ui < nStdKeys; ui++ ) {
181 if ( (int) aStdKeys[ui].hkey == (int) hkey )
182 return (StdKey)ui;
183 }
184
185 wxFAIL_MSG(wxT("non root hkey passed to wxRegKey::GetStdKeyFromHkey."));
186
187 return HKCR;
188 }
189
190 // ----------------------------------------------------------------------------
191 // ctors and dtor
192 // ----------------------------------------------------------------------------
193
194 wxRegKey::wxRegKey()
195 {
196 m_hRootKey = (WXHKEY) aStdKeys[HKCR].hkey;
197
198 Init();
199 }
200
201 wxRegKey::wxRegKey(const wxString& strKey) : m_strKey(strKey)
202 {
203 m_hRootKey = (WXHKEY) aStdKeys[ExtractKeyName(m_strKey)].hkey;
204
205 Init();
206 }
207
208 // parent is a predefined (and preopened) key
209 wxRegKey::wxRegKey(StdKey keyParent, const wxString& strKey) : m_strKey(strKey)
210 {
211 RemoveTrailingSeparator(m_strKey);
212 m_hRootKey = (WXHKEY) aStdKeys[keyParent].hkey;
213
214 Init();
215 }
216
217 // parent is a normal regkey
218 wxRegKey::wxRegKey(const wxRegKey& keyParent, const wxString& strKey)
219 : m_strKey(keyParent.m_strKey)
220 {
221 // combine our name with parent's to get the full name
222 if ( !m_strKey.IsEmpty() &&
223 (strKey.IsEmpty() || strKey[0] != REG_SEPARATOR) ) {
224 m_strKey += REG_SEPARATOR;
225 }
226
227 m_strKey += strKey;
228 RemoveTrailingSeparator(m_strKey);
229
230 m_hRootKey = keyParent.m_hRootKey;
231
232 Init();
233 }
234
235 // dtor closes the key releasing system resource
236 wxRegKey::~wxRegKey()
237 {
238 Close();
239 }
240
241 // ----------------------------------------------------------------------------
242 // change the key name/hkey
243 // ----------------------------------------------------------------------------
244
245 // set the full key name
246 void wxRegKey::SetName(const wxString& strKey)
247 {
248 Close();
249
250 m_strKey = strKey;
251 m_hRootKey = (WXHKEY) aStdKeys[ExtractKeyName(m_strKey)].hkey;
252 }
253
254 // the name is relative to the parent key
255 void wxRegKey::SetName(StdKey keyParent, const wxString& strKey)
256 {
257 Close();
258
259 m_strKey = strKey;
260 RemoveTrailingSeparator(m_strKey);
261 m_hRootKey = (WXHKEY) aStdKeys[keyParent].hkey;
262 }
263
264 // the name is relative to the parent key
265 void wxRegKey::SetName(const wxRegKey& keyParent, const wxString& strKey)
266 {
267 Close();
268
269 // combine our name with parent's to get the full name
270
271 // NB: this method is called by wxRegConfig::SetPath() which is a performance
272 // critical function and so it preallocates space for our m_strKey to
273 // gain some speed - this is why we only use += here and not = which
274 // would just free the prealloc'd buffer and would have to realloc it the
275 // next line!
276 m_strKey.clear();
277 m_strKey += keyParent.m_strKey;
278 if ( !strKey.IsEmpty() && strKey[0] != REG_SEPARATOR )
279 m_strKey += REG_SEPARATOR;
280 m_strKey += strKey;
281
282 RemoveTrailingSeparator(m_strKey);
283
284 m_hRootKey = keyParent.m_hRootKey;
285 }
286
287 // hKey should be opened and will be closed in wxRegKey dtor
288 void wxRegKey::SetHkey(WXHKEY hKey)
289 {
290 Close();
291
292 m_hKey = hKey;
293 }
294
295 // ----------------------------------------------------------------------------
296 // info about the key
297 // ----------------------------------------------------------------------------
298
299 // returns TRUE if the key exists
300 bool wxRegKey::Exists() const
301 {
302 // opened key has to exist, try to open it if not done yet
303 return IsOpened() ? TRUE : KeyExists(m_hRootKey, m_strKey);
304 }
305
306 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
307 wxString wxRegKey::GetName(bool bShortPrefix) const
308 {
309 StdKey key = GetStdKeyFromHkey((WXHKEY) m_hRootKey);
310 wxString str = bShortPrefix ? aStdKeys[key].szShortName
311 : aStdKeys[key].szName;
312 if ( !m_strKey.IsEmpty() )
313 str << _T("\\") << m_strKey;
314
315 return str;
316 }
317
318 bool wxRegKey::GetKeyInfo(size_t *pnSubKeys,
319 size_t *pnMaxKeyLen,
320 size_t *pnValues,
321 size_t *pnMaxValueLen) const
322 {
323 // old gcc headers incorrectly prototype RegQueryInfoKey()
324 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
325 #define REG_PARAM (size_t *)
326 #else
327 #define REG_PARAM (LPDWORD)
328 #endif
329
330 // it might be unexpected to some that this function doesn't open the key
331 wxASSERT_MSG( IsOpened(), _T("key should be opened in GetKeyInfo") );
332
333 m_dwLastError = ::RegQueryInfoKey
334 (
335 (HKEY) m_hKey,
336 NULL, // class name
337 NULL, // (ptr to) size of class name buffer
338 RESERVED,
339 REG_PARAM
340 pnSubKeys, // [out] number of subkeys
341 REG_PARAM
342 pnMaxKeyLen, // [out] max length of a subkey name
343 NULL, // longest subkey class name
344 REG_PARAM
345 pnValues, // [out] number of values
346 REG_PARAM
347 pnMaxValueLen, // [out] max length of a value name
348 NULL, // longest value data
349 NULL, // security descriptor
350 NULL // time of last modification
351 );
352
353 #undef REG_PARAM
354
355 if ( m_dwLastError != ERROR_SUCCESS ) {
356 wxLogSysError(m_dwLastError, _("Can't get info about registry key '%s'"),
357 GetName().c_str());
358 return FALSE;
359 }
360
361 return TRUE;
362 }
363
364 // ----------------------------------------------------------------------------
365 // operations
366 // ----------------------------------------------------------------------------
367
368 // opens key (it's not an error to call Open() on an already opened key)
369 bool wxRegKey::Open(AccessMode mode)
370 {
371 if ( IsOpened() )
372 return TRUE;
373
374 HKEY tmpKey;
375 m_dwLastError = ::RegOpenKeyEx
376 (
377 (HKEY) m_hRootKey,
378 m_strKey,
379 RESERVED,
380 mode == Read ? KEY_READ : KEY_ALL_ACCESS,
381 &tmpKey
382 );
383
384 if ( m_dwLastError != ERROR_SUCCESS )
385 {
386 wxLogSysError(m_dwLastError, _("Can't open registry key '%s'"),
387 GetName().c_str());
388 return FALSE;
389 }
390
391 m_hKey = (WXHKEY) tmpKey;
392 return TRUE;
393 }
394
395 // creates key, failing if it exists and !bOkIfExists
396 bool wxRegKey::Create(bool bOkIfExists)
397 {
398 // check for existence only if asked (i.e. order is important!)
399 if ( !bOkIfExists && Exists() )
400 return FALSE;
401
402 if ( IsOpened() )
403 return TRUE;
404
405 HKEY tmpKey;
406 #ifdef __WXWINCE__
407 DWORD disposition;
408 m_dwLastError = RegCreateKeyEx((HKEY) m_hRootKey, m_strKey,
409 NULL, // reserved
410 NULL, // class string
411 0,
412 0,
413 NULL,
414 &tmpKey,
415 &disposition);
416 #else
417 m_dwLastError = RegCreateKey((HKEY) m_hRootKey, m_strKey, &tmpKey);
418 #endif
419 if ( m_dwLastError != ERROR_SUCCESS ) {
420 wxLogSysError(m_dwLastError, _("Can't create registry key '%s'"),
421 GetName().c_str());
422 return FALSE;
423 }
424 else
425 {
426 m_hKey = (WXHKEY) tmpKey;
427 return TRUE;
428 }
429 }
430
431 // close the key, it's not an error to call it when not opened
432 bool wxRegKey::Close()
433 {
434 if ( IsOpened() ) {
435 m_dwLastError = RegCloseKey((HKEY) m_hKey);
436 m_hKey = 0;
437
438 if ( m_dwLastError != ERROR_SUCCESS ) {
439 wxLogSysError(m_dwLastError, _("Can't close registry key '%s'"),
440 GetName().c_str());
441
442 return FALSE;
443 }
444 }
445
446 return TRUE;
447 }
448
449 bool wxRegKey::RenameValue(const wxChar *szValueOld, const wxChar *szValueNew)
450 {
451 bool ok = TRUE;
452 if ( HasValue(szValueNew) ) {
453 wxLogError(_("Registry value '%s' already exists."), szValueNew);
454
455 ok = FALSE;
456 }
457
458 if ( !ok ||
459 !CopyValue(szValueOld, *this, szValueNew) ||
460 !DeleteValue(szValueOld) ) {
461 wxLogError(_("Failed to rename registry value '%s' to '%s'."),
462 szValueOld, szValueNew);
463
464 return FALSE;
465 }
466
467 return TRUE;
468 }
469
470 bool wxRegKey::CopyValue(const wxChar *szValue,
471 wxRegKey& keyDst,
472 const wxChar *szValueNew)
473 {
474 if ( !szValueNew ) {
475 // by default, use the same name
476 szValueNew = szValue;
477 }
478
479 switch ( GetValueType(szValue) ) {
480 case Type_String:
481 {
482 wxString strVal;
483 return QueryValue(szValue, strVal) &&
484 keyDst.SetValue(szValueNew, strVal);
485 }
486
487 case Type_Dword:
488 /* case Type_Dword_little_endian: == Type_Dword */
489 {
490 long dwVal;
491 return QueryValue(szValue, &dwVal) &&
492 keyDst.SetValue(szValueNew, dwVal);
493 }
494
495 #ifdef __WIN32__
496 case Type_Binary:
497 {
498 wxMemoryBuffer buf;
499 return QueryValue(szValue,buf) &&
500 keyDst.SetValue(szValueNew,buf);
501 }
502 // these types are unsupported because I am not sure about how
503 // exactly they should be copied and because they shouldn't
504 // occur among the application keys (supposedly created with
505 // this class)
506 case Type_None:
507 case Type_Expand_String:
508 case Type_Dword_big_endian:
509 case Type_Link:
510 case Type_Multi_String:
511 case Type_Resource_list:
512 case Type_Full_resource_descriptor:
513 case Type_Resource_requirements_list:
514 #endif // Win32
515 default:
516 wxLogError(_("Can't copy values of unsupported type %d."),
517 GetValueType(szValue));
518 return FALSE;
519 }
520 }
521
522 bool wxRegKey::Rename(const wxChar *szNewName)
523 {
524 wxCHECK_MSG( !!m_strKey, FALSE, _T("registry hives can't be renamed") );
525
526 if ( !Exists() ) {
527 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
528 GetFullName(this));
529
530 return FALSE;
531 }
532
533 // do we stay in the same hive?
534 bool inSameHive = !wxStrchr(szNewName, REG_SEPARATOR);
535
536 // construct the full new name of the key
537 wxRegKey keyDst;
538
539 if ( inSameHive ) {
540 // rename the key to the new name under the same parent
541 wxString strKey = m_strKey.BeforeLast(REG_SEPARATOR);
542 if ( !!strKey ) {
543 // don't add '\\' in the start if strFullNewName is empty
544 strKey += REG_SEPARATOR;
545 }
546
547 strKey += szNewName;
548
549 keyDst.SetName(GetStdKeyFromHkey(m_hRootKey), strKey);
550 }
551 else {
552 // this is the full name already
553 keyDst.SetName(szNewName);
554 }
555
556 bool ok = keyDst.Create(FALSE /* fail if alredy exists */);
557 if ( !ok ) {
558 wxLogError(_("Registry key '%s' already exists."),
559 GetFullName(&keyDst));
560 }
561 else {
562 ok = Copy(keyDst) && DeleteSelf();
563 }
564
565 if ( !ok ) {
566 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
567 GetFullName(this), GetFullName(&keyDst));
568 }
569 else {
570 m_hRootKey = keyDst.m_hRootKey;
571 m_strKey = keyDst.m_strKey;
572 }
573
574 return ok;
575 }
576
577 bool wxRegKey::Copy(const wxChar *szNewName)
578 {
579 // create the new key first
580 wxRegKey keyDst(szNewName);
581 bool ok = keyDst.Create(FALSE /* fail if alredy exists */);
582 if ( ok ) {
583 ok = Copy(keyDst);
584
585 // we created the dest key but copying to it failed - delete it
586 if ( !ok ) {
587 (void)keyDst.DeleteSelf();
588 }
589 }
590
591 return ok;
592 }
593
594 bool wxRegKey::Copy(wxRegKey& keyDst)
595 {
596 bool ok = TRUE;
597
598 // copy all sub keys to the new location
599 wxString strKey;
600 long lIndex;
601 bool bCont = GetFirstKey(strKey, lIndex);
602 while ( ok && bCont ) {
603 wxRegKey key(*this, strKey);
604 wxString keyName;
605 keyName << GetFullName(&keyDst) << REG_SEPARATOR << strKey;
606 ok = key.Copy((const wxChar*) keyName);
607
608 if ( ok )
609 bCont = GetNextKey(strKey, lIndex);
610 else
611 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."), GetFullName(&key), keyName.mb_str());
612
613 }
614
615 // copy all values
616 wxString strVal;
617 bCont = GetFirstValue(strVal, lIndex);
618 while ( ok && bCont ) {
619 ok = CopyValue(strVal, keyDst);
620
621 if ( !ok ) {
622 wxLogSysError(m_dwLastError,
623 _("Failed to copy registry value '%s'"),
624 strVal.c_str());
625 }
626 else {
627 bCont = GetNextValue(strVal, lIndex);
628 }
629 }
630
631 if ( !ok ) {
632 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."), GetFullName(this), GetFullName(&keyDst));
633 }
634
635 return ok;
636 }
637
638 // ----------------------------------------------------------------------------
639 // delete keys/values
640 // ----------------------------------------------------------------------------
641 bool wxRegKey::DeleteSelf()
642 {
643 {
644 wxLogNull nolog;
645 if ( !Open() ) {
646 // it already doesn't exist - ok!
647 return TRUE;
648 }
649 }
650
651 // prevent a buggy program from erasing one of the root registry keys or an
652 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
653 // key except HKCR (HKCR has some "deleteable" subkeys)
654 if ( m_strKey.IsEmpty() ||
655 ((m_hRootKey != (WXHKEY) aStdKeys[HKCR].hkey) &&
656 (m_strKey.Find(REG_SEPARATOR) == wxNOT_FOUND)) ) {
657 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."), GetFullName(this));
658
659 return FALSE;
660 }
661
662 // we can't delete keys while enumerating because it confuses GetNextKey, so
663 // we first save the key names and then delete them all
664 wxArrayString astrSubkeys;
665
666 wxString strKey;
667 long lIndex;
668 bool bCont = GetFirstKey(strKey, lIndex);
669 while ( bCont ) {
670 astrSubkeys.Add(strKey);
671
672 bCont = GetNextKey(strKey, lIndex);
673 }
674
675 size_t nKeyCount = astrSubkeys.Count();
676 for ( size_t nKey = 0; nKey < nKeyCount; nKey++ ) {
677 wxRegKey key(*this, astrSubkeys[nKey]);
678 if ( !key.DeleteSelf() )
679 return FALSE;
680 }
681
682 // now delete this key itself
683 Close();
684
685 m_dwLastError = RegDeleteKey((HKEY) m_hRootKey, m_strKey);
686 // deleting a key which doesn't exist is not considered an error
687 if ( m_dwLastError != ERROR_SUCCESS &&
688 m_dwLastError != ERROR_FILE_NOT_FOUND ) {
689 wxLogSysError(m_dwLastError, _("Can't delete key '%s'"),
690 GetName().c_str());
691 return FALSE;
692 }
693
694 return TRUE;
695 }
696
697 bool wxRegKey::DeleteKey(const wxChar *szKey)
698 {
699 if ( !Open() )
700 return FALSE;
701
702 wxRegKey key(*this, szKey);
703 return key.DeleteSelf();
704 }
705
706 bool wxRegKey::DeleteValue(const wxChar *szValue)
707 {
708 if ( !Open() )
709 return FALSE;
710
711 m_dwLastError = RegDeleteValue((HKEY) m_hKey, WXSTRINGCAST szValue);
712
713 // deleting a value which doesn't exist is not considered an error
714 if ( (m_dwLastError != ERROR_SUCCESS) &&
715 (m_dwLastError != ERROR_FILE_NOT_FOUND) ) {
716 wxLogSysError(m_dwLastError, _("Can't delete value '%s' from key '%s'"),
717 szValue, GetName().c_str());
718 return FALSE;
719 }
720
721 return TRUE;
722 }
723
724 // ----------------------------------------------------------------------------
725 // access to values and subkeys
726 // ----------------------------------------------------------------------------
727
728 // return TRUE if value exists
729 bool wxRegKey::HasValue(const wxChar *szValue) const
730 {
731 // this function should be silent, so suppress possible messages from Open()
732 wxLogNull nolog;
733
734 if ( !CONST_CAST Open(Read) )
735 return FALSE;
736
737 LONG dwRet = ::RegQueryValueEx((HKEY) m_hKey,
738 WXSTRINGCAST szValue,
739 RESERVED,
740 NULL, NULL, NULL);
741 return dwRet == ERROR_SUCCESS;
742 }
743
744 // returns TRUE if this key has any values
745 bool wxRegKey::HasValues() const
746 {
747 // suppress possible messages from GetFirstValue()
748 wxLogNull nolog;
749
750 // just call GetFirstValue with dummy parameters
751 wxString str;
752 long l;
753 return CONST_CAST GetFirstValue(str, l);
754 }
755
756 // returns TRUE if this key has any subkeys
757 bool wxRegKey::HasSubkeys() const
758 {
759 // suppress possible messages from GetFirstKey()
760 wxLogNull nolog;
761
762 // just call GetFirstKey with dummy parameters
763 wxString str;
764 long l;
765 return CONST_CAST GetFirstKey(str, l);
766 }
767
768 // returns TRUE if given subkey exists
769 bool wxRegKey::HasSubKey(const wxChar *szKey) const
770 {
771 // this function should be silent, so suppress possible messages from Open()
772 wxLogNull nolog;
773
774 if ( !CONST_CAST Open(Read) )
775 return FALSE;
776
777 return KeyExists(m_hKey, szKey);
778 }
779
780 wxRegKey::ValueType wxRegKey::GetValueType(const wxChar *szValue) const
781 {
782 if ( ! CONST_CAST Open(Read) )
783 return Type_None;
784
785 DWORD dwType;
786 m_dwLastError = RegQueryValueEx((HKEY) m_hKey, WXSTRINGCAST szValue, RESERVED,
787 &dwType, NULL, NULL);
788 if ( m_dwLastError != ERROR_SUCCESS ) {
789 wxLogSysError(m_dwLastError, _("Can't read value of key '%s'"),
790 GetName().c_str());
791 return Type_None;
792 }
793
794 return (ValueType)dwType;
795 }
796
797 #ifdef __WIN32__
798 bool wxRegKey::SetValue(const wxChar *szValue, long lValue)
799 {
800 if ( CONST_CAST Open() ) {
801 m_dwLastError = RegSetValueEx((HKEY) m_hKey, szValue, (DWORD) RESERVED, REG_DWORD,
802 (RegString)&lValue, sizeof(lValue));
803 if ( m_dwLastError == ERROR_SUCCESS )
804 return TRUE;
805 }
806
807 wxLogSysError(m_dwLastError, _("Can't set value of '%s'"),
808 GetFullName(this, szValue));
809 return FALSE;
810 }
811
812 bool wxRegKey::QueryValue(const wxChar *szValue, long *plValue) const
813 {
814 if ( CONST_CAST Open(Read) ) {
815 DWORD dwType, dwSize = sizeof(DWORD);
816 RegString pBuf = (RegString)plValue;
817 m_dwLastError = RegQueryValueEx((HKEY) m_hKey, WXSTRINGCAST szValue, RESERVED,
818 &dwType, pBuf, &dwSize);
819 if ( m_dwLastError != ERROR_SUCCESS ) {
820 wxLogSysError(m_dwLastError, _("Can't read value of key '%s'"),
821 GetName().c_str());
822 return FALSE;
823 }
824 else {
825 // check that we read the value of right type
826 wxASSERT_MSG( IsNumericValue(szValue),
827 wxT("Type mismatch in wxRegKey::QueryValue().") );
828
829 return TRUE;
830 }
831 }
832 else
833 return FALSE;
834 }
835
836 bool wxRegKey::SetValue(const wxChar *szValue,const wxMemoryBuffer& buffer)
837 {
838 #ifdef __TWIN32__
839 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
840 return FALSE;
841 #else
842 if ( CONST_CAST Open() ) {
843 m_dwLastError = RegSetValueEx((HKEY) m_hKey, szValue, (DWORD) RESERVED, REG_BINARY,
844 (RegBinary)buffer.GetData(),buffer.GetDataLen());
845 if ( m_dwLastError == ERROR_SUCCESS )
846 return TRUE;
847 }
848
849 wxLogSysError(m_dwLastError, _("Can't set value of '%s'"),
850 GetFullName(this, szValue));
851 return FALSE;
852 #endif
853 }
854
855 bool wxRegKey::QueryValue(const wxChar *szValue, wxMemoryBuffer& buffer) const
856 {
857 if ( CONST_CAST Open() ) {
858 // first get the type and size of the data
859 DWORD dwType, dwSize;
860 m_dwLastError = RegQueryValueEx((HKEY) m_hKey, WXSTRINGCAST szValue, RESERVED,
861 &dwType, NULL, &dwSize);
862
863 if ( m_dwLastError == ERROR_SUCCESS ) {
864 if ( dwSize ) {
865 const RegBinary pBuf = (RegBinary)buffer.GetWriteBuf(dwSize);
866 m_dwLastError = RegQueryValueEx((HKEY) m_hKey,
867 WXSTRINGCAST szValue,
868 RESERVED,
869 &dwType,
870 pBuf,
871 &dwSize);
872 buffer.UngetWriteBuf(dwSize);
873 } else {
874 buffer.SetDataLen(0);
875 }
876 }
877
878
879 if ( m_dwLastError != ERROR_SUCCESS ) {
880 wxLogSysError(m_dwLastError, _("Can't read value of key '%s'"),
881 GetName().c_str());
882 return FALSE;
883 }
884 return TRUE;
885 }
886 return FALSE;
887 }
888
889
890
891 #endif //Win32
892
893 bool wxRegKey::QueryValue(const wxChar *szValue,
894 wxString& strValue,
895 bool raw) const
896 {
897 if ( CONST_CAST Open(Read) ) {
898
899 // first get the type and size of the data
900 DWORD dwType, dwSize;
901 m_dwLastError = RegQueryValueEx((HKEY) m_hKey, WXSTRINGCAST szValue, RESERVED,
902 &dwType, NULL, &dwSize);
903 if ( m_dwLastError == ERROR_SUCCESS ) {
904 if ( !dwSize ) {
905 // must treat this case specially as GetWriteBuf() doesn't like
906 // being called with 0 size
907 strValue.Empty();
908 }
909 else {
910 m_dwLastError = RegQueryValueEx((HKEY) m_hKey,
911 WXSTRINGCAST szValue,
912 RESERVED,
913 &dwType,
914 (RegString)(wxChar*)wxStringBuffer(strValue, dwSize),
915 &dwSize);
916
917 // expand the var expansions in the string unless disabled
918 #ifndef __WXWINCE__
919 if ( (dwType == REG_EXPAND_SZ) && !raw )
920 {
921 DWORD dwExpSize = ::ExpandEnvironmentStrings(strValue, NULL, 0);
922 bool ok = dwExpSize != 0;
923 if ( ok )
924 {
925 wxString strExpValue;
926 ok = ::ExpandEnvironmentStrings
927 (
928 strValue,
929 wxStringBuffer(strExpValue, dwExpSize),
930 dwExpSize
931 ) != 0;
932 strValue = strExpValue;
933 }
934
935 if ( !ok )
936 {
937 wxLogLastError(_T("ExpandEnvironmentStrings"));
938 }
939 }
940 #endif
941 // __WXWINCE__
942 }
943
944 if ( m_dwLastError == ERROR_SUCCESS ) {
945 // check that it was the right type
946 wxASSERT_MSG( !IsNumericValue(szValue),
947 wxT("Type mismatch in wxRegKey::QueryValue().") );
948
949 return TRUE;
950 }
951 }
952 }
953
954 wxLogSysError(m_dwLastError, _("Can't read value of '%s'"),
955 GetFullName(this, szValue));
956 return FALSE;
957 }
958
959 bool wxRegKey::SetValue(const wxChar *szValue, const wxString& strValue)
960 {
961 if ( CONST_CAST Open() ) {
962 m_dwLastError = RegSetValueEx((HKEY) m_hKey, szValue, (DWORD) RESERVED, REG_SZ,
963 (RegString)strValue.c_str(),
964 (strValue.Len() + 1)*sizeof(wxChar));
965 if ( m_dwLastError == ERROR_SUCCESS )
966 return TRUE;
967 }
968
969 wxLogSysError(m_dwLastError, _("Can't set value of '%s'"),
970 GetFullName(this, szValue));
971 return FALSE;
972 }
973
974 wxString wxRegKey::QueryDefaultValue() const
975 {
976 wxString str;
977 QueryValue(NULL, str);
978 return str;
979 }
980
981 // ----------------------------------------------------------------------------
982 // enumeration
983 // NB: all these functions require an index variable which allows to have
984 // several concurrently running indexations on the same key
985 // ----------------------------------------------------------------------------
986
987 bool wxRegKey::GetFirstValue(wxString& strValueName, long& lIndex)
988 {
989 if ( !Open(Read) )
990 return FALSE;
991
992 lIndex = 0;
993 return GetNextValue(strValueName, lIndex);
994 }
995
996 bool wxRegKey::GetNextValue(wxString& strValueName, long& lIndex) const
997 {
998 wxASSERT( IsOpened() );
999
1000 // are we already at the end of enumeration?
1001 if ( lIndex == -1 )
1002 return FALSE;
1003
1004 wxChar szValueName[1024]; // @@ use RegQueryInfoKey...
1005 DWORD dwValueLen = WXSIZEOF(szValueName);
1006
1007 m_dwLastError = RegEnumValue((HKEY) m_hKey, lIndex++,
1008 szValueName, &dwValueLen,
1009 RESERVED,
1010 NULL, // [out] type
1011 NULL, // [out] buffer for value
1012 NULL); // [i/o] it's length
1013
1014 if ( m_dwLastError != ERROR_SUCCESS ) {
1015 if ( m_dwLastError == ERROR_NO_MORE_ITEMS ) {
1016 m_dwLastError = ERROR_SUCCESS;
1017 lIndex = -1;
1018 }
1019 else {
1020 wxLogSysError(m_dwLastError, _("Can't enumerate values of key '%s'"),
1021 GetName().c_str());
1022 }
1023
1024 return FALSE;
1025 }
1026
1027 strValueName = szValueName;
1028
1029 return TRUE;
1030 }
1031
1032 bool wxRegKey::GetFirstKey(wxString& strKeyName, long& lIndex)
1033 {
1034 if ( !Open(Read) )
1035 return FALSE;
1036
1037 lIndex = 0;
1038 return GetNextKey(strKeyName, lIndex);
1039 }
1040
1041 bool wxRegKey::GetNextKey(wxString& strKeyName, long& lIndex) const
1042 {
1043 wxASSERT( IsOpened() );
1044
1045 // are we already at the end of enumeration?
1046 if ( lIndex == -1 )
1047 return FALSE;
1048
1049 wxChar szKeyName[_MAX_PATH + 1];
1050
1051 #ifdef __WXWINCE__
1052 DWORD sizeName = WXSIZEOF(szKeyName);
1053 m_dwLastError = RegEnumKeyEx((HKEY) m_hKey, lIndex++, szKeyName, & sizeName,
1054 0, NULL, NULL, NULL);
1055 #else
1056 m_dwLastError = RegEnumKey((HKEY) m_hKey, lIndex++, szKeyName, WXSIZEOF(szKeyName));
1057 #endif
1058
1059 if ( m_dwLastError != ERROR_SUCCESS ) {
1060 if ( m_dwLastError == ERROR_NO_MORE_ITEMS ) {
1061 m_dwLastError = ERROR_SUCCESS;
1062 lIndex = -1;
1063 }
1064 else {
1065 wxLogSysError(m_dwLastError, _("Can't enumerate subkeys of key '%s'"),
1066 GetName().c_str());
1067 }
1068
1069 return FALSE;
1070 }
1071
1072 strKeyName = szKeyName;
1073 return TRUE;
1074 }
1075
1076 // returns TRUE if the value contains a number (else it's some string)
1077 bool wxRegKey::IsNumericValue(const wxChar *szValue) const
1078 {
1079 ValueType type = GetValueType(szValue);
1080 switch ( type ) {
1081 case Type_Dword:
1082 /* case Type_Dword_little_endian: == Type_Dword */
1083 case Type_Dword_big_endian:
1084 return TRUE;
1085
1086 default:
1087 return FALSE;
1088 }
1089 }
1090
1091 // ============================================================================
1092 // implementation of global private functions
1093 // ============================================================================
1094
1095 bool KeyExists(WXHKEY hRootKey, const wxChar *szKey)
1096 {
1097 // don't close this key itself for the case of empty szKey!
1098 if ( wxIsEmpty(szKey) )
1099 return TRUE;
1100
1101 HKEY hkeyDummy;
1102 if ( ::RegOpenKeyEx
1103 (
1104 (HKEY)hRootKey,
1105 szKey,
1106 RESERVED,
1107 KEY_READ, // we might not have enough rights for rw access
1108 &hkeyDummy
1109 ) == ERROR_SUCCESS )
1110 {
1111 ::RegCloseKey(hkeyDummy);
1112
1113 return TRUE;
1114 }
1115
1116 return FALSE;
1117 }
1118
1119 const wxChar *GetFullName(const wxRegKey *pKey, const wxChar *szValue)
1120 {
1121 static wxString s_str;
1122 s_str = pKey->GetName();
1123 if ( !wxIsEmpty(szValue) )
1124 s_str << wxT("\\") << szValue;
1125
1126 return s_str.c_str();
1127 }
1128
1129 void RemoveTrailingSeparator(wxString& str)
1130 {
1131 if ( !str.IsEmpty() && str.Last() == REG_SEPARATOR )
1132 str.Truncate(str.Len() - 1);
1133 }
1134