1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: implementation of wxFileConfig derivation of wxConfig
4 // Author: Vadim Zeitlin
6 // Created: 07.04.98 (adapted from appconf.cpp)
8 // Copyright: (c) 1997 Karsten Ballüder & Vadim Zeitlin
9 // Ballueder@usa.net <zeitlin@dptmaths.ens-cachan.fr>
10 // Licence: wxWindows license
11 ///////////////////////////////////////////////////////////////////////////////
14 #pragma implementation "fileconf.h"
17 // ----------------------------------------------------------------------------
19 // ----------------------------------------------------------------------------
21 #include "wx/wxprec.h"
30 #include "wx/string.h"
35 #include "wx/dynarray.h"
38 #include "wx/textfile.h"
39 #include "wx/config.h"
40 #include "wx/fileconf.h"
42 #include "wx/utils.h" // for wxGetHomeDir
44 // _WINDOWS_ is defined when windows.h is included,
45 // __WXMSW__ is defined for MS Windows compilation
46 #if defined(__WXMSW__) && !defined(_WINDOWS_)
57 // ----------------------------------------------------------------------------
59 // ----------------------------------------------------------------------------
60 #define CONST_CAST ((wxFileConfig *)this)->
62 // ----------------------------------------------------------------------------
64 // ----------------------------------------------------------------------------
69 // ----------------------------------------------------------------------------
70 // global functions declarations
71 // ----------------------------------------------------------------------------
73 // compare functions for sorting the arrays
74 static int LINKAGEMODE
CompareEntries(ConfigEntry
*p1
, ConfigEntry
*p2
);
75 static int LINKAGEMODE
CompareGroups(ConfigGroup
*p1
, ConfigGroup
*p2
);
78 static wxString
FilterInValue(const wxString
& str
);
79 static wxString
FilterOutValue(const wxString
& str
);
81 static wxString
FilterInEntryName(const wxString
& str
);
82 static wxString
FilterOutEntryName(const wxString
& str
);
84 // get the name to use in wxFileConfig ctor
85 static wxString
GetAppName(const wxString
& appname
);
87 // ============================================================================
89 // ============================================================================
91 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
94 wxString
wxFileConfig::GetGlobalDir()
98 #ifdef __VMS__ // Note if __VMS is defined __UNIX is also defined
99 strDir
= wxT("sys$manager:");
100 #elif defined( __UNIX__ )
101 strDir
= wxT("/etc/");
102 #elif defined(__WXPM__)
103 ULONG aulSysInfo
[QSV_MAX
] = {0};
107 rc
= DosQuerySysInfo( 1L, QSV_MAX
, (PVOID
)aulSysInfo
, sizeof(ULONG
)*QSV_MAX
);
110 drive
= aulSysInfo
[QSV_BOOT_DRIVE
- 1];
114 strDir
= "A:\\OS2\\";
117 strDir
= "B:\\OS2\\";
120 strDir
= "C:\\OS2\\";
123 strDir
= "D:\\OS2\\";
126 strDir
= "E:\\OS2\\";
129 strDir
= "F:\\OS2\\";
132 strDir
= "G:\\OS2\\";
135 strDir
= "H:\\OS2\\";
138 strDir
= "I:\\OS2\\";
141 strDir
= "J:\\OS2\\";
144 strDir
= "K:\\OS2\\";
147 strDir
= "L:\\OS2\\";
150 strDir
= "M:\\OS2\\";
153 strDir
= "N:\\OS2\\";
156 strDir
= "O:\\OS2\\";
159 strDir
= "P:\\OS2\\";
162 strDir
= "Q:\\OS2\\";
165 strDir
= "R:\\OS2\\";
168 strDir
= "S:\\OS2\\";
171 strDir
= "T:\\OS2\\";
174 strDir
= "U:\\OS2\\";
177 strDir
= "V:\\OS2\\";
180 strDir
= "W:\\OS2\\";
183 strDir
= "X:\\OS2\\";
186 strDir
= "Y:\\OS2\\";
189 strDir
= "Z:\\OS2\\";
193 #elif defined(__WXSTUBS__)
194 wxASSERT_MSG( FALSE
, wxT("TODO") ) ;
195 #elif defined(__WXMAC__)
200 if ( FindFolder( (short) kOnSystemDisk
, kPreferencesFolderType
, kDontCreateFolder
, &vRefNum
, &dirID
) == noErr
)
203 if ( FSMakeFSSpec( vRefNum
, dirID
, "\p" , &file
) == noErr
)
205 strDir
= wxMacFSSpec2UnixFilename( &file
) + "/" ;
210 wxChar szWinDir
[MAX_PATH
];
211 ::GetWindowsDirectory(szWinDir
, MAX_PATH
);
215 #endif // Unix/Windows
220 wxString
wxFileConfig::GetLocalDir()
225 wxGetHomeDir(&strDir
);
229 if (strDir
.Last() != wxT('/')) strDir
<< wxT('/');
231 if (strDir
.Last() != wxT('\\')) strDir
<< wxT('\\');
235 // no local dir concept on mac
236 return GetGlobalDir() ;
242 wxString
wxFileConfig::GetGlobalFileName(const wxChar
*szFile
)
244 wxString str
= GetGlobalDir();
247 if ( wxStrchr(szFile
, wxT('.')) == NULL
)
250 #elif defined( __WXMAC__ )
251 str
<< " Preferences";
259 wxString
wxFileConfig::GetLocalFileName(const wxChar
*szFile
)
261 #ifdef __VMS__ // On VMS I saw the problem that the home directory was appended
262 // twice for the configuration file. Does that also happen for other
264 wxString str
= wxT( ' ' );
266 wxString str
= GetLocalDir();
276 if ( wxStrchr(szFile
, wxT('.')) == NULL
)
282 str
<< " Preferences";
287 // ----------------------------------------------------------------------------
289 // ----------------------------------------------------------------------------
291 void wxFileConfig::Init()
294 m_pRootGroup
= new ConfigGroup(NULL
, "", this);
299 // it's not an error if (one of the) file(s) doesn't exist
301 // parse the global file
302 if ( !m_strGlobalFile
.IsEmpty() && wxFile::Exists(m_strGlobalFile
) ) {
303 wxTextFile
fileGlobal(m_strGlobalFile
);
305 if ( fileGlobal
.Open() ) {
306 Parse(fileGlobal
, FALSE
/* global */);
310 wxLogWarning(_("can't open global configuration file '%s'."),
311 m_strGlobalFile
.c_str());
314 // parse the local file
315 if ( !m_strLocalFile
.IsEmpty() && wxFile::Exists(m_strLocalFile
) ) {
316 wxTextFile
fileLocal(m_strLocalFile
);
317 if ( fileLocal
.Open() ) {
318 Parse(fileLocal
, TRUE
/* local */);
322 wxLogWarning(_("can't open user configuration file '%s'."),
323 m_strLocalFile
.c_str());
327 // constructor supports creation of wxFileConfig objects of any type
328 wxFileConfig::wxFileConfig(const wxString
& appName
, const wxString
& vendorName
,
329 const wxString
& strLocal
, const wxString
& strGlobal
,
331 : wxConfigBase(::GetAppName(appName
), vendorName
,
334 m_strLocalFile(strLocal
), m_strGlobalFile(strGlobal
)
336 // Make up names for files if empty
337 if ( m_strLocalFile
.IsEmpty() && (style
& wxCONFIG_USE_LOCAL_FILE
) )
339 m_strLocalFile
= GetLocalFileName(GetAppName());
342 if ( m_strGlobalFile
.IsEmpty() && (style
& wxCONFIG_USE_GLOBAL_FILE
) )
344 m_strGlobalFile
= GetGlobalFileName(GetAppName());
347 // Check if styles are not supplied, but filenames are, in which case
348 // add the correct styles.
349 if ( !m_strLocalFile
.IsEmpty() )
350 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
352 if ( !m_strGlobalFile
.IsEmpty() )
353 SetStyle(GetStyle() | wxCONFIG_USE_GLOBAL_FILE
);
355 // if the path is not absolute, prepend the standard directory to it
356 // UNLESS wxCONFIG_USE_RELATIVE_PATH style is set
357 if ( !(style
& wxCONFIG_USE_RELATIVE_PATH
) )
359 if ( !m_strLocalFile
.IsEmpty() && !wxIsAbsolutePath(m_strLocalFile
) )
361 wxString strLocal
= m_strLocalFile
;
362 m_strLocalFile
= GetLocalDir();
363 m_strLocalFile
<< strLocal
;
366 if ( !m_strGlobalFile
.IsEmpty() && !wxIsAbsolutePath(m_strGlobalFile
) )
368 wxString strGlobal
= m_strGlobalFile
;
369 m_strGlobalFile
= GetGlobalDir();
370 m_strGlobalFile
<< strGlobal
;
377 void wxFileConfig::CleanUp()
381 LineList
*pCur
= m_linesHead
;
382 while ( pCur
!= NULL
) {
383 LineList
*pNext
= pCur
->Next();
389 wxFileConfig::~wxFileConfig()
396 // ----------------------------------------------------------------------------
397 // parse a config file
398 // ----------------------------------------------------------------------------
400 void wxFileConfig::Parse(wxTextFile
& file
, bool bLocal
)
402 const wxChar
*pStart
;
406 size_t nLineCount
= file
.GetLineCount();
407 for ( size_t n
= 0; n
< nLineCount
; n
++ ) {
410 // add the line to linked list
412 LineListAppend(strLine
);
414 // skip leading spaces
415 for ( pStart
= strLine
; wxIsspace(*pStart
); pStart
++ )
418 // skip blank/comment lines
419 if ( *pStart
== wxT('\0')|| *pStart
== wxT(';') || *pStart
== wxT('#') )
422 if ( *pStart
== wxT('[') ) { // a new group
425 while ( *++pEnd
!= wxT(']') ) {
426 if ( *pEnd
== wxT('\n') || *pEnd
== wxT('\0') )
430 if ( *pEnd
!= wxT(']') ) {
431 wxLogError(_("file '%s': unexpected character %c at line %d."),
432 file
.GetName(), *pEnd
, n
+ 1);
433 continue; // skip this line
436 // group name here is always considered as abs path
439 strGroup
<< wxCONFIG_PATH_SEPARATOR
440 << FilterInEntryName(wxString(pStart
, pEnd
- pStart
));
442 // will create it if doesn't yet exist
446 m_pCurrentGroup
->SetLine(m_linesTail
);
448 // check that there is nothing except comments left on this line
450 while ( *++pEnd
!= wxT('\0') && bCont
) {
459 // ignore whitespace ('\n' impossible here)
463 wxLogWarning(_("file '%s', line %d: '%s' "
464 "ignored after group header."),
465 file
.GetName(), n
+ 1, pEnd
);
472 const wxChar
*pEnd
= pStart
;
473 while ( *pEnd
!= wxT('=') && !wxIsspace(*pEnd
) ) {
474 if ( *pEnd
== wxT('\\') ) {
475 // next character may be space or not - still take it because it's
484 wxString
strKey(FilterInEntryName(wxString(pStart
, count
)));
487 while ( isspace(*pEnd
) )
490 if ( *pEnd
++ != wxT('=') ) {
491 wxLogError(_("file '%s', line %d: '=' expected."),
492 file
.GetName(), n
+ 1);
495 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strKey
);
497 if ( pEntry
== NULL
) {
499 pEntry
= m_pCurrentGroup
->AddEntry(strKey
, n
);
502 pEntry
->SetLine(m_linesTail
);
505 if ( bLocal
&& pEntry
->IsImmutable() ) {
506 // immutable keys can't be changed by user
507 wxLogWarning(_("file '%s', line %d: value for "
508 "immutable key '%s' ignored."),
509 file
.GetName(), n
+ 1, strKey
.c_str());
512 // the condition below catches the cases (a) and (b) but not (c):
513 // (a) global key found second time in global file
514 // (b) key found second (or more) time in local file
515 // (c) key from global file now found in local one
516 // which is exactly what we want.
517 else if ( !bLocal
|| pEntry
->IsLocal() ) {
518 wxLogWarning(_("file '%s', line %d: key '%s' was first "
519 "found at line %d."),
520 file
.GetName(), n
+ 1, strKey
.c_str(), pEntry
->Line());
523 pEntry
->SetLine(m_linesTail
);
528 while ( wxIsspace(*pEnd
) )
531 pEntry
->SetValue(FilterInValue(pEnd
), FALSE
/* read from file */);
537 // ----------------------------------------------------------------------------
539 // ----------------------------------------------------------------------------
541 void wxFileConfig::SetRootPath()
544 m_pCurrentGroup
= m_pRootGroup
;
547 void wxFileConfig::SetPath(const wxString
& strPath
)
549 wxArrayString aParts
;
551 if ( strPath
.IsEmpty() ) {
556 if ( strPath
[0] == wxCONFIG_PATH_SEPARATOR
) {
558 wxSplitPath(aParts
, strPath
);
561 // relative path, combine with current one
562 wxString strFullPath
= m_strPath
;
563 strFullPath
<< wxCONFIG_PATH_SEPARATOR
<< strPath
;
564 wxSplitPath(aParts
, strFullPath
);
567 // change current group
569 m_pCurrentGroup
= m_pRootGroup
;
570 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
571 ConfigGroup
*pNextGroup
= m_pCurrentGroup
->FindSubgroup(aParts
[n
]);
572 if ( pNextGroup
== NULL
)
573 pNextGroup
= m_pCurrentGroup
->AddSubgroup(aParts
[n
]);
574 m_pCurrentGroup
= pNextGroup
;
577 // recombine path parts in one variable
579 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
580 m_strPath
<< wxCONFIG_PATH_SEPARATOR
<< aParts
[n
];
584 // ----------------------------------------------------------------------------
586 // ----------------------------------------------------------------------------
588 bool wxFileConfig::GetFirstGroup(wxString
& str
, long& lIndex
) const
591 return GetNextGroup(str
, lIndex
);
594 bool wxFileConfig::GetNextGroup (wxString
& str
, long& lIndex
) const
596 if ( size_t(lIndex
) < m_pCurrentGroup
->Groups().Count() ) {
597 str
= m_pCurrentGroup
->Groups()[(size_t)lIndex
++]->Name();
604 bool wxFileConfig::GetFirstEntry(wxString
& str
, long& lIndex
) const
607 return GetNextEntry(str
, lIndex
);
610 bool wxFileConfig::GetNextEntry (wxString
& str
, long& lIndex
) const
612 if ( size_t(lIndex
) < m_pCurrentGroup
->Entries().Count() ) {
613 str
= m_pCurrentGroup
->Entries()[(size_t)lIndex
++]->Name();
620 size_t wxFileConfig::GetNumberOfEntries(bool bRecursive
) const
622 size_t n
= m_pCurrentGroup
->Entries().Count();
624 ConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
625 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
626 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
627 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
628 n
+= GetNumberOfEntries(TRUE
);
629 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
636 size_t wxFileConfig::GetNumberOfGroups(bool bRecursive
) const
638 size_t n
= m_pCurrentGroup
->Groups().Count();
640 ConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
641 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
642 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
643 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
644 n
+= GetNumberOfGroups(TRUE
);
645 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
652 // ----------------------------------------------------------------------------
653 // tests for existence
654 // ----------------------------------------------------------------------------
656 bool wxFileConfig::HasGroup(const wxString
& strName
) const
658 wxConfigPathChanger
path(this, strName
);
660 ConfigGroup
*pGroup
= m_pCurrentGroup
->FindSubgroup(path
.Name());
661 return pGroup
!= NULL
;
664 bool wxFileConfig::HasEntry(const wxString
& strName
) const
666 wxConfigPathChanger
path(this, strName
);
668 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
669 return pEntry
!= NULL
;
672 // ----------------------------------------------------------------------------
674 // ----------------------------------------------------------------------------
676 bool wxFileConfig::Read(const wxString
& key
,
677 wxString
* pStr
) const
679 wxConfigPathChanger
path(this, key
);
681 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
682 if (pEntry
== NULL
) {
686 *pStr
= ExpandEnvVars(pEntry
->Value());
691 bool wxFileConfig::Read(const wxString
& key
,
692 wxString
* pStr
, const wxString
& defVal
) const
694 wxConfigPathChanger
path(this, key
);
696 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
697 if (pEntry
== NULL
) {
698 if( IsRecordingDefaults() )
699 ((wxFileConfig
*)this)->Write(key
,defVal
);
700 *pStr
= ExpandEnvVars(defVal
);
704 *pStr
= ExpandEnvVars(pEntry
->Value());
709 bool wxFileConfig::Read(const wxString
& key
, long *pl
) const
712 if ( Read(key
, & str
) ) {
721 bool wxFileConfig::Write(const wxString
& key
, const wxString
& szValue
)
723 wxConfigPathChanger
path(this, key
);
725 wxString strName
= path
.Name();
726 if ( strName
.IsEmpty() ) {
727 // setting the value of a group is an error
728 wxASSERT_MSG( wxIsEmpty(szValue
), wxT("can't set value of a group!") );
730 // ... except if it's empty in which case it's a way to force it's creation
731 m_pCurrentGroup
->SetDirty();
733 // this will add a line for this group if it didn't have it before
734 (void)m_pCurrentGroup
->GetGroupLine();
739 // check that the name is reasonable
740 if ( strName
[0u] == wxCONFIG_IMMUTABLE_PREFIX
) {
741 wxLogError(_("Config entry name cannot start with '%c'."),
742 wxCONFIG_IMMUTABLE_PREFIX
);
746 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strName
);
747 if ( pEntry
== NULL
)
748 pEntry
= m_pCurrentGroup
->AddEntry(strName
);
750 pEntry
->SetValue(szValue
);
756 bool wxFileConfig::Write(const wxString
& key
, long lValue
)
758 // ltoa() is not ANSI :-(
760 buf
.Printf(wxT("%ld"), lValue
);
761 return Write(key
, buf
);
764 bool wxFileConfig::Flush(bool /* bCurrentOnly */)
766 if ( LineListIsEmpty() || !m_pRootGroup
->IsDirty() || !m_strLocalFile
)
769 wxTempFile
file(m_strLocalFile
);
771 if ( !file
.IsOpened() ) {
772 wxLogError(_("can't open user configuration file."));
776 // write all strings to file
777 for ( LineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() ) {
778 if ( !file
.Write(p
->Text() + wxTextFile::GetEOL()) ) {
779 wxLogError(_("can't write user configuration file."));
785 return file
.Commit();
787 bool ret
= file
.Commit();
792 wxUnixFilename2FSSpec( m_strLocalFile
, &spec
) ;
794 if ( FSpGetFInfo( &spec
, &finfo
) == noErr
)
796 finfo
.fdType
= 'TEXT' ;
797 finfo
.fdCreator
= 'ttxt' ;
798 FSpSetFInfo( &spec
, &finfo
) ;
805 // ----------------------------------------------------------------------------
806 // renaming groups/entries
807 // ----------------------------------------------------------------------------
809 bool wxFileConfig::RenameEntry(const wxString
& oldName
,
810 const wxString
& newName
)
812 // check that the entry exists
813 ConfigEntry
*oldEntry
= m_pCurrentGroup
->FindEntry(oldName
);
817 // check that the new entry doesn't already exist
818 if ( m_pCurrentGroup
->FindEntry(newName
) )
821 // delete the old entry, create the new one
822 wxString value
= oldEntry
->Value();
823 if ( !m_pCurrentGroup
->DeleteEntry(oldName
) )
826 ConfigEntry
*newEntry
= m_pCurrentGroup
->AddEntry(newName
);
827 newEntry
->SetValue(value
);
832 bool wxFileConfig::RenameGroup(const wxString
& oldName
,
833 const wxString
& newName
)
835 // check that the group exists
836 ConfigGroup
*group
= m_pCurrentGroup
->FindSubgroup(oldName
);
840 // check that the new group doesn't already exist
841 if ( m_pCurrentGroup
->FindSubgroup(newName
) )
844 group
->Rename(newName
);
849 // ----------------------------------------------------------------------------
850 // delete groups/entries
851 // ----------------------------------------------------------------------------
853 bool wxFileConfig::DeleteEntry(const wxString
& key
, bool bGroupIfEmptyAlso
)
855 wxConfigPathChanger
path(this, key
);
857 if ( !m_pCurrentGroup
->DeleteEntry(path
.Name()) )
860 if ( bGroupIfEmptyAlso
&& m_pCurrentGroup
->IsEmpty() ) {
861 if ( m_pCurrentGroup
!= m_pRootGroup
) {
862 ConfigGroup
*pGroup
= m_pCurrentGroup
;
863 SetPath(wxT("..")); // changes m_pCurrentGroup!
864 m_pCurrentGroup
->DeleteSubgroupByName(pGroup
->Name());
866 //else: never delete the root group
872 bool wxFileConfig::DeleteGroup(const wxString
& key
)
874 wxConfigPathChanger
path(this, key
);
876 return m_pCurrentGroup
->DeleteSubgroupByName(path
.Name());
879 bool wxFileConfig::DeleteAll()
883 if ( remove(m_strLocalFile
.fn_str()) == -1 )
884 wxLogSysError(_("can't delete user configuration file '%s'"), m_strLocalFile
.c_str());
886 m_strLocalFile
= m_strGlobalFile
= wxT("");
892 // ----------------------------------------------------------------------------
893 // linked list functions
894 // ----------------------------------------------------------------------------
896 // append a new line to the end of the list
897 LineList
*wxFileConfig::LineListAppend(const wxString
& str
)
899 LineList
*pLine
= new LineList(str
);
901 if ( m_linesTail
== NULL
) {
907 m_linesTail
->SetNext(pLine
);
908 pLine
->SetPrev(m_linesTail
);
915 // insert a new line after the given one or in the very beginning if !pLine
916 LineList
*wxFileConfig::LineListInsert(const wxString
& str
,
919 if ( pLine
== m_linesTail
)
920 return LineListAppend(str
);
922 LineList
*pNewLine
= new LineList(str
);
923 if ( pLine
== NULL
) {
924 // prepend to the list
925 pNewLine
->SetNext(m_linesHead
);
926 m_linesHead
->SetPrev(pNewLine
);
927 m_linesHead
= pNewLine
;
930 // insert before pLine
931 LineList
*pNext
= pLine
->Next();
932 pNewLine
->SetNext(pNext
);
933 pNewLine
->SetPrev(pLine
);
934 pNext
->SetPrev(pNewLine
);
935 pLine
->SetNext(pNewLine
);
941 void wxFileConfig::LineListRemove(LineList
*pLine
)
943 LineList
*pPrev
= pLine
->Prev(),
944 *pNext
= pLine
->Next();
950 pPrev
->SetNext(pNext
);
956 pNext
->SetPrev(pPrev
);
961 bool wxFileConfig::LineListIsEmpty()
963 return m_linesHead
== NULL
;
966 // ============================================================================
967 // wxFileConfig::ConfigGroup
968 // ============================================================================
970 // ----------------------------------------------------------------------------
972 // ----------------------------------------------------------------------------
975 ConfigGroup::ConfigGroup(ConfigGroup
*pParent
,
976 const wxString
& strName
,
977 wxFileConfig
*pConfig
)
978 : m_aEntries(CompareEntries
),
979 m_aSubgroups(CompareGroups
),
991 // dtor deletes all children
992 ConfigGroup::~ConfigGroup()
995 size_t n
, nCount
= m_aEntries
.Count();
996 for ( n
= 0; n
< nCount
; n
++ )
997 delete m_aEntries
[n
];
1000 nCount
= m_aSubgroups
.Count();
1001 for ( n
= 0; n
< nCount
; n
++ )
1002 delete m_aSubgroups
[n
];
1005 // ----------------------------------------------------------------------------
1007 // ----------------------------------------------------------------------------
1009 void ConfigGroup::SetLine(LineList
*pLine
)
1011 wxASSERT( m_pLine
== NULL
); // shouldn't be called twice
1017 This is a bit complicated, so let me explain it in details. All lines that
1018 were read from the local file (the only one we will ever modify) are stored
1019 in a (doubly) linked list. Our problem is to know at which position in this
1020 list should we insert the new entries/subgroups. To solve it we keep three
1021 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1023 m_pLine points to the line containing "[group_name]"
1024 m_pLastEntry points to the last entry of this group in the local file.
1025 m_pLastGroup subgroup
1027 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1028 from the local file, the corresponding variable is set. However, if the group
1029 was read from the global file and then modified or created by the application
1030 these variables are still NULL and we need to create the corresponding lines.
1031 See the following functions (and comments preceding them) for the details of
1034 Also, when our last entry/group are deleted we need to find the new last
1035 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1036 of lines until it either founds an entry/subgroup (and this is the new last
1037 element) or the m_pLine of the group, in which case there are no more entries
1038 (or subgroups) left and m_pLast<element> becomes NULL.
1040 NB: This last problem could be avoided for entries if we added new entries
1041 immediately after m_pLine, but in this case the entries would appear
1042 backwards in the config file (OTOH, it's not that important) and as we
1043 would still need to do it for the subgroups the code wouldn't have been
1044 significantly less complicated.
1047 // Return the line which contains "[our name]". If we're still not in the list,
1048 // add our line to it immediately after the last line of our parent group if we
1049 // have it or in the very beginning if we're the root group.
1050 LineList
*ConfigGroup::GetGroupLine()
1052 if ( m_pLine
== NULL
) {
1053 ConfigGroup
*pParent
= Parent();
1055 // this group wasn't present in local config file, add it now
1056 if ( pParent
!= NULL
) {
1057 wxString strFullName
;
1058 strFullName
<< wxT("[")
1060 << FilterOutEntryName(GetFullName().c_str() + 1)
1062 m_pLine
= m_pConfig
->LineListInsert(strFullName
,
1063 pParent
->GetLastGroupLine());
1064 pParent
->SetLastGroup(this); // we're surely after all the others
1067 // we return NULL, so that LineListInsert() will insert us in the
1075 // Return the last line belonging to the subgroups of this group (after which
1076 // we can add a new subgroup), if we don't have any subgroups or entries our
1077 // last line is the group line (m_pLine) itself.
1078 LineList
*ConfigGroup::GetLastGroupLine()
1080 // if we have any subgroups, our last line is the last line of the last
1082 if ( m_pLastGroup
!= NULL
) {
1083 LineList
*pLine
= m_pLastGroup
->GetLastGroupLine();
1085 wxASSERT( pLine
!= NULL
); // last group must have !NULL associated line
1089 // no subgroups, so the last line is the line of thelast entry (if any)
1090 return GetLastEntryLine();
1093 // return the last line belonging to the entries of this group (after which
1094 // we can add a new entry), if we don't have any entries we will add the new
1095 // one immediately after the group line itself.
1096 LineList
*ConfigGroup::GetLastEntryLine()
1098 if ( m_pLastEntry
!= NULL
) {
1099 LineList
*pLine
= m_pLastEntry
->GetLine();
1101 wxASSERT( pLine
!= NULL
); // last entry must have !NULL associated line
1105 // no entries: insert after the group header
1106 return GetGroupLine();
1109 // ----------------------------------------------------------------------------
1111 // ----------------------------------------------------------------------------
1113 void ConfigGroup::Rename(const wxString
& newName
)
1115 m_strName
= newName
;
1117 LineList
*line
= GetGroupLine();
1118 wxString strFullName
;
1119 strFullName
<< wxT("[") << (GetFullName().c_str() + 1) << wxT("]"); // +1: no '/'
1120 line
->SetText(strFullName
);
1125 wxString
ConfigGroup::GetFullName() const
1128 return Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR
+ Name();
1133 // ----------------------------------------------------------------------------
1135 // ----------------------------------------------------------------------------
1137 // use binary search because the array is sorted
1139 ConfigGroup::FindEntry(const wxChar
*szName
) const
1143 hi
= m_aEntries
.Count();
1145 ConfigEntry
*pEntry
;
1149 pEntry
= m_aEntries
[i
];
1151 #if wxCONFIG_CASE_SENSITIVE
1152 res
= wxStrcmp(pEntry
->Name(), szName
);
1154 res
= wxStricmp(pEntry
->Name(), szName
);
1169 ConfigGroup::FindSubgroup(const wxChar
*szName
) const
1173 hi
= m_aSubgroups
.Count();
1175 ConfigGroup
*pGroup
;
1179 pGroup
= m_aSubgroups
[i
];
1181 #if wxCONFIG_CASE_SENSITIVE
1182 res
= wxStrcmp(pGroup
->Name(), szName
);
1184 res
= wxStricmp(pGroup
->Name(), szName
);
1198 // ----------------------------------------------------------------------------
1199 // create a new item
1200 // ----------------------------------------------------------------------------
1202 // create a new entry and add it to the current group
1204 ConfigGroup::AddEntry(const wxString
& strName
, int nLine
)
1206 wxASSERT( FindEntry(strName
) == NULL
);
1208 ConfigEntry
*pEntry
= new ConfigEntry(this, strName
, nLine
);
1209 m_aEntries
.Add(pEntry
);
1214 // create a new group and add it to the current group
1216 ConfigGroup::AddSubgroup(const wxString
& strName
)
1218 wxASSERT( FindSubgroup(strName
) == NULL
);
1220 ConfigGroup
*pGroup
= new ConfigGroup(this, strName
, m_pConfig
);
1221 m_aSubgroups
.Add(pGroup
);
1226 // ----------------------------------------------------------------------------
1228 // ----------------------------------------------------------------------------
1231 The delete operations are _very_ slow if we delete the last item of this
1232 group (see comments before GetXXXLineXXX functions for more details),
1233 so it's much better to start with the first entry/group if we want to
1234 delete several of them.
1237 bool ConfigGroup::DeleteSubgroupByName(const wxChar
*szName
)
1239 return DeleteSubgroup(FindSubgroup(szName
));
1242 // doesn't delete the subgroup itself, but does remove references to it from
1243 // all other data structures (and normally the returned pointer should be
1244 // deleted a.s.a.p. because there is nothing much to be done with it anyhow)
1245 bool ConfigGroup::DeleteSubgroup(ConfigGroup
*pGroup
)
1247 wxCHECK( pGroup
!= NULL
, FALSE
); // deleting non existing group?
1249 // delete all entries
1250 size_t nCount
= pGroup
->m_aEntries
.Count();
1251 for ( size_t nEntry
= 0; nEntry
< nCount
; nEntry
++ ) {
1252 LineList
*pLine
= pGroup
->m_aEntries
[nEntry
]->GetLine();
1253 if ( pLine
!= NULL
)
1254 m_pConfig
->LineListRemove(pLine
);
1257 // and subgroups of this sungroup
1258 nCount
= pGroup
->m_aSubgroups
.Count();
1259 for ( size_t nGroup
= 0; nGroup
< nCount
; nGroup
++ ) {
1260 pGroup
->DeleteSubgroup(pGroup
->m_aSubgroups
[0]);
1263 LineList
*pLine
= pGroup
->m_pLine
;
1264 if ( pLine
!= NULL
) {
1265 // notice that we may do this test inside the previous "if" because the
1266 // last entry's line is surely !NULL
1267 if ( pGroup
== m_pLastGroup
) {
1268 // our last entry is being deleted - find the last one which stays
1269 wxASSERT( m_pLine
!= NULL
); // we have a subgroup with !NULL pLine...
1271 // go back until we find a subgroup or reach the group's line
1272 ConfigGroup
*pNewLast
= NULL
;
1273 size_t n
, nSubgroups
= m_aSubgroups
.Count();
1275 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1276 // is it our subgroup?
1277 for ( n
= 0; (pNewLast
== NULL
) && (n
< nSubgroups
); n
++ ) {
1278 // do _not_ call GetGroupLine! we don't want to add it to the local
1279 // file if it's not already there
1280 if ( m_aSubgroups
[n
]->m_pLine
== m_pLine
)
1281 pNewLast
= m_aSubgroups
[n
];
1284 if ( pNewLast
!= NULL
) // found?
1288 if ( pl
== m_pLine
) {
1289 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1291 // we've reached the group line without finding any subgroups
1292 m_pLastGroup
= NULL
;
1295 m_pLastGroup
= pNewLast
;
1298 m_pConfig
->LineListRemove(pLine
);
1303 m_aSubgroups
.Remove(pGroup
);
1309 bool ConfigGroup::DeleteEntry(const wxChar
*szName
)
1311 ConfigEntry
*pEntry
= FindEntry(szName
);
1312 wxCHECK( pEntry
!= NULL
, FALSE
); // deleting non existing item?
1314 LineList
*pLine
= pEntry
->GetLine();
1315 if ( pLine
!= NULL
) {
1316 // notice that we may do this test inside the previous "if" because the
1317 // last entry's line is surely !NULL
1318 if ( pEntry
== m_pLastEntry
) {
1319 // our last entry is being deleted - find the last one which stays
1320 wxASSERT( m_pLine
!= NULL
); // if we have an entry with !NULL pLine...
1322 // go back until we find another entry or reach the group's line
1323 ConfigEntry
*pNewLast
= NULL
;
1324 size_t n
, nEntries
= m_aEntries
.Count();
1326 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1327 // is it our subgroup?
1328 for ( n
= 0; (pNewLast
== NULL
) && (n
< nEntries
); n
++ ) {
1329 if ( m_aEntries
[n
]->GetLine() == m_pLine
)
1330 pNewLast
= m_aEntries
[n
];
1333 if ( pNewLast
!= NULL
) // found?
1337 if ( pl
== m_pLine
) {
1338 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1340 // we've reached the group line without finding any subgroups
1341 m_pLastEntry
= NULL
;
1344 m_pLastEntry
= pNewLast
;
1347 m_pConfig
->LineListRemove(pLine
);
1350 // we must be written back for the changes to be saved
1353 m_aEntries
.Remove(pEntry
);
1359 // ----------------------------------------------------------------------------
1361 // ----------------------------------------------------------------------------
1362 void ConfigGroup::SetDirty()
1365 if ( Parent() != NULL
) // propagate upwards
1366 Parent()->SetDirty();
1369 // ============================================================================
1370 // wxFileConfig::ConfigEntry
1371 // ============================================================================
1373 // ----------------------------------------------------------------------------
1375 // ----------------------------------------------------------------------------
1376 ConfigEntry::ConfigEntry(ConfigGroup
*pParent
,
1377 const wxString
& strName
,
1379 : m_strName(strName
)
1381 wxASSERT( !strName
.IsEmpty() );
1383 m_pParent
= pParent
;
1389 m_bImmutable
= strName
[0] == wxCONFIG_IMMUTABLE_PREFIX
;
1391 m_strName
.erase(0, 1); // remove first character
1394 // ----------------------------------------------------------------------------
1396 // ----------------------------------------------------------------------------
1398 void ConfigEntry::SetLine(LineList
*pLine
)
1400 if ( m_pLine
!= NULL
) {
1401 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1402 Name().c_str(), m_pParent
->GetFullName().c_str());
1406 Group()->SetLastEntry(this);
1409 // second parameter is FALSE if we read the value from file and prevents the
1410 // entry from being marked as 'dirty'
1411 void ConfigEntry::SetValue(const wxString
& strValue
, bool bUser
)
1413 if ( bUser
&& IsImmutable() ) {
1414 wxLogWarning(_("attempt to change immutable key '%s' ignored."),
1419 // do nothing if it's the same value
1420 if ( strValue
== m_strValue
)
1423 m_strValue
= strValue
;
1426 wxString strVal
= FilterOutValue(strValue
);
1428 strLine
<< FilterOutEntryName(m_strName
) << wxT('=') << strVal
;
1430 if ( m_pLine
!= NULL
) {
1431 // entry was read from the local config file, just modify the line
1432 m_pLine
->SetText(strLine
);
1435 // add a new line to the file
1436 wxASSERT( m_nLine
== wxNOT_FOUND
); // consistency check
1438 m_pLine
= Group()->Config()->LineListInsert(strLine
,
1439 Group()->GetLastEntryLine());
1440 Group()->SetLastEntry(this);
1447 void ConfigEntry::SetDirty()
1450 Group()->SetDirty();
1453 // ============================================================================
1455 // ============================================================================
1457 // ----------------------------------------------------------------------------
1458 // compare functions for array sorting
1459 // ----------------------------------------------------------------------------
1461 int CompareEntries(ConfigEntry
*p1
,
1464 #if wxCONFIG_CASE_SENSITIVE
1465 return wxStrcmp(p1
->Name(), p2
->Name());
1467 return wxStricmp(p1
->Name(), p2
->Name());
1471 int CompareGroups(ConfigGroup
*p1
,
1474 #if wxCONFIG_CASE_SENSITIVE
1475 return wxStrcmp(p1
->Name(), p2
->Name());
1477 return wxStricmp(p1
->Name(), p2
->Name());
1481 // ----------------------------------------------------------------------------
1483 // ----------------------------------------------------------------------------
1485 // undo FilterOutValue
1486 static wxString
FilterInValue(const wxString
& str
)
1489 strResult
.Alloc(str
.Len());
1491 bool bQuoted
= !str
.IsEmpty() && str
[0] == '"';
1493 for ( size_t n
= bQuoted
? 1 : 0; n
< str
.Len(); n
++ ) {
1494 if ( str
[n
] == wxT('\\') ) {
1495 switch ( str
[++n
] ) {
1497 strResult
+= wxT('\n');
1501 strResult
+= wxT('\r');
1505 strResult
+= wxT('\t');
1509 strResult
+= wxT('\\');
1513 strResult
+= wxT('"');
1518 if ( str
[n
] != wxT('"') || !bQuoted
)
1519 strResult
+= str
[n
];
1520 else if ( n
!= str
.Len() - 1 ) {
1521 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1524 //else: it's the last quote of a quoted string, ok
1531 // quote the string before writing it to file
1532 static wxString
FilterOutValue(const wxString
& str
)
1538 strResult
.Alloc(str
.Len());
1540 // quoting is necessary to preserve spaces in the beginning of the string
1541 bool bQuote
= wxIsspace(str
[0]) || str
[0] == wxT('"');
1544 strResult
+= wxT('"');
1547 for ( size_t n
= 0; n
< str
.Len(); n
++ ) {
1570 //else: fall through
1573 strResult
+= str
[n
];
1574 continue; // nothing special to do
1577 // we get here only for special characters
1578 strResult
<< wxT('\\') << c
;
1582 strResult
+= wxT('"');
1587 // undo FilterOutEntryName
1588 static wxString
FilterInEntryName(const wxString
& str
)
1591 strResult
.Alloc(str
.Len());
1593 for ( const wxChar
*pc
= str
.c_str(); *pc
!= '\0'; pc
++ ) {
1594 if ( *pc
== wxT('\\') )
1603 // sanitize entry or group name: insert '\\' before any special characters
1604 static wxString
FilterOutEntryName(const wxString
& str
)
1607 strResult
.Alloc(str
.Len());
1609 for ( const wxChar
*pc
= str
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
1612 // we explicitly allow some of "safe" chars and 8bit ASCII characters
1613 // which will probably never have special meaning
1614 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
1615 // should *not* be quoted
1616 if ( !wxIsalnum(c
) && !wxStrchr(wxT("@_/-!.*%"), c
) && ((c
& 0x80) == 0) )
1617 strResult
+= wxT('\\');
1625 // we can't put ?: in the ctor initializer list because it confuses some
1626 // broken compilers (Borland C++)
1627 static wxString
GetAppName(const wxString
& appName
)
1629 if ( !appName
&& wxTheApp
)
1630 return wxTheApp
->GetAppName();
1635 #endif // wxUSE_CONFIG