Include wx/msw/wrap*.h according to pch support (with other minor cleaning).
[wxWidgets.git] / src / msw / registry.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/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 // for compilers that support precompilation, includes "wx.h".
16 #include "wx/wxprec.h"
17
18 #ifdef __BORLANDC__
19 #pragma hdrstop
20 #endif
21
22 #ifndef WX_PRECOMP
23 #include "wx/msw/wrapwin.h"
24 #include "wx/string.h"
25 #include "wx/intl.h"
26 #include "wx/log.h"
27 #endif
28
29 #include "wx/file.h"
30 #include "wx/wfstream.h"
31
32 // Windows headers
33 #ifdef __WXWINCE__
34 #include "wx/msw/private.h"
35 #include <winbase.h>
36 #include <winreg.h>
37 #endif
38
39 // other std headers
40 #include <stdlib.h> // for _MAX_PATH
41
42 #ifndef _MAX_PATH
43 #define _MAX_PATH 512
44 #endif
45
46 // our header
47 #define HKEY_DEFINED // already defined in windows.h
48 #include "wx/msw/registry.h"
49
50 // some registry functions don't like signed chars
51 typedef unsigned char *RegString;
52 typedef BYTE* RegBinary;
53
54 // ----------------------------------------------------------------------------
55 // constants
56 // ----------------------------------------------------------------------------
57
58 // the standard key names, short names and handles all bundled together for
59 // convenient access
60 static struct
61 {
62 HKEY hkey;
63 const wxChar *szName;
64 const wxChar *szShortName;
65 }
66 aStdKeys[] =
67 {
68 { HKEY_CLASSES_ROOT, wxT("HKEY_CLASSES_ROOT"), wxT("HKCR") },
69 { HKEY_CURRENT_USER, wxT("HKEY_CURRENT_USER"), wxT("HKCU") },
70 { HKEY_LOCAL_MACHINE, wxT("HKEY_LOCAL_MACHINE"), wxT("HKLM") },
71 { HKEY_USERS, wxT("HKEY_USERS"), wxT("HKU") }, // short name?
72 #ifndef __WXWINCE__
73 { HKEY_PERFORMANCE_DATA, wxT("HKEY_PERFORMANCE_DATA"), wxT("HKPD") },
74 #endif
75 #ifdef HKEY_CURRENT_CONFIG
76 { HKEY_CURRENT_CONFIG, wxT("HKEY_CURRENT_CONFIG"), wxT("HKCC") },
77 #endif
78 #ifdef HKEY_DYN_DATA
79 { HKEY_DYN_DATA, wxT("HKEY_DYN_DATA"), wxT("HKDD") }, // short name?
80 #endif
81 };
82
83 // the registry name separator (perhaps one day MS will change it to '/' ;-)
84 #define REG_SEPARATOR wxT('\\')
85
86 // useful for Windows programmers: makes somewhat more clear all these zeroes
87 // being passed to Windows APIs
88 #define RESERVED (0)
89
90 // ----------------------------------------------------------------------------
91 // macros
92 // ----------------------------------------------------------------------------
93
94 // const_cast<> is not yet supported by all compilers
95 #define CONST_CAST ((wxRegKey *)this)->
96
97 // and neither is mutable which m_dwLastError should be
98 #define m_dwLastError CONST_CAST m_dwLastError
99
100 // ----------------------------------------------------------------------------
101 // non member functions
102 // ----------------------------------------------------------------------------
103
104 // removes the trailing backslash from the string if it has one
105 static inline void RemoveTrailingSeparator(wxString& str);
106
107 // returns true if given registry key exists
108 static bool KeyExists(WXHKEY hRootKey, const wxChar *szKey);
109
110 // combines value and key name (uses static buffer!)
111 static const wxChar *GetFullName(const wxRegKey *pKey,
112 const wxChar *szValue = NULL);
113
114 // ============================================================================
115 // implementation of wxRegKey class
116 // ============================================================================
117
118 // ----------------------------------------------------------------------------
119 // static functions and variables
120 // ----------------------------------------------------------------------------
121
122 const size_t wxRegKey::nStdKeys = WXSIZEOF(aStdKeys);
123
124 // @@ should take a `StdKey key', but as it's often going to be used in loops
125 // it would require casts in user code.
126 const wxChar *wxRegKey::GetStdKeyName(size_t key)
127 {
128 // return empty string if key is invalid
129 wxCHECK_MSG( key < nStdKeys, wxEmptyString, wxT("invalid key in wxRegKey::GetStdKeyName") );
130
131 return aStdKeys[key].szName;
132 }
133
134 const wxChar *wxRegKey::GetStdKeyShortName(size_t key)
135 {
136 // return empty string if key is invalid
137 wxCHECK( key < nStdKeys, wxEmptyString );
138
139 return aStdKeys[key].szShortName;
140 }
141
142 wxRegKey::StdKey wxRegKey::ExtractKeyName(wxString& strKey)
143 {
144 wxString strRoot = strKey.BeforeFirst(REG_SEPARATOR);
145
146 HKEY hRootKey = 0;
147 size_t ui;
148 for ( ui = 0; ui < nStdKeys; ui++ ) {
149 if ( strRoot.CmpNoCase(aStdKeys[ui].szName) == 0 ||
150 strRoot.CmpNoCase(aStdKeys[ui].szShortName) == 0 ) {
151 hRootKey = aStdKeys[ui].hkey;
152 break;
153 }
154 }
155
156 if ( ui == nStdKeys ) {
157 wxFAIL_MSG(wxT("invalid key prefix in wxRegKey::ExtractKeyName."));
158
159 hRootKey = HKEY_CLASSES_ROOT;
160 }
161 else {
162 strKey = strKey.After(REG_SEPARATOR);
163 if ( !strKey.empty() && strKey.Last() == REG_SEPARATOR )
164 strKey.Truncate(strKey.Len() - 1);
165 }
166
167 return (wxRegKey::StdKey)(int)hRootKey;
168 }
169
170 wxRegKey::StdKey wxRegKey::GetStdKeyFromHkey(WXHKEY hkey)
171 {
172 for ( size_t ui = 0; ui < nStdKeys; ui++ ) {
173 if ( (int) aStdKeys[ui].hkey == (int) hkey )
174 return (StdKey)ui;
175 }
176
177 wxFAIL_MSG(wxT("non root hkey passed to wxRegKey::GetStdKeyFromHkey."));
178
179 return HKCR;
180 }
181
182 // ----------------------------------------------------------------------------
183 // ctors and dtor
184 // ----------------------------------------------------------------------------
185
186 wxRegKey::wxRegKey()
187 {
188 m_hRootKey = (WXHKEY) aStdKeys[HKCR].hkey;
189
190 Init();
191 }
192
193 wxRegKey::wxRegKey(const wxString& strKey) : m_strKey(strKey)
194 {
195 m_hRootKey = (WXHKEY) aStdKeys[ExtractKeyName(m_strKey)].hkey;
196
197 Init();
198 }
199
200 // parent is a predefined (and preopened) key
201 wxRegKey::wxRegKey(StdKey keyParent, const wxString& strKey) : m_strKey(strKey)
202 {
203 RemoveTrailingSeparator(m_strKey);
204 m_hRootKey = (WXHKEY) aStdKeys[keyParent].hkey;
205
206 Init();
207 }
208
209 // parent is a normal regkey
210 wxRegKey::wxRegKey(const wxRegKey& keyParent, const wxString& strKey)
211 : m_strKey(keyParent.m_strKey)
212 {
213 // combine our name with parent's to get the full name
214 if ( !m_strKey.empty() &&
215 (strKey.empty() || strKey[0] != REG_SEPARATOR) ) {
216 m_strKey += REG_SEPARATOR;
217 }
218
219 m_strKey += strKey;
220 RemoveTrailingSeparator(m_strKey);
221
222 m_hRootKey = keyParent.m_hRootKey;
223
224 Init();
225 }
226
227 // dtor closes the key releasing system resource
228 wxRegKey::~wxRegKey()
229 {
230 Close();
231 }
232
233 // ----------------------------------------------------------------------------
234 // change the key name/hkey
235 // ----------------------------------------------------------------------------
236
237 // set the full key name
238 void wxRegKey::SetName(const wxString& strKey)
239 {
240 Close();
241
242 m_strKey = strKey;
243 m_hRootKey = (WXHKEY) aStdKeys[ExtractKeyName(m_strKey)].hkey;
244 }
245
246 // the name is relative to the parent key
247 void wxRegKey::SetName(StdKey keyParent, const wxString& strKey)
248 {
249 Close();
250
251 m_strKey = strKey;
252 RemoveTrailingSeparator(m_strKey);
253 m_hRootKey = (WXHKEY) aStdKeys[keyParent].hkey;
254 }
255
256 // the name is relative to the parent key
257 void wxRegKey::SetName(const wxRegKey& keyParent, const wxString& strKey)
258 {
259 Close();
260
261 // combine our name with parent's to get the full name
262
263 // NB: this method is called by wxRegConfig::SetPath() which is a performance
264 // critical function and so it preallocates space for our m_strKey to
265 // gain some speed - this is why we only use += here and not = which
266 // would just free the prealloc'd buffer and would have to realloc it the
267 // next line!
268 m_strKey.clear();
269 m_strKey += keyParent.m_strKey;
270 if ( !strKey.empty() && strKey[0] != REG_SEPARATOR )
271 m_strKey += REG_SEPARATOR;
272 m_strKey += strKey;
273
274 RemoveTrailingSeparator(m_strKey);
275
276 m_hRootKey = keyParent.m_hRootKey;
277 }
278
279 // hKey should be opened and will be closed in wxRegKey dtor
280 void wxRegKey::SetHkey(WXHKEY hKey)
281 {
282 Close();
283
284 m_hKey = hKey;
285 }
286
287 // ----------------------------------------------------------------------------
288 // info about the key
289 // ----------------------------------------------------------------------------
290
291 // returns true if the key exists
292 bool wxRegKey::Exists() const
293 {
294 // opened key has to exist, try to open it if not done yet
295 return IsOpened() ? true : KeyExists(m_hRootKey, m_strKey);
296 }
297
298 // returns the full name of the key (prefix is abbreviated if bShortPrefix)
299 wxString wxRegKey::GetName(bool bShortPrefix) const
300 {
301 StdKey key = GetStdKeyFromHkey((WXHKEY) m_hRootKey);
302 wxString str = bShortPrefix ? aStdKeys[key].szShortName
303 : aStdKeys[key].szName;
304 if ( !m_strKey.empty() )
305 str << _T("\\") << m_strKey;
306
307 return str;
308 }
309
310 bool wxRegKey::GetKeyInfo(size_t *pnSubKeys,
311 size_t *pnMaxKeyLen,
312 size_t *pnValues,
313 size_t *pnMaxValueLen) const
314 {
315 // old gcc headers incorrectly prototype RegQueryInfoKey()
316 #if defined(__GNUWIN32_OLD__) && !defined(__CYGWIN10__)
317 #define REG_PARAM (size_t *)
318 #else
319 #define REG_PARAM (LPDWORD)
320 #endif
321
322 // it might be unexpected to some that this function doesn't open the key
323 wxASSERT_MSG( IsOpened(), _T("key should be opened in GetKeyInfo") );
324
325 m_dwLastError = ::RegQueryInfoKey
326 (
327 (HKEY) m_hKey,
328 NULL, // class name
329 NULL, // (ptr to) size of class name buffer
330 RESERVED,
331 REG_PARAM
332 pnSubKeys, // [out] number of subkeys
333 REG_PARAM
334 pnMaxKeyLen, // [out] max length of a subkey name
335 NULL, // longest subkey class name
336 REG_PARAM
337 pnValues, // [out] number of values
338 REG_PARAM
339 pnMaxValueLen, // [out] max length of a value name
340 NULL, // longest value data
341 NULL, // security descriptor
342 NULL // time of last modification
343 );
344
345 #undef REG_PARAM
346
347 if ( m_dwLastError != ERROR_SUCCESS ) {
348 wxLogSysError(m_dwLastError, _("Can't get info about registry key '%s'"),
349 GetName().c_str());
350 return false;
351 }
352
353 return true;
354 }
355
356 // ----------------------------------------------------------------------------
357 // operations
358 // ----------------------------------------------------------------------------
359
360 // opens key (it's not an error to call Open() on an already opened key)
361 bool wxRegKey::Open(AccessMode mode)
362 {
363 if ( IsOpened() )
364 {
365 if ( mode <= m_mode )
366 return true;
367
368 // we had been opened in read mode but now must be reopened in write
369 Close();
370 }
371
372 HKEY tmpKey;
373 m_dwLastError = ::RegOpenKeyEx
374 (
375 (HKEY) m_hRootKey,
376 m_strKey,
377 RESERVED,
378 mode == Read ? KEY_READ : KEY_ALL_ACCESS,
379 &tmpKey
380 );
381
382 if ( m_dwLastError != ERROR_SUCCESS )
383 {
384 wxLogSysError(m_dwLastError, _("Can't open registry key '%s'"),
385 GetName().c_str());
386 return false;
387 }
388
389 m_hKey = (WXHKEY) tmpKey;
390 m_mode = mode;
391
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 case Type_Binary:
496 {
497 wxMemoryBuffer buf;
498 return QueryValue(szValue,buf) &&
499 keyDst.SetValue(szValueNew,buf);
500 }
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 default:
515 wxLogError(_("Can't copy values of unsupported type %d."),
516 GetValueType(szValue));
517 return false;
518 }
519 }
520
521 bool wxRegKey::Rename(const wxChar *szNewName)
522 {
523 wxCHECK_MSG( !m_strKey.empty(), false, _T("registry hives can't be renamed") );
524
525 if ( !Exists() ) {
526 wxLogError(_("Registry key '%s' does not exist, cannot rename it."),
527 GetFullName(this));
528
529 return false;
530 }
531
532 // do we stay in the same hive?
533 bool inSameHive = !wxStrchr(szNewName, REG_SEPARATOR);
534
535 // construct the full new name of the key
536 wxRegKey keyDst;
537
538 if ( inSameHive ) {
539 // rename the key to the new name under the same parent
540 wxString strKey = m_strKey.BeforeLast(REG_SEPARATOR);
541 if ( !strKey.empty() ) {
542 // don't add '\\' in the start if strFullNewName is empty
543 strKey += REG_SEPARATOR;
544 }
545
546 strKey += szNewName;
547
548 keyDst.SetName(GetStdKeyFromHkey(m_hRootKey), strKey);
549 }
550 else {
551 // this is the full name already
552 keyDst.SetName(szNewName);
553 }
554
555 bool ok = keyDst.Create(false /* fail if alredy exists */);
556 if ( !ok ) {
557 wxLogError(_("Registry key '%s' already exists."),
558 GetFullName(&keyDst));
559 }
560 else {
561 ok = Copy(keyDst) && DeleteSelf();
562 }
563
564 if ( !ok ) {
565 wxLogError(_("Failed to rename the registry key '%s' to '%s'."),
566 GetFullName(this), GetFullName(&keyDst));
567 }
568 else {
569 m_hRootKey = keyDst.m_hRootKey;
570 m_strKey = keyDst.m_strKey;
571 }
572
573 return ok;
574 }
575
576 bool wxRegKey::Copy(const wxChar *szNewName)
577 {
578 // create the new key first
579 wxRegKey keyDst(szNewName);
580 bool ok = keyDst.Create(false /* fail if alredy exists */);
581 if ( ok ) {
582 ok = Copy(keyDst);
583
584 // we created the dest key but copying to it failed - delete it
585 if ( !ok ) {
586 (void)keyDst.DeleteSelf();
587 }
588 }
589
590 return ok;
591 }
592
593 bool wxRegKey::Copy(wxRegKey& keyDst)
594 {
595 bool ok = true;
596
597 // copy all sub keys to the new location
598 wxString strKey;
599 long lIndex;
600 bool bCont = GetFirstKey(strKey, lIndex);
601 while ( ok && bCont ) {
602 wxRegKey key(*this, strKey);
603 wxString keyName;
604 keyName << GetFullName(&keyDst) << REG_SEPARATOR << strKey;
605 ok = key.Copy((const wxChar*) keyName);
606
607 if ( ok )
608 bCont = GetNextKey(strKey, lIndex);
609 else
610 wxLogError(_("Failed to copy the registry subkey '%s' to '%s'."),
611 GetFullName(&key), keyName.c_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'."),
633 GetFullName(this), GetFullName(&keyDst));
634 }
635
636 return ok;
637 }
638
639 // ----------------------------------------------------------------------------
640 // delete keys/values
641 // ----------------------------------------------------------------------------
642 bool wxRegKey::DeleteSelf()
643 {
644 {
645 wxLogNull nolog;
646 if ( !Open() ) {
647 // it already doesn't exist - ok!
648 return true;
649 }
650 }
651
652 // prevent a buggy program from erasing one of the root registry keys or an
653 // immediate subkey (i.e. one which doesn't have '\\' inside) of any other
654 // key except HKCR (HKCR has some "deleteable" subkeys)
655 if ( m_strKey.empty() ||
656 ((m_hRootKey != (WXHKEY) aStdKeys[HKCR].hkey) &&
657 (m_strKey.Find(REG_SEPARATOR) == wxNOT_FOUND)) ) {
658 wxLogError(_("Registry key '%s' is needed for normal system operation,\ndeleting it will leave your system in unusable state:\noperation aborted."),
659 GetFullName(this));
660
661 return false;
662 }
663
664 // we can't delete keys while enumerating because it confuses GetNextKey, so
665 // we first save the key names and then delete them all
666 wxArrayString astrSubkeys;
667
668 wxString strKey;
669 long lIndex;
670 bool bCont = GetFirstKey(strKey, lIndex);
671 while ( bCont ) {
672 astrSubkeys.Add(strKey);
673
674 bCont = GetNextKey(strKey, lIndex);
675 }
676
677 size_t nKeyCount = astrSubkeys.Count();
678 for ( size_t nKey = 0; nKey < nKeyCount; nKey++ ) {
679 wxRegKey key(*this, astrSubkeys[nKey]);
680 if ( !key.DeleteSelf() )
681 return false;
682 }
683
684 // now delete this key itself
685 Close();
686
687 m_dwLastError = RegDeleteKey((HKEY) m_hRootKey, m_strKey);
688 // deleting a key which doesn't exist is not considered an error
689 if ( m_dwLastError != ERROR_SUCCESS &&
690 m_dwLastError != ERROR_FILE_NOT_FOUND ) {
691 wxLogSysError(m_dwLastError, _("Can't delete key '%s'"),
692 GetName().c_str());
693 return false;
694 }
695
696 return true;
697 }
698
699 bool wxRegKey::DeleteKey(const wxChar *szKey)
700 {
701 if ( !Open() )
702 return false;
703
704 wxRegKey key(*this, szKey);
705 return key.DeleteSelf();
706 }
707
708 bool wxRegKey::DeleteValue(const wxChar *szValue)
709 {
710 if ( !Open() )
711 return false;
712
713 m_dwLastError = RegDeleteValue((HKEY) m_hKey, WXSTRINGCAST szValue);
714
715 // deleting a value which doesn't exist is not considered an error
716 if ( (m_dwLastError != ERROR_SUCCESS) &&
717 (m_dwLastError != ERROR_FILE_NOT_FOUND) )
718 {
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 bool wxRegKey::SetValue(const wxChar *szValue, long lValue)
801 {
802 if ( CONST_CAST Open() ) {
803 m_dwLastError = RegSetValueEx((HKEY) m_hKey, szValue, (DWORD) RESERVED, REG_DWORD,
804 (RegString)&lValue, sizeof(lValue));
805 if ( m_dwLastError == ERROR_SUCCESS )
806 return true;
807 }
808
809 wxLogSysError(m_dwLastError, _("Can't set value of '%s'"),
810 GetFullName(this, szValue));
811 return false;
812 }
813
814 bool wxRegKey::QueryValue(const wxChar *szValue, long *plValue) const
815 {
816 if ( CONST_CAST Open(Read) ) {
817 DWORD dwType, dwSize = sizeof(DWORD);
818 RegString pBuf = (RegString)plValue;
819 m_dwLastError = RegQueryValueEx((HKEY) m_hKey, WXSTRINGCAST szValue, RESERVED,
820 &dwType, pBuf, &dwSize);
821 if ( m_dwLastError != ERROR_SUCCESS ) {
822 wxLogSysError(m_dwLastError, _("Can't read value of key '%s'"),
823 GetName().c_str());
824 return false;
825 }
826 else {
827 // check that we read the value of right type
828 wxASSERT_MSG( IsNumericValue(szValue),
829 wxT("Type mismatch in wxRegKey::QueryValue().") );
830
831 return true;
832 }
833 }
834 else
835 return false;
836 }
837
838 bool wxRegKey::SetValue(const wxChar *szValue,const wxMemoryBuffer& buffer)
839 {
840 #ifdef __TWIN32__
841 wxFAIL_MSG("RegSetValueEx not implemented by TWIN32");
842 return false;
843 #else
844 if ( CONST_CAST Open() ) {
845 m_dwLastError = RegSetValueEx((HKEY) m_hKey, szValue, (DWORD) RESERVED, REG_BINARY,
846 (RegBinary)buffer.GetData(),buffer.GetDataLen());
847 if ( m_dwLastError == ERROR_SUCCESS )
848 return true;
849 }
850
851 wxLogSysError(m_dwLastError, _("Can't set value of '%s'"),
852 GetFullName(this, szValue));
853 return false;
854 #endif
855 }
856
857 bool wxRegKey::QueryValue(const wxChar *szValue, wxMemoryBuffer& buffer) const
858 {
859 if ( CONST_CAST Open(Read) ) {
860 // first get the type and size of the data
861 DWORD dwType, dwSize;
862 m_dwLastError = RegQueryValueEx((HKEY) m_hKey, WXSTRINGCAST szValue, RESERVED,
863 &dwType, NULL, &dwSize);
864
865 if ( m_dwLastError == ERROR_SUCCESS ) {
866 if ( dwSize ) {
867 const RegBinary pBuf = (RegBinary)buffer.GetWriteBuf(dwSize);
868 m_dwLastError = RegQueryValueEx((HKEY) m_hKey,
869 WXSTRINGCAST szValue,
870 RESERVED,
871 &dwType,
872 pBuf,
873 &dwSize);
874 buffer.UngetWriteBuf(dwSize);
875 } else {
876 buffer.SetDataLen(0);
877 }
878 }
879
880
881 if ( m_dwLastError != ERROR_SUCCESS ) {
882 wxLogSysError(m_dwLastError, _("Can't read value of key '%s'"),
883 GetName().c_str());
884 return false;
885 }
886 return true;
887 }
888 return false;
889 }
890
891
892
893 bool wxRegKey::QueryValue(const wxChar *szValue,
894 wxString& strValue,
895 bool WXUNUSED_IN_WINCE(raw)) const
896 {
897 if ( CONST_CAST Open(Read) )
898 {
899
900 // first get the type and size of the data
901 DWORD dwType=REG_NONE, dwSize=0;
902 m_dwLastError = RegQueryValueEx((HKEY) m_hKey, WXSTRINGCAST szValue, RESERVED,
903 &dwType, NULL, &dwSize);
904 if ( m_dwLastError == ERROR_SUCCESS )
905 {
906 if ( !dwSize )
907 {
908 // must treat this case specially as GetWriteBuf() doesn't like
909 // being called with 0 size
910 strValue.Empty();
911 }
912 else
913 {
914 m_dwLastError = RegQueryValueEx((HKEY) m_hKey,
915 WXSTRINGCAST szValue,
916 RESERVED,
917 &dwType,
918 (RegString)(wxChar*)wxStringBuffer(strValue, dwSize),
919 &dwSize);
920
921 // expand the var expansions in the string unless disabled
922 #ifndef __WXWINCE__
923 if ( (dwType == REG_EXPAND_SZ) && !raw )
924 {
925 DWORD dwExpSize = ::ExpandEnvironmentStrings(strValue, NULL, 0);
926 bool ok = dwExpSize != 0;
927 if ( ok )
928 {
929 wxString strExpValue;
930 ok = ::ExpandEnvironmentStrings(strValue,
931 wxStringBuffer(strExpValue, dwExpSize),
932 dwExpSize
933 ) != 0;
934 strValue = strExpValue;
935 }
936
937 if ( !ok )
938 {
939 wxLogLastError(_T("ExpandEnvironmentStrings"));
940 }
941 }
942 #endif
943 // __WXWINCE__
944 }
945
946 if ( m_dwLastError == ERROR_SUCCESS )
947 {
948 // check that it was the right type
949 wxASSERT_MSG( !IsNumericValue(szValue),
950 wxT("Type mismatch in wxRegKey::QueryValue().") );
951
952 return true;
953 }
954 }
955 }
956
957 wxLogSysError(m_dwLastError, _("Can't read value of '%s'"),
958 GetFullName(this, szValue));
959 return false;
960 }
961
962 bool wxRegKey::SetValue(const wxChar *szValue, const wxString& strValue)
963 {
964 if ( CONST_CAST Open() ) {
965 m_dwLastError = RegSetValueEx((HKEY) m_hKey, szValue, (DWORD) RESERVED, REG_SZ,
966 (RegString)strValue.c_str(),
967 (strValue.Len() + 1)*sizeof(wxChar));
968 if ( m_dwLastError == ERROR_SUCCESS )
969 return true;
970 }
971
972 wxLogSysError(m_dwLastError, _("Can't set value of '%s'"),
973 GetFullName(this, szValue));
974 return false;
975 }
976
977 wxString wxRegKey::QueryDefaultValue() const
978 {
979 wxString str;
980 QueryValue(NULL, str);
981 return str;
982 }
983
984 // ----------------------------------------------------------------------------
985 // enumeration
986 // NB: all these functions require an index variable which allows to have
987 // several concurrently running indexations on the same key
988 // ----------------------------------------------------------------------------
989
990 bool wxRegKey::GetFirstValue(wxString& strValueName, long& lIndex)
991 {
992 if ( !Open(Read) )
993 return false;
994
995 lIndex = 0;
996 return GetNextValue(strValueName, lIndex);
997 }
998
999 bool wxRegKey::GetNextValue(wxString& strValueName, long& lIndex) const
1000 {
1001 wxASSERT( IsOpened() );
1002
1003 // are we already at the end of enumeration?
1004 if ( lIndex == -1 )
1005 return false;
1006
1007 wxChar szValueName[1024]; // @@ use RegQueryInfoKey...
1008 DWORD dwValueLen = WXSIZEOF(szValueName);
1009
1010 m_dwLastError = RegEnumValue((HKEY) m_hKey, lIndex++,
1011 szValueName, &dwValueLen,
1012 RESERVED,
1013 NULL, // [out] type
1014 NULL, // [out] buffer for value
1015 NULL); // [i/o] it's length
1016
1017 if ( m_dwLastError != ERROR_SUCCESS ) {
1018 if ( m_dwLastError == ERROR_NO_MORE_ITEMS ) {
1019 m_dwLastError = ERROR_SUCCESS;
1020 lIndex = -1;
1021 }
1022 else {
1023 wxLogSysError(m_dwLastError, _("Can't enumerate values of key '%s'"),
1024 GetName().c_str());
1025 }
1026
1027 return false;
1028 }
1029
1030 strValueName = szValueName;
1031
1032 return true;
1033 }
1034
1035 bool wxRegKey::GetFirstKey(wxString& strKeyName, long& lIndex)
1036 {
1037 if ( !Open(Read) )
1038 return false;
1039
1040 lIndex = 0;
1041 return GetNextKey(strKeyName, lIndex);
1042 }
1043
1044 bool wxRegKey::GetNextKey(wxString& strKeyName, long& lIndex) const
1045 {
1046 wxASSERT( IsOpened() );
1047
1048 // are we already at the end of enumeration?
1049 if ( lIndex == -1 )
1050 return false;
1051
1052 wxChar szKeyName[_MAX_PATH + 1];
1053
1054 #ifdef __WXWINCE__
1055 DWORD sizeName = WXSIZEOF(szKeyName);
1056 m_dwLastError = RegEnumKeyEx((HKEY) m_hKey, lIndex++, szKeyName, & sizeName,
1057 0, NULL, NULL, NULL);
1058 #else
1059 m_dwLastError = RegEnumKey((HKEY) m_hKey, lIndex++, szKeyName, WXSIZEOF(szKeyName));
1060 #endif
1061
1062 if ( m_dwLastError != ERROR_SUCCESS ) {
1063 if ( m_dwLastError == ERROR_NO_MORE_ITEMS ) {
1064 m_dwLastError = ERROR_SUCCESS;
1065 lIndex = -1;
1066 }
1067 else {
1068 wxLogSysError(m_dwLastError, _("Can't enumerate subkeys of key '%s'"),
1069 GetName().c_str());
1070 }
1071
1072 return false;
1073 }
1074
1075 strKeyName = szKeyName;
1076 return true;
1077 }
1078
1079 // returns true if the value contains a number (else it's some string)
1080 bool wxRegKey::IsNumericValue(const wxChar *szValue) const
1081 {
1082 ValueType type = GetValueType(szValue);
1083 switch ( type ) {
1084 case Type_Dword:
1085 /* case Type_Dword_little_endian: == Type_Dword */
1086 case Type_Dword_big_endian:
1087 return true;
1088
1089 default:
1090 return false;
1091 }
1092 }
1093
1094 // ----------------------------------------------------------------------------
1095 // exporting registry keys to file
1096 // ----------------------------------------------------------------------------
1097
1098 #if wxUSE_STREAMS
1099
1100 // helper functions for writing ASCII strings (even in Unicode build)
1101 static inline bool WriteAsciiChar(wxOutputStream& ostr, char ch)
1102 {
1103 ostr.PutC(ch);
1104 return ostr.IsOk();
1105 }
1106
1107 static inline bool WriteAsciiEOL(wxOutputStream& ostr)
1108 {
1109 // as we open the file in text mode, it is enough to write LF without CR
1110 return WriteAsciiChar(ostr, '\n');
1111 }
1112
1113 static inline bool WriteAsciiString(wxOutputStream& ostr, const char *p)
1114 {
1115 return ostr.Write(p, strlen(p)).IsOk();
1116 }
1117
1118 static inline bool WriteAsciiString(wxOutputStream& ostr, const wxString& s)
1119 {
1120 #if wxUSE_UNICODE
1121 wxCharBuffer name(s.mb_str());
1122 ostr.Write(name, strlen(name));
1123 #else
1124 ostr.Write(s, s.length());
1125 #endif
1126
1127 return ostr.IsOk();
1128 }
1129
1130 #endif // wxUSE_STREAMS
1131
1132 bool wxRegKey::Export(const wxString& filename) const
1133 {
1134 #if wxUSE_FFILE && wxUSE_STREAMS
1135 if ( wxFile::Exists(filename) )
1136 {
1137 wxLogError(_("Exporting registry key: file \"%s\" already exists and won't be overwritten."),
1138 filename.c_str());
1139 return false;
1140 }
1141
1142 wxFFileOutputStream ostr(filename, _T("w"));
1143
1144 return ostr.Ok() && Export(ostr);
1145 #else
1146 wxUnusedVar(filename);
1147 return false;
1148 #endif
1149 }
1150
1151 #if wxUSE_STREAMS
1152 bool wxRegKey::Export(wxOutputStream& ostr) const
1153 {
1154 // write out the header
1155 if ( !WriteAsciiString(ostr, "REGEDIT4\n\n") )
1156 return false;
1157
1158 return DoExport(ostr);
1159 }
1160 #endif // wxUSE_STREAMS
1161
1162 static
1163 wxString
1164 FormatAsHex(const void *data,
1165 size_t size,
1166 wxRegKey::ValueType type = wxRegKey::Type_Binary)
1167 {
1168 wxString value(_T("hex"));
1169
1170 // binary values use just "hex:" prefix while the other ones must indicate
1171 // the real type
1172 if ( type != wxRegKey::Type_Binary )
1173 value << _T('(') << type << _T(')');
1174 value << _T(':');
1175
1176 // write all the rest as comma-separated bytes
1177 value.reserve(3*size + 10);
1178 const char * const p = wx_static_cast(const char *, data);
1179 for ( size_t n = 0; n < size; n++ )
1180 {
1181 // TODO: line wrapping: although not required by regedit, this makes
1182 // the generated files easier to read and compare with the files
1183 // produced by regedit
1184 if ( n )
1185 value << _T(',');
1186
1187 value << wxString::Format(_T("%02x"), (unsigned char)p[n]);
1188 }
1189
1190 return value;
1191 }
1192
1193 static inline
1194 wxString FormatAsHex(const wxString& value, wxRegKey::ValueType type)
1195 {
1196 return FormatAsHex(value.c_str(), value.length() + 1, type);
1197 }
1198
1199 wxString wxRegKey::FormatValue(const wxString& name) const
1200 {
1201 wxString rhs;
1202 const ValueType type = GetValueType(name);
1203 switch ( type )
1204 {
1205 case Type_String:
1206 {
1207 wxString value;
1208 if ( !QueryValue(name, value) )
1209 break;
1210
1211 // quotes and backslashes must be quoted, linefeeds are not
1212 // allowed in string values
1213 rhs.reserve(value.length() + 2);
1214 rhs = _T('"');
1215
1216 // there can be no NULs here
1217 bool useHex = false;
1218 for ( const wxChar *p = value.c_str(); *p && !useHex; p++ )
1219 {
1220 switch ( *p )
1221 {
1222 case _T('\n'):
1223 // we can only represent this string in hex
1224 useHex = true;
1225 break;
1226
1227 case _T('"'):
1228 case _T('\\'):
1229 // escape special symbol
1230 rhs += _T('\\');
1231 // fall through
1232
1233 default:
1234 rhs += *p;
1235 }
1236 }
1237
1238 if ( useHex )
1239 rhs = FormatAsHex(value, Type_String);
1240 else
1241 rhs += _T('"');
1242 }
1243 break;
1244
1245 case Type_Dword:
1246 /* case Type_Dword_little_endian: == Type_Dword */
1247 {
1248 long value;
1249 if ( !QueryValue(name, &value) )
1250 break;
1251
1252 rhs.Printf(_T("dword:%08x"), (unsigned int)value);
1253 }
1254 break;
1255
1256 case Type_Expand_String:
1257 case Type_Multi_String:
1258 {
1259 wxString value;
1260 if ( !QueryRawValue(name, value) )
1261 break;
1262
1263 rhs = FormatAsHex(value, type);
1264 }
1265 break;
1266
1267 case Type_Binary:
1268 {
1269 wxMemoryBuffer buf;
1270 if ( !QueryValue(name, buf) )
1271 break;
1272
1273 rhs = FormatAsHex(buf.GetData(), buf.GetDataLen());
1274 }
1275 break;
1276
1277 // no idea how those appear in REGEDIT4 files
1278 case Type_None:
1279 case Type_Dword_big_endian:
1280 case Type_Link:
1281 case Type_Resource_list:
1282 case Type_Full_resource_descriptor:
1283 case Type_Resource_requirements_list:
1284 default:
1285 wxLogWarning(_("Can't export value of unsupported type %d."), type);
1286 }
1287
1288 return rhs;
1289 }
1290
1291 #if wxUSE_STREAMS
1292
1293 bool wxRegKey::DoExportValue(wxOutputStream& ostr, const wxString& name) const
1294 {
1295 // first examine the value type: if it's unsupported, simply skip it
1296 // instead of aborting the entire export process because we failed to
1297 // export a single value
1298 wxString value = FormatValue(name);
1299 if ( value.empty() )
1300 {
1301 wxLogWarning(_("Ignoring value \"%s\" of the key \"%s\"."),
1302 name.c_str(), GetName().c_str());
1303 return true;
1304 }
1305
1306 // we do have the text representation of the value, now write everything
1307 // out
1308
1309 // special case: unnamed/default value is represented as just "@"
1310 if ( name.empty() )
1311 {
1312 if ( !WriteAsciiChar(ostr, '@') )
1313 return false;
1314 }
1315 else // normal, named, value
1316 {
1317 if ( !WriteAsciiChar(ostr, '"') ||
1318 !WriteAsciiString(ostr, name) ||
1319 !WriteAsciiChar(ostr, '"') )
1320 return false;
1321 }
1322
1323 if ( !WriteAsciiChar(ostr, '=') )
1324 return false;
1325
1326 return WriteAsciiString(ostr, value) && WriteAsciiEOL(ostr);
1327 }
1328
1329 bool wxRegKey::DoExport(wxOutputStream& ostr) const
1330 {
1331 // write out this key name
1332 if ( !WriteAsciiChar(ostr, '[') )
1333 return false;
1334
1335 if ( !WriteAsciiString(ostr, GetName(false /* no short prefix */)) )
1336 return false;
1337
1338 if ( !WriteAsciiChar(ostr, ']') || !WriteAsciiEOL(ostr) )
1339 return false;
1340
1341 // dump all our values
1342 long dummy;
1343 wxString name;
1344 wxRegKey& self = wx_const_cast(wxRegKey&, *this);
1345 bool cont = self.GetFirstValue(name, dummy);
1346 while ( cont )
1347 {
1348 if ( !DoExportValue(ostr, name) )
1349 return false;
1350
1351 cont = GetNextValue(name, dummy);
1352 }
1353
1354 // always terminate values by blank line, even if there were no values
1355 if ( !WriteAsciiEOL(ostr) )
1356 return false;
1357
1358 // recurse to subkeys
1359 cont = self.GetFirstKey(name, dummy);
1360 while ( cont )
1361 {
1362 wxRegKey subkey(*this, name);
1363 if ( !subkey.DoExport(ostr) )
1364 return false;
1365
1366 cont = GetNextKey(name, dummy);
1367 }
1368
1369 return true;
1370 }
1371
1372 #endif // wxUSE_STREAMS
1373
1374 // ============================================================================
1375 // implementation of global private functions
1376 // ============================================================================
1377
1378 bool KeyExists(WXHKEY hRootKey, const wxChar *szKey)
1379 {
1380 // don't close this key itself for the case of empty szKey!
1381 if ( wxIsEmpty(szKey) )
1382 return true;
1383
1384 HKEY hkeyDummy;
1385 if ( ::RegOpenKeyEx
1386 (
1387 (HKEY)hRootKey,
1388 szKey,
1389 RESERVED,
1390 KEY_READ, // we might not have enough rights for rw access
1391 &hkeyDummy
1392 ) == ERROR_SUCCESS )
1393 {
1394 ::RegCloseKey(hkeyDummy);
1395
1396 return true;
1397 }
1398
1399 return false;
1400 }
1401
1402 const wxChar *GetFullName(const wxRegKey *pKey, const wxChar *szValue)
1403 {
1404 static wxString s_str;
1405 s_str = pKey->GetName();
1406 if ( !wxIsEmpty(szValue) )
1407 s_str << wxT("\\") << szValue;
1408
1409 return s_str.c_str();
1410 }
1411
1412 void RemoveTrailingSeparator(wxString& str)
1413 {
1414 if ( !str.empty() && str.Last() == REG_SEPARATOR )
1415 str.Truncate(str.Len() - 1);
1416 }