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