]> git.saurik.com Git - wxWidgets.git/blob - src/msw/registry.cpp
dwCallback if DWORD.
[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.IsEmpty(), 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.IsEmpty() ) {
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'."),
612 GetFullName(&key), keyName.c_str());
613
614 }
615
616 // copy all values
617 wxString strVal;
618 bCont = GetFirstValue(strVal, lIndex);
619 while ( ok && bCont ) {
620 ok = CopyValue(strVal, keyDst);
621
622 if ( !ok ) {
623 wxLogSysError(m_dwLastError,
624 _("Failed to copy registry value '%s'"),
625 strVal.c_str());
626 }
627 else {
628 bCont = GetNextValue(strVal, lIndex);
629 }
630 }
631
632 if ( !ok ) {
633 wxLogError(_("Failed to copy the contents of registry key '%s' to '%s'."),
634 GetFullName(this), GetFullName(&keyDst));
635 }
636
637 return ok;
638 }
639
640 // ----------------------------------------------------------------------------
641 // delete keys/values
642 // ----------------------------------------------------------------------------
643 bool wxRegKey::DeleteSelf()
644 {
645 {
646 wxLogNull nolog;
647 if ( !Open() ) {
648 // it already doesn't exist - ok!
649 return true;
650 }
651 }
652
653 // prevent a buggy program from erasing one of the root registry keys or an
654 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
655 // key except HKCR (HKCR has some "deleteable" subkeys)
656 if ( m_strKey.IsEmpty() ||
657 ((m_hRootKey != (WXHKEY) aStdKeys[HKCR].hkey) &&
658 (m_strKey.Find(REG_SEPARATOR) == wxNOT_FOUND)) ) {
659 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
660 GetFullName(this));
661
662 return false;
663 }
664
665 // we can't delete keys while enumerating because it confuses GetNextKey, so
666 // we first save the key names and then delete them all
667 wxArrayString astrSubkeys;
668
669 wxString strKey;
670 long lIndex;
671 bool bCont = GetFirstKey(strKey, lIndex);
672 while ( bCont ) {
673 astrSubkeys.Add(strKey);
674
675 bCont = GetNextKey(strKey, lIndex);
676 }
677
678 size_t nKeyCount = astrSubkeys.Count();
679 for ( size_t nKey = 0; nKey < nKeyCount; nKey++ ) {
680 wxRegKey key(*this, astrSubkeys[nKey]);
681 if ( !key.DeleteSelf() )
682 return false;
683 }
684
685 // now delete this key itself
686 Close();
687
688 m_dwLastError = RegDeleteKey((HKEY) m_hRootKey, m_strKey);
689 // deleting a key which doesn't exist is not considered an error
690 if ( m_dwLastError != ERROR_SUCCESS &&
691 m_dwLastError != ERROR_FILE_NOT_FOUND ) {
692 wxLogSysError(m_dwLastError, _("Can't delete key '%s'"),
693 GetName().c_str());
694 return false;
695 }
696
697 return true;
698 }
699
700 bool wxRegKey::DeleteKey(const wxChar *szKey)
701 {
702 if ( !Open() )
703 return false;
704
705 wxRegKey key(*this, szKey);
706 return key.DeleteSelf();
707 }
708
709 bool wxRegKey::DeleteValue(const wxChar *szValue)
710 {
711 if ( !Open() )
712 return false;
713
714 m_dwLastError = RegDeleteValue((HKEY) m_hKey, WXSTRINGCAST szValue);
715
716 // deleting a value which doesn't exist is not considered an error
717 if ( (m_dwLastError != ERROR_SUCCESS) &&
718 (m_dwLastError != ERROR_FILE_NOT_FOUND) ) {
719 wxLogSysError(m_dwLastError, _("Can't delete value '%s' from key '%s'"),
720 szValue, GetName().c_str());
721 return false;
722 }
723
724 return true;
725 }
726
727 // ----------------------------------------------------------------------------
728 // access to values and subkeys
729 // ----------------------------------------------------------------------------
730
731 // return true if value exists
732 bool wxRegKey::HasValue(const wxChar *szValue) const
733 {
734 // this function should be silent, so suppress possible messages from Open()
735 wxLogNull nolog;
736
737 if ( !CONST_CAST Open(Read) )
738 return false;
739
740 LONG dwRet = ::RegQueryValueEx((HKEY) m_hKey,
741 WXSTRINGCAST szValue,
742 RESERVED,
743 NULL, NULL, NULL);
744 return dwRet == ERROR_SUCCESS;
745 }
746
747 // returns true if this key has any values
748 bool wxRegKey::HasValues() const
749 {
750 // suppress possible messages from GetFirstValue()
751 wxLogNull nolog;
752
753 // just call GetFirstValue with dummy parameters
754 wxString str;
755 long l;
756 return CONST_CAST GetFirstValue(str, l);
757 }
758
759 // returns true if this key has any subkeys
760 bool wxRegKey::HasSubkeys() const
761 {
762 // suppress possible messages from GetFirstKey()
763 wxLogNull nolog;
764
765 // just call GetFirstKey with dummy parameters
766 wxString str;
767 long l;
768 return CONST_CAST GetFirstKey(str, l);
769 }
770
771 // returns true if given subkey exists
772 bool wxRegKey::HasSubKey(const wxChar *szKey) const
773 {
774 // this function should be silent, so suppress possible messages from Open()
775 wxLogNull nolog;
776
777 if ( !CONST_CAST Open(Read) )
778 return false;
779
780 return KeyExists(m_hKey, szKey);
781 }
782
783 wxRegKey::ValueType wxRegKey::GetValueType(const wxChar *szValue) const
784 {
785 if ( ! CONST_CAST Open(Read) )
786 return Type_None;
787
788 DWORD dwType;
789 m_dwLastError = RegQueryValueEx((HKEY) m_hKey, WXSTRINGCAST szValue, RESERVED,
790 &dwType, NULL, NULL);
791 if ( m_dwLastError != ERROR_SUCCESS ) {
792 wxLogSysError(m_dwLastError, _("Can't read value of key '%s'"),
793 GetName().c_str());
794 return Type_None;
795 }
796
797 return (ValueType)dwType;
798 }
799
800 #ifdef __WIN32__
801 bool wxRegKey::SetValue(const wxChar *szValue, long lValue)
802 {
803 if ( CONST_CAST Open() ) {
804 m_dwLastError = RegSetValueEx((HKEY) m_hKey, szValue, (DWORD) RESERVED, REG_DWORD,
805 (RegString)&lValue, sizeof(lValue));
806 if ( m_dwLastError == ERROR_SUCCESS )
807 return true;
808 }
809
810 wxLogSysError(m_dwLastError, _("Can't set value of '%s'"),
811 GetFullName(this, szValue));
812 return false;
813 }
814
815 bool wxRegKey::QueryValue(const wxChar *szValue, long *plValue) const
816 {
817 if ( CONST_CAST Open(Read) ) {
818 DWORD dwType, dwSize = sizeof(DWORD);
819 RegString pBuf = (RegString)plValue;
820 m_dwLastError = RegQueryValueEx((HKEY) m_hKey, WXSTRINGCAST szValue, RESERVED,
821 &dwType, pBuf, &dwSize);
822 if ( m_dwLastError != ERROR_SUCCESS ) {
823 wxLogSysError(m_dwLastError, _("Can't read value of key '%s'"),
824 GetName().c_str());
825 return false;
826 }
827 else {
828 // check that we read the value of right type
829 wxASSERT_MSG( IsNumericValue(szValue),
830 wxT("Type mismatch in wxRegKey::QueryValue().") );
831
832 return true;
833 }
834 }
835 else
836 return false;
837 }
838
839 bool wxRegKey::SetValue(const wxChar *szValue,const wxMemoryBuffer& buffer)
840 {
841 #ifdef __TWIN32__
842 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
843 return false;
844 #else
845 if ( CONST_CAST Open() ) {
846 m_dwLastError = RegSetValueEx((HKEY) m_hKey, szValue, (DWORD) RESERVED, REG_BINARY,
847 (RegBinary)buffer.GetData(),buffer.GetDataLen());
848 if ( m_dwLastError == ERROR_SUCCESS )
849 return true;
850 }
851
852 wxLogSysError(m_dwLastError, _("Can't set value of '%s'"),
853 GetFullName(this, szValue));
854 return false;
855 #endif
856 }
857
858 bool wxRegKey::QueryValue(const wxChar *szValue, wxMemoryBuffer& buffer) const
859 {
860 if ( CONST_CAST Open() ) {
861 // first get the type and size of the data
862 DWORD dwType, dwSize;
863 m_dwLastError = RegQueryValueEx((HKEY) m_hKey, WXSTRINGCAST szValue, RESERVED,
864 &dwType, NULL, &dwSize);
865
866 if ( m_dwLastError == ERROR_SUCCESS ) {
867 if ( dwSize ) {
868 const RegBinary pBuf = (RegBinary)buffer.GetWriteBuf(dwSize);
869 m_dwLastError = RegQueryValueEx((HKEY) m_hKey,
870 WXSTRINGCAST szValue,
871 RESERVED,
872 &dwType,
873 pBuf,
874 &dwSize);
875 buffer.UngetWriteBuf(dwSize);
876 } else {
877 buffer.SetDataLen(0);
878 }
879 }
880
881
882 if ( m_dwLastError != ERROR_SUCCESS ) {
883 wxLogSysError(m_dwLastError, _("Can't read value of key '%s'"),
884 GetName().c_str());
885 return false;
886 }
887 return true;
888 }
889 return false;
890 }
891
892
893
894 #endif //Win32
895
896 bool wxRegKey::QueryValue(const wxChar *szValue,
897 wxString& strValue,
898 bool raw) const
899 {
900 if ( CONST_CAST Open(Read) ) {
901
902 // first get the type and size of the data
903 DWORD dwType, dwSize;
904 m_dwLastError = RegQueryValueEx((HKEY) m_hKey, WXSTRINGCAST szValue, RESERVED,
905 &dwType, NULL, &dwSize);
906 if ( m_dwLastError == ERROR_SUCCESS ) {
907 if ( !dwSize ) {
908 // must treat this case specially as GetWriteBuf() doesn't like
909 // being called with 0 size
910 strValue.Empty();
911 }
912 else {
913 m_dwLastError = RegQueryValueEx((HKEY) m_hKey,
914 WXSTRINGCAST szValue,
915 RESERVED,
916 &dwType,
917 (RegString)(wxChar*)wxStringBuffer(strValue, dwSize),
918 &dwSize);
919
920 // expand the var expansions in the string unless disabled
921 #ifndef __WXWINCE__
922 if ( (dwType == REG_EXPAND_SZ) && !raw )
923 {
924 DWORD dwExpSize = ::ExpandEnvironmentStrings(strValue, NULL, 0);
925 bool ok = dwExpSize != 0;
926 if ( ok )
927 {
928 wxString strExpValue;
929 ok = ::ExpandEnvironmentStrings
930 (
931 strValue,
932 wxStringBuffer(strExpValue, dwExpSize),
933 dwExpSize
934 ) != 0;
935 strValue = strExpValue;
936 }
937
938 if ( !ok )
939 {
940 wxLogLastError(_T("ExpandEnvironmentStrings"));
941 }
942 }
943 #else
944 wxUnusedVar(raw);
945 #endif
946 // __WXWINCE__
947 }
948
949 if ( m_dwLastError == ERROR_SUCCESS ) {
950 // check that it was the right type
951 wxASSERT_MSG( !IsNumericValue(szValue),
952 wxT("Type mismatch in wxRegKey::QueryValue().") );
953
954 return true;
955 }
956 }
957 }
958
959 wxLogSysError(m_dwLastError, _("Can't read value of '%s'"),
960 GetFullName(this, szValue));
961 return false;
962 }
963
964 bool wxRegKey::SetValue(const wxChar *szValue, const wxString& strValue)
965 {
966 if ( CONST_CAST Open() ) {
967 m_dwLastError = RegSetValueEx((HKEY) m_hKey, szValue, (DWORD) RESERVED, REG_SZ,
968 (RegString)strValue.c_str(),
969 (strValue.Len() + 1)*sizeof(wxChar));
970 if ( m_dwLastError == ERROR_SUCCESS )
971 return true;
972 }
973
974 wxLogSysError(m_dwLastError, _("Can't set value of '%s'"),
975 GetFullName(this, szValue));
976 return false;
977 }
978
979 wxString wxRegKey::QueryDefaultValue() const
980 {
981 wxString str;
982 QueryValue(NULL, str);
983 return str;
984 }
985
986 // ----------------------------------------------------------------------------
987 // enumeration
988 // NB: all these functions require an index variable which allows to have
989 // several concurrently running indexations on the same key
990 // ----------------------------------------------------------------------------
991
992 bool wxRegKey::GetFirstValue(wxString& strValueName, long& lIndex)
993 {
994 if ( !Open(Read) )
995 return false;
996
997 lIndex = 0;
998 return GetNextValue(strValueName, lIndex);
999 }
1000
1001 bool wxRegKey::GetNextValue(wxString& strValueName, long& lIndex) const
1002 {
1003 wxASSERT( IsOpened() );
1004
1005 // are we already at the end of enumeration?
1006 if ( lIndex == -1 )
1007 return false;
1008
1009 wxChar szValueName[1024]; // @@ use RegQueryInfoKey...
1010 DWORD dwValueLen = WXSIZEOF(szValueName);
1011
1012 m_dwLastError = RegEnumValue((HKEY) m_hKey, lIndex++,
1013 szValueName, &dwValueLen,
1014 RESERVED,
1015 NULL, // [out] type
1016 NULL, // [out] buffer for value
1017 NULL); // [i/o] it's length
1018
1019 if ( m_dwLastError != ERROR_SUCCESS ) {
1020 if ( m_dwLastError == ERROR_NO_MORE_ITEMS ) {
1021 m_dwLastError = ERROR_SUCCESS;
1022 lIndex = -1;
1023 }
1024 else {
1025 wxLogSysError(m_dwLastError, _("Can't enumerate values of key '%s'"),
1026 GetName().c_str());
1027 }
1028
1029 return false;
1030 }
1031
1032 strValueName = szValueName;
1033
1034 return true;
1035 }
1036
1037 bool wxRegKey::GetFirstKey(wxString& strKeyName, long& lIndex)
1038 {
1039 if ( !Open(Read) )
1040 return false;
1041
1042 lIndex = 0;
1043 return GetNextKey(strKeyName, lIndex);
1044 }
1045
1046 bool wxRegKey::GetNextKey(wxString& strKeyName, long& lIndex) const
1047 {
1048 wxASSERT( IsOpened() );
1049
1050 // are we already at the end of enumeration?
1051 if ( lIndex == -1 )
1052 return false;
1053
1054 wxChar szKeyName[_MAX_PATH + 1];
1055
1056 #ifdef __WXWINCE__
1057 DWORD sizeName = WXSIZEOF(szKeyName);
1058 m_dwLastError = RegEnumKeyEx((HKEY) m_hKey, lIndex++, szKeyName, & sizeName,
1059 0, NULL, NULL, NULL);
1060 #else
1061 m_dwLastError = RegEnumKey((HKEY) m_hKey, lIndex++, szKeyName, WXSIZEOF(szKeyName));
1062 #endif
1063
1064 if ( m_dwLastError != ERROR_SUCCESS ) {
1065 if ( m_dwLastError == ERROR_NO_MORE_ITEMS ) {
1066 m_dwLastError = ERROR_SUCCESS;
1067 lIndex = -1;
1068 }
1069 else {
1070 wxLogSysError(m_dwLastError, _("Can't enumerate subkeys of key '%s'"),
1071 GetName().c_str());
1072 }
1073
1074 return false;
1075 }
1076
1077 strKeyName = szKeyName;
1078 return true;
1079 }
1080
1081 // returns true if the value contains a number (else it's some string)
1082 bool wxRegKey::IsNumericValue(const wxChar *szValue) const
1083 {
1084 ValueType type = GetValueType(szValue);
1085 switch ( type ) {
1086 case Type_Dword:
1087 /* case Type_Dword_little_endian: == Type_Dword */
1088 case Type_Dword_big_endian:
1089 return true;
1090
1091 default:
1092 return false;
1093 }
1094 }
1095
1096 // ============================================================================
1097 // implementation of global private functions
1098 // ============================================================================
1099
1100 bool KeyExists(WXHKEY hRootKey, const wxChar *szKey)
1101 {
1102 // don't close this key itself for the case of empty szKey!
1103 if ( wxIsEmpty(szKey) )
1104 return true;
1105
1106 HKEY hkeyDummy;
1107 if ( ::RegOpenKeyEx
1108 (
1109 (HKEY)hRootKey,
1110 szKey,
1111 RESERVED,
1112 KEY_READ, // we might not have enough rights for rw access
1113 &hkeyDummy
1114 ) == ERROR_SUCCESS )
1115 {
1116 ::RegCloseKey(hkeyDummy);
1117
1118 return true;
1119 }
1120
1121 return false;
1122 }
1123
1124 const wxChar *GetFullName(const wxRegKey *pKey, const wxChar *szValue)
1125 {
1126 static wxString s_str;
1127 s_str = pKey->GetName();
1128 if ( !wxIsEmpty(szValue) )
1129 s_str << wxT("\\") << szValue;
1130
1131 return s_str.c_str();
1132 }
1133
1134 void RemoveTrailingSeparator(wxString& str)
1135 {
1136 if ( !str.IsEmpty() && str.Last() == REG_SEPARATOR )
1137 str.Truncate(str.Len() - 1);
1138 }
1139