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