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