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 // ----------------------------------------------------------------------------
23 // ----------------------------------------------------------------------------
24 #include "wx/wxprec.h"
31 #include "wx/string.h"
36 #include "wx/dynarray.h"
39 #include "wx/textfile.h"
40 #include "wx/config.h"
41 #include "wx/fileconf.h"
43 #include "wx/utils.h" // for wxGetHomeDir
45 // _WINDOWS_ is defined when windows.h is included,
46 // __WXMSW__ is defined for MS Windows compilation
47 #if defined(__WXMSW__) && !defined(_WINDOWS_)
54 // ----------------------------------------------------------------------------
56 // ----------------------------------------------------------------------------
57 #define CONST_CAST ((wxFileConfig *)this)->
59 // ----------------------------------------------------------------------------
61 // ----------------------------------------------------------------------------
66 // ----------------------------------------------------------------------------
67 // global functions declarations
68 // ----------------------------------------------------------------------------
70 // compare functions for sorting the arrays
71 static int CompareEntries(ConfigEntry
*p1
, ConfigEntry
*p2
);
72 static int CompareGroups(ConfigGroup
*p1
, ConfigGroup
*p2
);
75 static wxString
FilterInValue(const wxString
& str
);
76 static wxString
FilterOutValue(const wxString
& str
);
78 static wxString
FilterInEntryName(const wxString
& str
);
79 static wxString
FilterOutEntryName(const wxString
& str
);
81 // get the name to use in wxFileConfig ctor
82 static wxString
GetAppName(const wxString
& appname
);
84 // ============================================================================
86 // ============================================================================
88 // ----------------------------------------------------------------------------
90 // ----------------------------------------------------------------------------
91 wxString
wxFileConfig::GetGlobalDir()
97 #elif defined(__WXSTUBS__)
98 wxASSERT_MSG( FALSE
, _T("TODO") ) ;
99 #elif defined(__WXMAC__)
100 wxASSERT_MSG( FALSE
, _T("TODO") ) ;
102 wxChar szWinDir
[MAX_PATH
];
103 ::GetWindowsDirectory(szWinDir
, MAX_PATH
);
107 #endif // Unix/Windows
112 wxString
wxFileConfig::GetLocalDir()
116 wxGetHomeDir(&strDir
);
119 if (strDir
.Last() != _T('/')) strDir
<< _T('/');
121 if (strDir
.Last() != _T('\\')) strDir
<< _T('\\');
127 wxString
wxFileConfig::GetGlobalFileName(const wxChar
*szFile
)
129 wxString str
= GetGlobalDir();
132 if ( wxStrchr(szFile
, _T('.')) == NULL
)
142 wxString
wxFileConfig::GetLocalFileName(const wxChar
*szFile
)
144 wxString str
= GetLocalDir();
153 if ( wxStrchr(szFile
, _T('.')) == NULL
)
160 // ----------------------------------------------------------------------------
162 // ----------------------------------------------------------------------------
164 void wxFileConfig::Init()
167 m_pRootGroup
= new ConfigGroup(NULL
, "", this);
172 // it's not an error if (one of the) file(s) doesn't exist
174 // parse the global file
175 if ( !m_strGlobalFile
.IsEmpty() && wxFile::Exists(m_strGlobalFile
) ) {
176 wxTextFile
fileGlobal(m_strGlobalFile
);
178 if ( fileGlobal
.Open() ) {
179 Parse(fileGlobal
, FALSE
/* global */);
183 wxLogWarning(_("can't open global configuration file '%s'."),
184 m_strGlobalFile
.c_str());
187 // parse the local file
188 if ( !m_strLocalFile
.IsEmpty() && wxFile::Exists(m_strLocalFile
) ) {
189 wxTextFile
fileLocal(m_strLocalFile
);
190 if ( fileLocal
.Open() ) {
191 Parse(fileLocal
, TRUE
/* local */);
195 wxLogWarning(_("can't open user configuration file '%s'."),
196 m_strLocalFile
.c_str());
200 // constructor supports creation of wxFileConfig objects of any type
201 wxFileConfig::wxFileConfig(const wxString
& appName
, const wxString
& vendorName
,
202 const wxString
& strLocal
, const wxString
& strGlobal
,
204 : wxConfigBase(::GetAppName(appName
), vendorName
,
207 m_strLocalFile(strLocal
), m_strGlobalFile(strGlobal
)
209 // Make up names for files if empty
210 if ( m_strLocalFile
.IsEmpty() && (style
& wxCONFIG_USE_LOCAL_FILE
) )
212 m_strLocalFile
= GetLocalFileName(GetAppName());
215 if ( m_strGlobalFile
.IsEmpty() && (style
& wxCONFIG_USE_GLOBAL_FILE
) )
217 m_strGlobalFile
= GetGlobalFileName(GetAppName());
220 // Check if styles are not supplied, but filenames are, in which case
221 // add the correct styles.
222 if ( !m_strLocalFile
.IsEmpty() )
223 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
225 if ( !m_strGlobalFile
.IsEmpty() )
226 SetStyle(GetStyle() | wxCONFIG_USE_GLOBAL_FILE
);
228 // if the path is not absolute, prepend the standard directory to it
229 // UNLESS wxCONFIG_USE_RELATIVE_PATH style is set
230 if ( !(style
& wxCONFIG_USE_RELATIVE_PATH
) ){
231 if ( !m_strLocalFile
.IsEmpty() && !wxIsAbsolutePath(m_strLocalFile
) )
233 wxString strLocal
= m_strLocalFile
;
234 m_strLocalFile
= GetLocalDir();
235 m_strLocalFile
<< strLocal
;
238 if ( !m_strGlobalFile
.IsEmpty() && !wxIsAbsolutePath(m_strGlobalFile
) )
240 wxString strGlobal
= m_strGlobalFile
;
241 m_strGlobalFile
= GetGlobalDir();
242 m_strGlobalFile
<< strGlobal
;
249 void wxFileConfig::CleanUp()
253 LineList
*pCur
= m_linesHead
;
254 while ( pCur
!= NULL
) {
255 LineList
*pNext
= pCur
->Next();
261 wxFileConfig::~wxFileConfig()
268 // ----------------------------------------------------------------------------
269 // parse a config file
270 // ----------------------------------------------------------------------------
272 void wxFileConfig::Parse(wxTextFile
& file
, bool bLocal
)
274 const wxChar
*pStart
;
278 size_t nLineCount
= file
.GetLineCount();
279 for ( size_t n
= 0; n
< nLineCount
; n
++ ) {
282 // add the line to linked list
284 LineListAppend(strLine
);
286 // skip leading spaces
287 for ( pStart
= strLine
; wxIsspace(*pStart
); pStart
++ )
290 // skip blank/comment lines
291 if ( *pStart
== _T('\0')|| *pStart
== _T(';') || *pStart
== _T('#') )
294 if ( *pStart
== _T('[') ) { // a new group
297 while ( *++pEnd
!= _T(']') ) {
298 if ( *pEnd
== _T('\n') || *pEnd
== _T('\0') )
302 if ( *pEnd
!= _T(']') ) {
303 wxLogError(_("file '%s': unexpected character %c at line %d."),
304 file
.GetName(), *pEnd
, n
+ 1);
305 continue; // skip this line
308 // group name here is always considered as abs path
311 strGroup
<< wxCONFIG_PATH_SEPARATOR
312 << FilterInEntryName(wxString(pStart
, pEnd
- pStart
));
314 // will create it if doesn't yet exist
318 m_pCurrentGroup
->SetLine(m_linesTail
);
320 // check that there is nothing except comments left on this line
322 while ( *++pEnd
!= _T('\0') && bCont
) {
331 // ignore whitespace ('\n' impossible here)
335 wxLogWarning(_("file '%s', line %d: '%s' "
336 "ignored after group header."),
337 file
.GetName(), n
+ 1, pEnd
);
343 const wxChar
*pEnd
= pStart
;
344 while ( *pEnd
!= _T('=') && !wxIsspace(*pEnd
) ) {
345 if ( *pEnd
== _T('\\') ) {
346 // next character may be space or not - still take it because it's
354 wxString
strKey(FilterInEntryName(wxString(pStart
, pEnd
)));
357 while ( isspace(*pEnd
) )
360 if ( *pEnd
++ != _T('=') ) {
361 wxLogError(_("file '%s', line %d: '=' expected."),
362 file
.GetName(), n
+ 1);
365 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strKey
);
367 if ( pEntry
== NULL
) {
369 pEntry
= m_pCurrentGroup
->AddEntry(strKey
, n
);
372 pEntry
->SetLine(m_linesTail
);
375 if ( bLocal
&& pEntry
->IsImmutable() ) {
376 // immutable keys can't be changed by user
377 wxLogWarning(_("file '%s', line %d: value for "
378 "immutable key '%s' ignored."),
379 file
.GetName(), n
+ 1, strKey
.c_str());
382 // the condition below catches the cases (a) and (b) but not (c):
383 // (a) global key found second time in global file
384 // (b) key found second (or more) time in local file
385 // (c) key from global file now found in local one
386 // which is exactly what we want.
387 else if ( !bLocal
|| pEntry
->IsLocal() ) {
388 wxLogWarning(_("file '%s', line %d: key '%s' was first "
389 "found at line %d."),
390 file
.GetName(), n
+ 1, strKey
.c_str(), pEntry
->Line());
393 pEntry
->SetLine(m_linesTail
);
398 while ( wxIsspace(*pEnd
) )
401 pEntry
->SetValue(FilterInValue(pEnd
), FALSE
/* read from file */);
407 // ----------------------------------------------------------------------------
409 // ----------------------------------------------------------------------------
411 void wxFileConfig::SetRootPath()
414 m_pCurrentGroup
= m_pRootGroup
;
417 void wxFileConfig::SetPath(const wxString
& strPath
)
419 wxArrayString aParts
;
421 if ( strPath
.IsEmpty() ) {
426 if ( strPath
[0] == wxCONFIG_PATH_SEPARATOR
) {
428 wxSplitPath(aParts
, strPath
);
431 // relative path, combine with current one
432 wxString strFullPath
= m_strPath
;
433 strFullPath
<< wxCONFIG_PATH_SEPARATOR
<< strPath
;
434 wxSplitPath(aParts
, strFullPath
);
437 // change current group
439 m_pCurrentGroup
= m_pRootGroup
;
440 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
441 ConfigGroup
*pNextGroup
= m_pCurrentGroup
->FindSubgroup(aParts
[n
]);
442 if ( pNextGroup
== NULL
)
443 pNextGroup
= m_pCurrentGroup
->AddSubgroup(aParts
[n
]);
444 m_pCurrentGroup
= pNextGroup
;
447 // recombine path parts in one variable
449 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
450 m_strPath
<< wxCONFIG_PATH_SEPARATOR
<< aParts
[n
];
454 // ----------------------------------------------------------------------------
456 // ----------------------------------------------------------------------------
458 bool wxFileConfig::GetFirstGroup(wxString
& str
, long& lIndex
) const
461 return GetNextGroup(str
, lIndex
);
464 bool wxFileConfig::GetNextGroup (wxString
& str
, long& lIndex
) const
466 if ( size_t(lIndex
) < m_pCurrentGroup
->Groups().Count() ) {
467 str
= m_pCurrentGroup
->Groups()[lIndex
++]->Name();
474 bool wxFileConfig::GetFirstEntry(wxString
& str
, long& lIndex
) const
477 return GetNextEntry(str
, lIndex
);
480 bool wxFileConfig::GetNextEntry (wxString
& str
, long& lIndex
) const
482 if ( size_t(lIndex
) < m_pCurrentGroup
->Entries().Count() ) {
483 str
= m_pCurrentGroup
->Entries()[lIndex
++]->Name();
490 size_t wxFileConfig::GetNumberOfEntries(bool bRecursive
) const
492 size_t n
= m_pCurrentGroup
->Entries().Count();
494 ConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
495 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
496 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
497 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
498 n
+= GetNumberOfEntries(TRUE
);
499 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
506 size_t wxFileConfig::GetNumberOfGroups(bool bRecursive
) const
508 size_t n
= m_pCurrentGroup
->Groups().Count();
510 ConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
511 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
512 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
513 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
514 n
+= GetNumberOfGroups(TRUE
);
515 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
522 // ----------------------------------------------------------------------------
523 // tests for existence
524 // ----------------------------------------------------------------------------
526 bool wxFileConfig::HasGroup(const wxString
& strName
) const
528 wxConfigPathChanger
path(this, strName
);
530 ConfigGroup
*pGroup
= m_pCurrentGroup
->FindSubgroup(path
.Name());
531 return pGroup
!= NULL
;
534 bool wxFileConfig::HasEntry(const wxString
& strName
) const
536 wxConfigPathChanger
path(this, strName
);
538 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
539 return pEntry
!= NULL
;
542 // ----------------------------------------------------------------------------
544 // ----------------------------------------------------------------------------
546 bool wxFileConfig::Read(const wxString
& key
,
547 wxString
* pStr
) const
549 wxConfigPathChanger
path(this, key
);
551 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
552 if (pEntry
== NULL
) {
556 *pStr
= ExpandEnvVars(pEntry
->Value());
561 bool wxFileConfig::Read(const wxString
& key
,
562 wxString
* pStr
, const wxString
& defVal
) const
564 wxConfigPathChanger
path(this, key
);
566 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
567 if (pEntry
== NULL
) {
568 if( IsRecordingDefaults() )
569 ((wxFileConfig
*)this)->Write(key
,defVal
);
570 *pStr
= ExpandEnvVars(defVal
);
574 *pStr
= ExpandEnvVars(pEntry
->Value());
579 bool wxFileConfig::Read(const wxString
& key
, long *pl
) const
582 if ( Read(key
, & str
) ) {
591 bool wxFileConfig::Write(const wxString
& key
, const wxString
& szValue
)
593 wxConfigPathChanger
path(this, key
);
595 wxString strName
= path
.Name();
596 if ( strName
.IsEmpty() ) {
597 // setting the value of a group is an error
598 wxASSERT_MSG( wxIsEmpty(szValue
), _T("can't set value of a group!") );
600 // ... except if it's empty in which case it's a way to force it's creation
601 m_pCurrentGroup
->SetDirty();
603 // this will add a line for this group if it didn't have it before
604 (void)m_pCurrentGroup
->GetGroupLine();
609 // check that the name is reasonable
610 if ( strName
[0u] == wxCONFIG_IMMUTABLE_PREFIX
) {
611 wxLogError(_("Config entry name cannot start with '%c'."),
612 wxCONFIG_IMMUTABLE_PREFIX
);
616 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strName
);
617 if ( pEntry
== NULL
)
618 pEntry
= m_pCurrentGroup
->AddEntry(strName
);
620 pEntry
->SetValue(szValue
);
626 bool wxFileConfig::Write(const wxString
& key
, long lValue
)
628 // ltoa() is not ANSI :-(
630 buf
.Printf(_T("%ld"), lValue
);
631 return Write(key
, buf
);
634 bool wxFileConfig::Flush(bool /* bCurrentOnly */)
636 if ( LineListIsEmpty() || !m_pRootGroup
->IsDirty() )
639 wxTempFile
file(m_strLocalFile
);
641 if ( !file
.IsOpened() ) {
642 wxLogError(_("can't open user configuration file."));
646 // write all strings to file
647 for ( LineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() ) {
648 if ( !file
.Write(p
->Text() + wxTextFile::GetEOL()) ) {
649 wxLogError(_("can't write user configuration file."));
654 return file
.Commit();
657 // ----------------------------------------------------------------------------
658 // renaming groups/entries
659 // ----------------------------------------------------------------------------
661 bool wxFileConfig::RenameEntry(const wxString
& oldName
,
662 const wxString
& newName
)
664 // check that the entry exists
665 ConfigEntry
*oldEntry
= m_pCurrentGroup
->FindEntry(oldName
);
669 // check that the new entry doesn't already exist
670 if ( m_pCurrentGroup
->FindEntry(newName
) )
673 // delete the old entry, create the new one
674 wxString value
= oldEntry
->Value();
675 if ( !m_pCurrentGroup
->DeleteEntry(oldName
) )
678 ConfigEntry
*newEntry
= m_pCurrentGroup
->AddEntry(newName
);
679 newEntry
->SetValue(value
);
684 bool wxFileConfig::RenameGroup(const wxString
& oldName
,
685 const wxString
& newName
)
687 // check that the group exists
688 ConfigGroup
*group
= m_pCurrentGroup
->FindSubgroup(oldName
);
692 // check that the new group doesn't already exist
693 if ( m_pCurrentGroup
->FindSubgroup(newName
) )
696 group
->Rename(newName
);
701 // ----------------------------------------------------------------------------
702 // delete groups/entries
703 // ----------------------------------------------------------------------------
705 bool wxFileConfig::DeleteEntry(const wxString
& key
, bool bGroupIfEmptyAlso
)
707 wxConfigPathChanger
path(this, key
);
709 if ( !m_pCurrentGroup
->DeleteEntry(path
.Name()) )
712 if ( bGroupIfEmptyAlso
&& m_pCurrentGroup
->IsEmpty() ) {
713 if ( m_pCurrentGroup
!= m_pRootGroup
) {
714 ConfigGroup
*pGroup
= m_pCurrentGroup
;
715 SetPath(_T("..")); // changes m_pCurrentGroup!
716 m_pCurrentGroup
->DeleteSubgroupByName(pGroup
->Name());
718 //else: never delete the root group
724 bool wxFileConfig::DeleteGroup(const wxString
& key
)
726 wxConfigPathChanger
path(this, key
);
728 return m_pCurrentGroup
->DeleteSubgroupByName(path
.Name());
731 bool wxFileConfig::DeleteAll()
735 if ( remove(m_strLocalFile
.fn_str()) == -1 )
736 wxLogSysError(_("can't delete user configuration file '%s'"), m_strLocalFile
.c_str());
738 m_strLocalFile
= m_strGlobalFile
= _T("");
744 // ----------------------------------------------------------------------------
745 // linked list functions
746 // ----------------------------------------------------------------------------
748 // append a new line to the end of the list
749 LineList
*wxFileConfig::LineListAppend(const wxString
& str
)
751 LineList
*pLine
= new LineList(str
);
753 if ( m_linesTail
== NULL
) {
759 m_linesTail
->SetNext(pLine
);
760 pLine
->SetPrev(m_linesTail
);
767 // insert a new line after the given one or in the very beginning if !pLine
768 LineList
*wxFileConfig::LineListInsert(const wxString
& str
,
771 if ( pLine
== m_linesTail
)
772 return LineListAppend(str
);
774 LineList
*pNewLine
= new LineList(str
);
775 if ( pLine
== NULL
) {
776 // prepend to the list
777 pNewLine
->SetNext(m_linesHead
);
778 m_linesHead
->SetPrev(pNewLine
);
779 m_linesHead
= pNewLine
;
782 // insert before pLine
783 LineList
*pNext
= pLine
->Next();
784 pNewLine
->SetNext(pNext
);
785 pNewLine
->SetPrev(pLine
);
786 pNext
->SetPrev(pNewLine
);
787 pLine
->SetNext(pNewLine
);
793 void wxFileConfig::LineListRemove(LineList
*pLine
)
795 LineList
*pPrev
= pLine
->Prev(),
796 *pNext
= pLine
->Next();
802 pPrev
->SetNext(pNext
);
808 pNext
->SetPrev(pPrev
);
813 bool wxFileConfig::LineListIsEmpty()
815 return m_linesHead
== NULL
;
818 // ============================================================================
819 // wxFileConfig::ConfigGroup
820 // ============================================================================
822 // ----------------------------------------------------------------------------
824 // ----------------------------------------------------------------------------
827 ConfigGroup::ConfigGroup(ConfigGroup
*pParent
,
828 const wxString
& strName
,
829 wxFileConfig
*pConfig
)
830 : m_aEntries(CompareEntries
),
831 m_aSubgroups(CompareGroups
),
843 // dtor deletes all children
844 ConfigGroup::~ConfigGroup()
847 size_t n
, nCount
= m_aEntries
.Count();
848 for ( n
= 0; n
< nCount
; n
++ )
849 delete m_aEntries
[n
];
852 nCount
= m_aSubgroups
.Count();
853 for ( n
= 0; n
< nCount
; n
++ )
854 delete m_aSubgroups
[n
];
857 // ----------------------------------------------------------------------------
859 // ----------------------------------------------------------------------------
861 void ConfigGroup::SetLine(LineList
*pLine
)
863 wxASSERT( m_pLine
== NULL
); // shouldn't be called twice
869 This is a bit complicated, so let me explain it in details. All lines that
870 were read from the local file (the only one we will ever modify) are stored
871 in a (doubly) linked list. Our problem is to know at which position in this
872 list should we insert the new entries/subgroups. To solve it we keep three
873 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
875 m_pLine points to the line containing "[group_name]"
876 m_pLastEntry points to the last entry of this group in the local file.
877 m_pLastGroup subgroup
879 Initially, they're NULL all three. When the group (an entry/subgroup) is read
880 from the local file, the corresponding variable is set. However, if the group
881 was read from the global file and then modified or created by the application
882 these variables are still NULL and we need to create the corresponding lines.
883 See the following functions (and comments preceding them) for the details of
886 Also, when our last entry/group are deleted we need to find the new last
887 element - the code in DeleteEntry/Subgroup does this by backtracking the list
888 of lines until it either founds an entry/subgroup (and this is the new last
889 element) or the m_pLine of the group, in which case there are no more entries
890 (or subgroups) left and m_pLast<element> becomes NULL.
892 NB: This last problem could be avoided for entries if we added new entries
893 immediately after m_pLine, but in this case the entries would appear
894 backwards in the config file (OTOH, it's not that important) and as we
895 would still need to do it for the subgroups the code wouldn't have been
896 significantly less complicated.
899 // Return the line which contains "[our name]". If we're still not in the list,
900 // add our line to it immediately after the last line of our parent group if we
901 // have it or in the very beginning if we're the root group.
902 LineList
*ConfigGroup::GetGroupLine()
904 if ( m_pLine
== NULL
) {
905 ConfigGroup
*pParent
= Parent();
907 // this group wasn't present in local config file, add it now
908 if ( pParent
!= NULL
) {
909 wxString strFullName
;
910 strFullName
<< _T("[")
912 << FilterOutEntryName(GetFullName().c_str() + 1)
914 m_pLine
= m_pConfig
->LineListInsert(strFullName
,
915 pParent
->GetLastGroupLine());
916 pParent
->SetLastGroup(this); // we're surely after all the others
919 // we return NULL, so that LineListInsert() will insert us in the
927 // Return the last line belonging to the subgroups of this group (after which
928 // we can add a new subgroup), if we don't have any subgroups or entries our
929 // last line is the group line (m_pLine) itself.
930 LineList
*ConfigGroup::GetLastGroupLine()
932 // if we have any subgroups, our last line is the last line of the last
934 if ( m_pLastGroup
!= NULL
) {
935 LineList
*pLine
= m_pLastGroup
->GetLastGroupLine();
937 wxASSERT( pLine
!= NULL
); // last group must have !NULL associated line
941 // no subgroups, so the last line is the line of thelast entry (if any)
942 return GetLastEntryLine();
945 // return the last line belonging to the entries of this group (after which
946 // we can add a new entry), if we don't have any entries we will add the new
947 // one immediately after the group line itself.
948 LineList
*ConfigGroup::GetLastEntryLine()
950 if ( m_pLastEntry
!= NULL
) {
951 LineList
*pLine
= m_pLastEntry
->GetLine();
953 wxASSERT( pLine
!= NULL
); // last entry must have !NULL associated line
957 // no entries: insert after the group header
958 return GetGroupLine();
961 // ----------------------------------------------------------------------------
963 // ----------------------------------------------------------------------------
965 void ConfigGroup::Rename(const wxString
& newName
)
969 LineList
*line
= GetGroupLine();
970 wxString strFullName
;
971 strFullName
<< _T("[") << (GetFullName().c_str() + 1) << _T("]"); // +1: no '/'
972 line
->SetText(strFullName
);
977 wxString
ConfigGroup::GetFullName() const
980 return Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR
+ Name();
985 // ----------------------------------------------------------------------------
987 // ----------------------------------------------------------------------------
989 // use binary search because the array is sorted
991 ConfigGroup::FindEntry(const wxChar
*szName
) const
995 hi
= m_aEntries
.Count();
1001 pEntry
= m_aEntries
[i
];
1003 #if wxCONFIG_CASE_SENSITIVE
1004 res
= wxStrcmp(pEntry
->Name(), szName
);
1006 res
= wxStricmp(pEntry
->Name(), szName
);
1021 ConfigGroup::FindSubgroup(const wxChar
*szName
) const
1025 hi
= m_aSubgroups
.Count();
1027 ConfigGroup
*pGroup
;
1031 pGroup
= m_aSubgroups
[i
];
1033 #if wxCONFIG_CASE_SENSITIVE
1034 res
= wxStrcmp(pGroup
->Name(), szName
);
1036 res
= wxStricmp(pGroup
->Name(), szName
);
1050 // ----------------------------------------------------------------------------
1051 // create a new item
1052 // ----------------------------------------------------------------------------
1054 // create a new entry and add it to the current group
1056 ConfigGroup::AddEntry(const wxString
& strName
, int nLine
)
1058 wxASSERT( FindEntry(strName
) == NULL
);
1060 ConfigEntry
*pEntry
= new ConfigEntry(this, strName
, nLine
);
1061 m_aEntries
.Add(pEntry
);
1066 // create a new group and add it to the current group
1068 ConfigGroup::AddSubgroup(const wxString
& strName
)
1070 wxASSERT( FindSubgroup(strName
) == NULL
);
1072 ConfigGroup
*pGroup
= new ConfigGroup(this, strName
, m_pConfig
);
1073 m_aSubgroups
.Add(pGroup
);
1078 // ----------------------------------------------------------------------------
1080 // ----------------------------------------------------------------------------
1083 The delete operations are _very_ slow if we delete the last item of this
1084 group (see comments before GetXXXLineXXX functions for more details),
1085 so it's much better to start with the first entry/group if we want to
1086 delete several of them.
1089 bool ConfigGroup::DeleteSubgroupByName(const wxChar
*szName
)
1091 return DeleteSubgroup(FindSubgroup(szName
));
1094 // doesn't delete the subgroup itself, but does remove references to it from
1095 // all other data structures (and normally the returned pointer should be
1096 // deleted a.s.a.p. because there is nothing much to be done with it anyhow)
1097 bool ConfigGroup::DeleteSubgroup(ConfigGroup
*pGroup
)
1099 wxCHECK( pGroup
!= NULL
, FALSE
); // deleting non existing group?
1101 // delete all entries
1102 size_t nCount
= pGroup
->m_aEntries
.Count();
1103 for ( size_t nEntry
= 0; nEntry
< nCount
; nEntry
++ ) {
1104 LineList
*pLine
= pGroup
->m_aEntries
[nEntry
]->GetLine();
1105 if ( pLine
!= NULL
)
1106 m_pConfig
->LineListRemove(pLine
);
1109 // and subgroups of this sungroup
1110 nCount
= pGroup
->m_aSubgroups
.Count();
1111 for ( size_t nGroup
= 0; nGroup
< nCount
; nGroup
++ ) {
1112 pGroup
->DeleteSubgroup(pGroup
->m_aSubgroups
[0]);
1115 LineList
*pLine
= pGroup
->m_pLine
;
1116 if ( pLine
!= NULL
) {
1117 // notice that we may do this test inside the previous "if" because the
1118 // last entry's line is surely !NULL
1119 if ( pGroup
== m_pLastGroup
) {
1120 // our last entry is being deleted - find the last one which stays
1121 wxASSERT( m_pLine
!= NULL
); // we have a subgroup with !NULL pLine...
1123 // go back until we find a subgroup or reach the group's line
1124 ConfigGroup
*pNewLast
= NULL
;
1125 size_t n
, nSubgroups
= m_aSubgroups
.Count();
1127 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1128 // is it our subgroup?
1129 for ( n
= 0; (pNewLast
== NULL
) && (n
< nSubgroups
); n
++ ) {
1130 // do _not_ call GetGroupLine! we don't want to add it to the local
1131 // file if it's not already there
1132 if ( m_aSubgroups
[n
]->m_pLine
== m_pLine
)
1133 pNewLast
= m_aSubgroups
[n
];
1136 if ( pNewLast
!= NULL
) // found?
1140 if ( pl
== m_pLine
) {
1141 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1143 // we've reached the group line without finding any subgroups
1144 m_pLastGroup
= NULL
;
1147 m_pLastGroup
= pNewLast
;
1150 m_pConfig
->LineListRemove(pLine
);
1155 m_aSubgroups
.Remove(pGroup
);
1161 bool ConfigGroup::DeleteEntry(const wxChar
*szName
)
1163 ConfigEntry
*pEntry
= FindEntry(szName
);
1164 wxCHECK( pEntry
!= NULL
, FALSE
); // deleting non existing item?
1166 LineList
*pLine
= pEntry
->GetLine();
1167 if ( pLine
!= NULL
) {
1168 // notice that we may do this test inside the previous "if" because the
1169 // last entry's line is surely !NULL
1170 if ( pEntry
== m_pLastEntry
) {
1171 // our last entry is being deleted - find the last one which stays
1172 wxASSERT( m_pLine
!= NULL
); // if we have an entry with !NULL pLine...
1174 // go back until we find another entry or reach the group's line
1175 ConfigEntry
*pNewLast
= NULL
;
1176 size_t n
, nEntries
= m_aEntries
.Count();
1178 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1179 // is it our subgroup?
1180 for ( n
= 0; (pNewLast
== NULL
) && (n
< nEntries
); n
++ ) {
1181 if ( m_aEntries
[n
]->GetLine() == m_pLine
)
1182 pNewLast
= m_aEntries
[n
];
1185 if ( pNewLast
!= NULL
) // found?
1189 if ( pl
== m_pLine
) {
1190 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1192 // we've reached the group line without finding any subgroups
1193 m_pLastEntry
= NULL
;
1196 m_pLastEntry
= pNewLast
;
1199 m_pConfig
->LineListRemove(pLine
);
1202 // we must be written back for the changes to be saved
1205 m_aEntries
.Remove(pEntry
);
1211 // ----------------------------------------------------------------------------
1213 // ----------------------------------------------------------------------------
1214 void ConfigGroup::SetDirty()
1217 if ( Parent() != NULL
) // propagate upwards
1218 Parent()->SetDirty();
1221 // ============================================================================
1222 // wxFileConfig::ConfigEntry
1223 // ============================================================================
1225 // ----------------------------------------------------------------------------
1227 // ----------------------------------------------------------------------------
1228 ConfigEntry::ConfigEntry(ConfigGroup
*pParent
,
1229 const wxString
& strName
,
1231 : m_strName(strName
)
1233 wxASSERT( !strName
.IsEmpty() );
1235 m_pParent
= pParent
;
1241 m_bImmutable
= strName
[0] == wxCONFIG_IMMUTABLE_PREFIX
;
1243 m_strName
.erase(0, 1); // remove first character
1246 // ----------------------------------------------------------------------------
1248 // ----------------------------------------------------------------------------
1250 void ConfigEntry::SetLine(LineList
*pLine
)
1252 if ( m_pLine
!= NULL
) {
1253 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1254 Name().c_str(), m_pParent
->GetFullName().c_str());
1258 Group()->SetLastEntry(this);
1261 // second parameter is FALSE if we read the value from file and prevents the
1262 // entry from being marked as 'dirty'
1263 void ConfigEntry::SetValue(const wxString
& strValue
, bool bUser
)
1265 if ( bUser
&& IsImmutable() ) {
1266 wxLogWarning(_("attempt to change immutable key '%s' ignored."),
1271 // do nothing if it's the same value
1272 if ( strValue
== m_strValue
)
1275 m_strValue
= strValue
;
1278 wxString strVal
= FilterOutValue(strValue
);
1280 strLine
<< FilterOutEntryName(m_strName
) << _T('=') << strVal
;
1282 if ( m_pLine
!= NULL
) {
1283 // entry was read from the local config file, just modify the line
1284 m_pLine
->SetText(strLine
);
1287 // add a new line to the file
1288 wxASSERT( m_nLine
== wxNOT_FOUND
); // consistency check
1290 m_pLine
= Group()->Config()->LineListInsert(strLine
,
1291 Group()->GetLastEntryLine());
1292 Group()->SetLastEntry(this);
1299 void ConfigEntry::SetDirty()
1302 Group()->SetDirty();
1305 // ============================================================================
1307 // ============================================================================
1309 // ----------------------------------------------------------------------------
1310 // compare functions for array sorting
1311 // ----------------------------------------------------------------------------
1313 int CompareEntries(ConfigEntry
*p1
,
1316 #if wxCONFIG_CASE_SENSITIVE
1317 return wxStrcmp(p1
->Name(), p2
->Name());
1319 return wxStricmp(p1
->Name(), p2
->Name());
1323 int CompareGroups(ConfigGroup
*p1
,
1326 #if wxCONFIG_CASE_SENSITIVE
1327 return wxStrcmp(p1
->Name(), p2
->Name());
1329 return wxStricmp(p1
->Name(), p2
->Name());
1333 // ----------------------------------------------------------------------------
1335 // ----------------------------------------------------------------------------
1337 // undo FilterOutValue
1338 static wxString
FilterInValue(const wxString
& str
)
1341 strResult
.Alloc(str
.Len());
1343 bool bQuoted
= !str
.IsEmpty() && str
[0] == '"';
1345 for ( size_t n
= bQuoted
? 1 : 0; n
< str
.Len(); n
++ ) {
1346 if ( str
[n
] == _T('\\') ) {
1347 switch ( str
[++n
] ) {
1349 strResult
+= _T('\n');
1353 strResult
+= _T('\r');
1357 strResult
+= _T('\t');
1361 strResult
+= _T('\\');
1365 strResult
+= _T('"');
1370 if ( str
[n
] != _T('"') || !bQuoted
)
1371 strResult
+= str
[n
];
1372 else if ( n
!= str
.Len() - 1 ) {
1373 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1376 //else: it's the last quote of a quoted string, ok
1383 // quote the string before writing it to file
1384 static wxString
FilterOutValue(const wxString
& str
)
1390 strResult
.Alloc(str
.Len());
1392 // quoting is necessary to preserve spaces in the beginning of the string
1393 bool bQuote
= wxIsspace(str
[0]) || str
[0] == _T('"');
1396 strResult
+= _T('"');
1399 for ( size_t n
= 0; n
< str
.Len(); n
++ ) {
1422 //else: fall through
1425 strResult
+= str
[n
];
1426 continue; // nothing special to do
1429 // we get here only for special characters
1430 strResult
<< _T('\\') << c
;
1434 strResult
+= _T('"');
1439 // undo FilterOutEntryName
1440 static wxString
FilterInEntryName(const wxString
& str
)
1443 strResult
.Alloc(str
.Len());
1445 for ( const wxChar
*pc
= str
.c_str(); *pc
!= '\0'; pc
++ ) {
1446 if ( *pc
== _T('\\') )
1455 // sanitize entry or group name: insert '\\' before any special characters
1456 static wxString
FilterOutEntryName(const wxString
& str
)
1459 strResult
.Alloc(str
.Len());
1461 for ( const wxChar
*pc
= str
.c_str(); *pc
!= _T('\0'); pc
++ ) {
1464 // we explicitly allow some of "safe" chars and 8bit ASCII characters
1465 // which will probably never have special meaning
1466 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
1467 // should *not* be quoted
1468 if ( !wxIsalnum(c
) && !wxStrchr(_T("@_/-!.*%"), c
) && ((c
& 0x80) == 0) )
1469 strResult
+= _T('\\');
1477 // we can't put ?: in the ctor initializer list because it confuses some
1478 // broken compilers (Borland C++)
1479 static wxString
GetAppName(const wxString
& appName
)
1481 if ( !appName
&& wxTheApp
)
1482 return wxTheApp
->GetAppName();