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 if ( !m_strLocalFile
.IsEmpty() && !wxIsAbsolutePath(m_strLocalFile
) )
231 wxString strLocal
= m_strLocalFile
;
232 m_strLocalFile
= GetLocalDir();
233 m_strLocalFile
<< strLocal
;
236 if ( !m_strGlobalFile
.IsEmpty() && !wxIsAbsolutePath(m_strGlobalFile
) )
238 wxString strGlobal
= m_strGlobalFile
;
239 m_strGlobalFile
= GetGlobalDir();
240 m_strGlobalFile
<< strGlobal
;
246 void wxFileConfig::CleanUp()
250 LineList
*pCur
= m_linesHead
;
251 while ( pCur
!= NULL
) {
252 LineList
*pNext
= pCur
->Next();
258 wxFileConfig::~wxFileConfig()
265 // ----------------------------------------------------------------------------
266 // parse a config file
267 // ----------------------------------------------------------------------------
269 void wxFileConfig::Parse(wxTextFile
& file
, bool bLocal
)
271 const wxChar
*pStart
;
275 size_t nLineCount
= file
.GetLineCount();
276 for ( size_t n
= 0; n
< nLineCount
; n
++ ) {
279 // add the line to linked list
281 LineListAppend(strLine
);
283 // skip leading spaces
284 for ( pStart
= strLine
; wxIsspace(*pStart
); pStart
++ )
287 // skip blank/comment lines
288 if ( *pStart
== _T('\0')|| *pStart
== _T(';') || *pStart
== _T('#') )
291 if ( *pStart
== _T('[') ) { // a new group
294 while ( *++pEnd
!= _T(']') ) {
295 if ( *pEnd
== _T('\n') || *pEnd
== _T('\0') )
299 if ( *pEnd
!= _T(']') ) {
300 wxLogError(_("file '%s': unexpected character %c at line %d."),
301 file
.GetName(), *pEnd
, n
+ 1);
302 continue; // skip this line
305 // group name here is always considered as abs path
308 strGroup
<< wxCONFIG_PATH_SEPARATOR
309 << FilterInEntryName(wxString(pStart
, pEnd
- pStart
));
311 // will create it if doesn't yet exist
315 m_pCurrentGroup
->SetLine(m_linesTail
);
317 // check that there is nothing except comments left on this line
319 while ( *++pEnd
!= _T('\0') && bCont
) {
328 // ignore whitespace ('\n' impossible here)
332 wxLogWarning(_("file '%s', line %d: '%s' "
333 "ignored after group header."),
334 file
.GetName(), n
+ 1, pEnd
);
340 const wxChar
*pEnd
= pStart
;
341 while ( !wxIsspace(*pEnd
) ) {
342 if ( *pEnd
== _T('\\') ) {
343 // next character may be space or not - still take it because it's
351 wxString
strKey(FilterInEntryName(wxString(pStart
, pEnd
)));
354 while ( isspace(*pEnd
) )
357 if ( *pEnd
++ != _T('=') ) {
358 wxLogError(_("file '%s', line %d: '=' expected."),
359 file
.GetName(), n
+ 1);
362 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strKey
);
364 if ( pEntry
== NULL
) {
366 pEntry
= m_pCurrentGroup
->AddEntry(strKey
, n
);
369 pEntry
->SetLine(m_linesTail
);
372 if ( bLocal
&& pEntry
->IsImmutable() ) {
373 // immutable keys can't be changed by user
374 wxLogWarning(_("file '%s', line %d: value for "
375 "immutable key '%s' ignored."),
376 file
.GetName(), n
+ 1, strKey
.c_str());
379 // the condition below catches the cases (a) and (b) but not (c):
380 // (a) global key found second time in global file
381 // (b) key found second (or more) time in local file
382 // (c) key from global file now found in local one
383 // which is exactly what we want.
384 else if ( !bLocal
|| pEntry
->IsLocal() ) {
385 wxLogWarning(_("file '%s', line %d: key '%s' was first "
386 "found at line %d."),
387 file
.GetName(), n
+ 1, strKey
.c_str(), pEntry
->Line());
390 pEntry
->SetLine(m_linesTail
);
395 while ( wxIsspace(*pEnd
) )
398 pEntry
->SetValue(FilterInValue(pEnd
), FALSE
/* read from file */);
404 // ----------------------------------------------------------------------------
406 // ----------------------------------------------------------------------------
408 void wxFileConfig::SetRootPath()
411 m_pCurrentGroup
= m_pRootGroup
;
414 void wxFileConfig::SetPath(const wxString
& strPath
)
416 wxArrayString aParts
;
418 if ( strPath
.IsEmpty() ) {
423 if ( strPath
[0] == wxCONFIG_PATH_SEPARATOR
) {
425 wxSplitPath(aParts
, strPath
);
428 // relative path, combine with current one
429 wxString strFullPath
= m_strPath
;
430 strFullPath
<< wxCONFIG_PATH_SEPARATOR
<< strPath
;
431 wxSplitPath(aParts
, strFullPath
);
434 // change current group
436 m_pCurrentGroup
= m_pRootGroup
;
437 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
438 ConfigGroup
*pNextGroup
= m_pCurrentGroup
->FindSubgroup(aParts
[n
]);
439 if ( pNextGroup
== NULL
)
440 pNextGroup
= m_pCurrentGroup
->AddSubgroup(aParts
[n
]);
441 m_pCurrentGroup
= pNextGroup
;
444 // recombine path parts in one variable
446 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
447 m_strPath
<< wxCONFIG_PATH_SEPARATOR
<< aParts
[n
];
451 // ----------------------------------------------------------------------------
453 // ----------------------------------------------------------------------------
455 bool wxFileConfig::GetFirstGroup(wxString
& str
, long& lIndex
) const
458 return GetNextGroup(str
, lIndex
);
461 bool wxFileConfig::GetNextGroup (wxString
& str
, long& lIndex
) const
463 if ( size_t(lIndex
) < m_pCurrentGroup
->Groups().Count() ) {
464 str
= m_pCurrentGroup
->Groups()[lIndex
++]->Name();
471 bool wxFileConfig::GetFirstEntry(wxString
& str
, long& lIndex
) const
474 return GetNextEntry(str
, lIndex
);
477 bool wxFileConfig::GetNextEntry (wxString
& str
, long& lIndex
) const
479 if ( size_t(lIndex
) < m_pCurrentGroup
->Entries().Count() ) {
480 str
= m_pCurrentGroup
->Entries()[lIndex
++]->Name();
487 size_t wxFileConfig::GetNumberOfEntries(bool bRecursive
) const
489 size_t n
= m_pCurrentGroup
->Entries().Count();
491 ConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
492 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
493 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
494 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
495 n
+= GetNumberOfEntries(TRUE
);
496 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
503 size_t wxFileConfig::GetNumberOfGroups(bool bRecursive
) const
505 size_t n
= m_pCurrentGroup
->Groups().Count();
507 ConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
508 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
509 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
510 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
511 n
+= GetNumberOfGroups(TRUE
);
512 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
519 // ----------------------------------------------------------------------------
520 // tests for existence
521 // ----------------------------------------------------------------------------
523 bool wxFileConfig::HasGroup(const wxString
& strName
) const
525 wxConfigPathChanger
path(this, strName
);
527 ConfigGroup
*pGroup
= m_pCurrentGroup
->FindSubgroup(path
.Name());
528 return pGroup
!= NULL
;
531 bool wxFileConfig::HasEntry(const wxString
& strName
) const
533 wxConfigPathChanger
path(this, strName
);
535 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
536 return pEntry
!= NULL
;
539 // ----------------------------------------------------------------------------
541 // ----------------------------------------------------------------------------
543 bool wxFileConfig::Read(const wxString
& key
,
544 wxString
* pStr
) const
546 wxConfigPathChanger
path(this, key
);
548 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
549 if (pEntry
== NULL
) {
553 *pStr
= ExpandEnvVars(pEntry
->Value());
558 bool wxFileConfig::Read(const wxString
& key
,
559 wxString
* pStr
, const wxString
& defVal
) const
561 wxConfigPathChanger
path(this, key
);
563 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
564 if (pEntry
== NULL
) {
565 if( IsRecordingDefaults() )
566 ((wxFileConfig
*)this)->Write(key
,defVal
);
567 *pStr
= ExpandEnvVars(defVal
);
571 *pStr
= ExpandEnvVars(pEntry
->Value());
576 bool wxFileConfig::Read(const wxString
& key
, long *pl
) const
579 if ( Read(key
, & str
) ) {
588 bool wxFileConfig::Write(const wxString
& key
, const wxString
& szValue
)
590 wxConfigPathChanger
path(this, key
);
592 wxString strName
= path
.Name();
593 if ( strName
.IsEmpty() ) {
594 // setting the value of a group is an error
595 wxASSERT_MSG( wxIsEmpty(szValue
), _T("can't set value of a group!") );
597 // ... except if it's empty in which case it's a way to force it's creation
598 m_pCurrentGroup
->SetDirty();
600 // this will add a line for this group if it didn't have it before
601 (void)m_pCurrentGroup
->GetGroupLine();
606 // check that the name is reasonable
607 if ( strName
[0u] == wxCONFIG_IMMUTABLE_PREFIX
) {
608 wxLogError(_("Config entry name cannot start with '%c'."),
609 wxCONFIG_IMMUTABLE_PREFIX
);
613 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strName
);
614 if ( pEntry
== NULL
)
615 pEntry
= m_pCurrentGroup
->AddEntry(strName
);
617 pEntry
->SetValue(szValue
);
623 bool wxFileConfig::Write(const wxString
& key
, long lValue
)
625 // ltoa() is not ANSI :-(
627 buf
.Printf(_T("%ld"), lValue
);
628 return Write(key
, buf
);
631 bool wxFileConfig::Flush(bool /* bCurrentOnly */)
633 if ( LineListIsEmpty() || !m_pRootGroup
->IsDirty() )
636 wxTempFile
file(m_strLocalFile
);
638 if ( !file
.IsOpened() ) {
639 wxLogError(_("can't open user configuration file."));
643 // write all strings to file
644 for ( LineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() ) {
645 if ( !file
.Write(p
->Text() + wxTextFile::GetEOL()) ) {
646 wxLogError(_("can't write user configuration file."));
651 return file
.Commit();
654 // ----------------------------------------------------------------------------
655 // renaming groups/entries
656 // ----------------------------------------------------------------------------
658 bool wxFileConfig::RenameEntry(const wxString
& oldName
,
659 const wxString
& newName
)
661 // check that the entry exists
662 ConfigEntry
*oldEntry
= m_pCurrentGroup
->FindEntry(oldName
);
666 // check that the new entry doesn't already exist
667 if ( m_pCurrentGroup
->FindEntry(newName
) )
670 // delete the old entry, create the new one
671 wxString value
= oldEntry
->Value();
672 if ( !m_pCurrentGroup
->DeleteEntry(oldName
) )
675 ConfigEntry
*newEntry
= m_pCurrentGroup
->AddEntry(newName
);
676 newEntry
->SetValue(value
);
681 bool wxFileConfig::RenameGroup(const wxString
& oldName
,
682 const wxString
& newName
)
684 // check that the group exists
685 ConfigGroup
*group
= m_pCurrentGroup
->FindSubgroup(oldName
);
689 // check that the new group doesn't already exist
690 if ( m_pCurrentGroup
->FindSubgroup(newName
) )
693 group
->Rename(newName
);
698 // ----------------------------------------------------------------------------
699 // delete groups/entries
700 // ----------------------------------------------------------------------------
702 bool wxFileConfig::DeleteEntry(const wxString
& key
, bool bGroupIfEmptyAlso
)
704 wxConfigPathChanger
path(this, key
);
706 if ( !m_pCurrentGroup
->DeleteEntry(path
.Name()) )
709 if ( bGroupIfEmptyAlso
&& m_pCurrentGroup
->IsEmpty() ) {
710 if ( m_pCurrentGroup
!= m_pRootGroup
) {
711 ConfigGroup
*pGroup
= m_pCurrentGroup
;
712 SetPath(_T("..")); // changes m_pCurrentGroup!
713 m_pCurrentGroup
->DeleteSubgroupByName(pGroup
->Name());
715 //else: never delete the root group
721 bool wxFileConfig::DeleteGroup(const wxString
& key
)
723 wxConfigPathChanger
path(this, key
);
725 return m_pCurrentGroup
->DeleteSubgroupByName(path
.Name());
728 bool wxFileConfig::DeleteAll()
732 if ( remove(m_strLocalFile
.fn_str()) == -1 )
733 wxLogSysError(_("can't delete user configuration file '%s'"), m_strLocalFile
.c_str());
735 m_strLocalFile
= m_strGlobalFile
= _T("");
741 // ----------------------------------------------------------------------------
742 // linked list functions
743 // ----------------------------------------------------------------------------
745 // append a new line to the end of the list
746 LineList
*wxFileConfig::LineListAppend(const wxString
& str
)
748 LineList
*pLine
= new LineList(str
);
750 if ( m_linesTail
== NULL
) {
756 m_linesTail
->SetNext(pLine
);
757 pLine
->SetPrev(m_linesTail
);
764 // insert a new line after the given one or in the very beginning if !pLine
765 LineList
*wxFileConfig::LineListInsert(const wxString
& str
,
768 if ( pLine
== m_linesTail
)
769 return LineListAppend(str
);
771 LineList
*pNewLine
= new LineList(str
);
772 if ( pLine
== NULL
) {
773 // prepend to the list
774 pNewLine
->SetNext(m_linesHead
);
775 m_linesHead
->SetPrev(pNewLine
);
776 m_linesHead
= pNewLine
;
779 // insert before pLine
780 LineList
*pNext
= pLine
->Next();
781 pNewLine
->SetNext(pNext
);
782 pNewLine
->SetPrev(pLine
);
783 pNext
->SetPrev(pNewLine
);
784 pLine
->SetNext(pNewLine
);
790 void wxFileConfig::LineListRemove(LineList
*pLine
)
792 LineList
*pPrev
= pLine
->Prev(),
793 *pNext
= pLine
->Next();
799 pPrev
->SetNext(pNext
);
805 pNext
->SetPrev(pPrev
);
810 bool wxFileConfig::LineListIsEmpty()
812 return m_linesHead
== NULL
;
815 // ============================================================================
816 // wxFileConfig::ConfigGroup
817 // ============================================================================
819 // ----------------------------------------------------------------------------
821 // ----------------------------------------------------------------------------
824 ConfigGroup::ConfigGroup(ConfigGroup
*pParent
,
825 const wxString
& strName
,
826 wxFileConfig
*pConfig
)
827 : m_aEntries(CompareEntries
),
828 m_aSubgroups(CompareGroups
),
840 // dtor deletes all children
841 ConfigGroup::~ConfigGroup()
844 size_t n
, nCount
= m_aEntries
.Count();
845 for ( n
= 0; n
< nCount
; n
++ )
846 delete m_aEntries
[n
];
849 nCount
= m_aSubgroups
.Count();
850 for ( n
= 0; n
< nCount
; n
++ )
851 delete m_aSubgroups
[n
];
854 // ----------------------------------------------------------------------------
856 // ----------------------------------------------------------------------------
858 void ConfigGroup::SetLine(LineList
*pLine
)
860 wxASSERT( m_pLine
== NULL
); // shouldn't be called twice
866 This is a bit complicated, so let me explain it in details. All lines that
867 were read from the local file (the only one we will ever modify) are stored
868 in a (doubly) linked list. Our problem is to know at which position in this
869 list should we insert the new entries/subgroups. To solve it we keep three
870 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
872 m_pLine points to the line containing "[group_name]"
873 m_pLastEntry points to the last entry of this group in the local file.
874 m_pLastGroup subgroup
876 Initially, they're NULL all three. When the group (an entry/subgroup) is read
877 from the local file, the corresponding variable is set. However, if the group
878 was read from the global file and then modified or created by the application
879 these variables are still NULL and we need to create the corresponding lines.
880 See the following functions (and comments preceding them) for the details of
883 Also, when our last entry/group are deleted we need to find the new last
884 element - the code in DeleteEntry/Subgroup does this by backtracking the list
885 of lines until it either founds an entry/subgroup (and this is the new last
886 element) or the m_pLine of the group, in which case there are no more entries
887 (or subgroups) left and m_pLast<element> becomes NULL.
889 NB: This last problem could be avoided for entries if we added new entries
890 immediately after m_pLine, but in this case the entries would appear
891 backwards in the config file (OTOH, it's not that important) and as we
892 would still need to do it for the subgroups the code wouldn't have been
893 significantly less complicated.
896 // Return the line which contains "[our name]". If we're still not in the list,
897 // add our line to it immediately after the last line of our parent group if we
898 // have it or in the very beginning if we're the root group.
899 LineList
*ConfigGroup::GetGroupLine()
901 if ( m_pLine
== NULL
) {
902 ConfigGroup
*pParent
= Parent();
904 // this group wasn't present in local config file, add it now
905 if ( pParent
!= NULL
) {
906 wxString strFullName
;
907 strFullName
<< _T("[")
909 << FilterOutEntryName(GetFullName().c_str() + 1)
911 m_pLine
= m_pConfig
->LineListInsert(strFullName
,
912 pParent
->GetLastGroupLine());
913 pParent
->SetLastGroup(this); // we're surely after all the others
916 // we return NULL, so that LineListInsert() will insert us in the
924 // Return the last line belonging to the subgroups of this group (after which
925 // we can add a new subgroup), if we don't have any subgroups or entries our
926 // last line is the group line (m_pLine) itself.
927 LineList
*ConfigGroup::GetLastGroupLine()
929 // if we have any subgroups, our last line is the last line of the last
931 if ( m_pLastGroup
!= NULL
) {
932 LineList
*pLine
= m_pLastGroup
->GetLastGroupLine();
934 wxASSERT( pLine
!= NULL
); // last group must have !NULL associated line
938 // no subgroups, so the last line is the line of thelast entry (if any)
939 return GetLastEntryLine();
942 // return the last line belonging to the entries of this group (after which
943 // we can add a new entry), if we don't have any entries we will add the new
944 // one immediately after the group line itself.
945 LineList
*ConfigGroup::GetLastEntryLine()
947 if ( m_pLastEntry
!= NULL
) {
948 LineList
*pLine
= m_pLastEntry
->GetLine();
950 wxASSERT( pLine
!= NULL
); // last entry must have !NULL associated line
954 // no entries: insert after the group header
955 return GetGroupLine();
958 // ----------------------------------------------------------------------------
960 // ----------------------------------------------------------------------------
962 void ConfigGroup::Rename(const wxString
& newName
)
966 LineList
*line
= GetGroupLine();
967 wxString strFullName
;
968 strFullName
<< _T("[") << (GetFullName().c_str() + 1) << _T("]"); // +1: no '/'
969 line
->SetText(strFullName
);
974 wxString
ConfigGroup::GetFullName() const
977 return Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR
+ Name();
982 // ----------------------------------------------------------------------------
984 // ----------------------------------------------------------------------------
986 // use binary search because the array is sorted
988 ConfigGroup::FindEntry(const wxChar
*szName
) const
992 hi
= m_aEntries
.Count();
998 pEntry
= m_aEntries
[i
];
1000 #if wxCONFIG_CASE_SENSITIVE
1001 res
= wxStrcmp(pEntry
->Name(), szName
);
1003 res
= wxStricmp(pEntry
->Name(), szName
);
1018 ConfigGroup::FindSubgroup(const wxChar
*szName
) const
1022 hi
= m_aSubgroups
.Count();
1024 ConfigGroup
*pGroup
;
1028 pGroup
= m_aSubgroups
[i
];
1030 #if wxCONFIG_CASE_SENSITIVE
1031 res
= wxStrcmp(pGroup
->Name(), szName
);
1033 res
= wxStricmp(pGroup
->Name(), szName
);
1047 // ----------------------------------------------------------------------------
1048 // create a new item
1049 // ----------------------------------------------------------------------------
1051 // create a new entry and add it to the current group
1053 ConfigGroup::AddEntry(const wxString
& strName
, int nLine
)
1055 wxASSERT( FindEntry(strName
) == NULL
);
1057 ConfigEntry
*pEntry
= new ConfigEntry(this, strName
, nLine
);
1058 m_aEntries
.Add(pEntry
);
1063 // create a new group and add it to the current group
1065 ConfigGroup::AddSubgroup(const wxString
& strName
)
1067 wxASSERT( FindSubgroup(strName
) == NULL
);
1069 ConfigGroup
*pGroup
= new ConfigGroup(this, strName
, m_pConfig
);
1070 m_aSubgroups
.Add(pGroup
);
1075 // ----------------------------------------------------------------------------
1077 // ----------------------------------------------------------------------------
1080 The delete operations are _very_ slow if we delete the last item of this
1081 group (see comments before GetXXXLineXXX functions for more details),
1082 so it's much better to start with the first entry/group if we want to
1083 delete several of them.
1086 bool ConfigGroup::DeleteSubgroupByName(const wxChar
*szName
)
1088 return DeleteSubgroup(FindSubgroup(szName
));
1091 // doesn't delete the subgroup itself, but does remove references to it from
1092 // all other data structures (and normally the returned pointer should be
1093 // deleted a.s.a.p. because there is nothing much to be done with it anyhow)
1094 bool ConfigGroup::DeleteSubgroup(ConfigGroup
*pGroup
)
1096 wxCHECK( pGroup
!= NULL
, FALSE
); // deleting non existing group?
1098 // delete all entries
1099 size_t nCount
= pGroup
->m_aEntries
.Count();
1100 for ( size_t nEntry
= 0; nEntry
< nCount
; nEntry
++ ) {
1101 LineList
*pLine
= pGroup
->m_aEntries
[nEntry
]->GetLine();
1102 if ( pLine
!= NULL
)
1103 m_pConfig
->LineListRemove(pLine
);
1106 // and subgroups of this sungroup
1107 nCount
= pGroup
->m_aSubgroups
.Count();
1108 for ( size_t nGroup
= 0; nGroup
< nCount
; nGroup
++ ) {
1109 pGroup
->DeleteSubgroup(pGroup
->m_aSubgroups
[0]);
1112 LineList
*pLine
= pGroup
->m_pLine
;
1113 if ( pLine
!= NULL
) {
1114 // notice that we may do this test inside the previous "if" because the
1115 // last entry's line is surely !NULL
1116 if ( pGroup
== m_pLastGroup
) {
1117 // our last entry is being deleted - find the last one which stays
1118 wxASSERT( m_pLine
!= NULL
); // we have a subgroup with !NULL pLine...
1120 // go back until we find a subgroup or reach the group's line
1121 ConfigGroup
*pNewLast
= NULL
;
1122 size_t n
, nSubgroups
= m_aSubgroups
.Count();
1124 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1125 // is it our subgroup?
1126 for ( n
= 0; (pNewLast
== NULL
) && (n
< nSubgroups
); n
++ ) {
1127 // do _not_ call GetGroupLine! we don't want to add it to the local
1128 // file if it's not already there
1129 if ( m_aSubgroups
[n
]->m_pLine
== m_pLine
)
1130 pNewLast
= m_aSubgroups
[n
];
1133 if ( pNewLast
!= NULL
) // found?
1137 if ( pl
== m_pLine
) {
1138 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1140 // we've reached the group line without finding any subgroups
1141 m_pLastGroup
= NULL
;
1144 m_pLastGroup
= pNewLast
;
1147 m_pConfig
->LineListRemove(pLine
);
1152 m_aSubgroups
.Remove(pGroup
);
1158 bool ConfigGroup::DeleteEntry(const wxChar
*szName
)
1160 ConfigEntry
*pEntry
= FindEntry(szName
);
1161 wxCHECK( pEntry
!= NULL
, FALSE
); // deleting non existing item?
1163 LineList
*pLine
= pEntry
->GetLine();
1164 if ( pLine
!= NULL
) {
1165 // notice that we may do this test inside the previous "if" because the
1166 // last entry's line is surely !NULL
1167 if ( pEntry
== m_pLastEntry
) {
1168 // our last entry is being deleted - find the last one which stays
1169 wxASSERT( m_pLine
!= NULL
); // if we have an entry with !NULL pLine...
1171 // go back until we find another entry or reach the group's line
1172 ConfigEntry
*pNewLast
= NULL
;
1173 size_t n
, nEntries
= m_aEntries
.Count();
1175 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1176 // is it our subgroup?
1177 for ( n
= 0; (pNewLast
== NULL
) && (n
< nEntries
); n
++ ) {
1178 if ( m_aEntries
[n
]->GetLine() == m_pLine
)
1179 pNewLast
= m_aEntries
[n
];
1182 if ( pNewLast
!= NULL
) // found?
1186 if ( pl
== m_pLine
) {
1187 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1189 // we've reached the group line without finding any subgroups
1190 m_pLastEntry
= NULL
;
1193 m_pLastEntry
= pNewLast
;
1196 m_pConfig
->LineListRemove(pLine
);
1199 // we must be written back for the changes to be saved
1202 m_aEntries
.Remove(pEntry
);
1208 // ----------------------------------------------------------------------------
1210 // ----------------------------------------------------------------------------
1211 void ConfigGroup::SetDirty()
1214 if ( Parent() != NULL
) // propagate upwards
1215 Parent()->SetDirty();
1218 // ============================================================================
1219 // wxFileConfig::ConfigEntry
1220 // ============================================================================
1222 // ----------------------------------------------------------------------------
1224 // ----------------------------------------------------------------------------
1225 ConfigEntry::ConfigEntry(ConfigGroup
*pParent
,
1226 const wxString
& strName
,
1228 : m_strName(strName
)
1230 wxASSERT( !strName
.IsEmpty() );
1232 m_pParent
= pParent
;
1238 m_bImmutable
= strName
[0] == wxCONFIG_IMMUTABLE_PREFIX
;
1240 m_strName
.erase(0, 1); // remove first character
1243 // ----------------------------------------------------------------------------
1245 // ----------------------------------------------------------------------------
1247 void ConfigEntry::SetLine(LineList
*pLine
)
1249 if ( m_pLine
!= NULL
) {
1250 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1251 Name().c_str(), m_pParent
->GetFullName().c_str());
1255 Group()->SetLastEntry(this);
1258 // second parameter is FALSE if we read the value from file and prevents the
1259 // entry from being marked as 'dirty'
1260 void ConfigEntry::SetValue(const wxString
& strValue
, bool bUser
)
1262 if ( bUser
&& IsImmutable() ) {
1263 wxLogWarning(_("attempt to change immutable key '%s' ignored."),
1268 // do nothing if it's the same value
1269 if ( strValue
== m_strValue
)
1272 m_strValue
= strValue
;
1275 wxString strVal
= FilterOutValue(strValue
);
1277 strLine
<< FilterOutEntryName(m_strName
) << _T(" = ") << strVal
;
1279 if ( m_pLine
!= NULL
) {
1280 // entry was read from the local config file, just modify the line
1281 m_pLine
->SetText(strLine
);
1284 // add a new line to the file
1285 wxASSERT( m_nLine
== wxNOT_FOUND
); // consistency check
1287 m_pLine
= Group()->Config()->LineListInsert(strLine
,
1288 Group()->GetLastEntryLine());
1289 Group()->SetLastEntry(this);
1296 void ConfigEntry::SetDirty()
1299 Group()->SetDirty();
1302 // ============================================================================
1304 // ============================================================================
1306 // ----------------------------------------------------------------------------
1307 // compare functions for array sorting
1308 // ----------------------------------------------------------------------------
1310 int CompareEntries(ConfigEntry
*p1
,
1313 #if wxCONFIG_CASE_SENSITIVE
1314 return wxStrcmp(p1
->Name(), p2
->Name());
1316 return wxStricmp(p1
->Name(), p2
->Name());
1320 int CompareGroups(ConfigGroup
*p1
,
1323 #if wxCONFIG_CASE_SENSITIVE
1324 return wxStrcmp(p1
->Name(), p2
->Name());
1326 return wxStricmp(p1
->Name(), p2
->Name());
1330 // ----------------------------------------------------------------------------
1332 // ----------------------------------------------------------------------------
1334 // undo FilterOutValue
1335 static wxString
FilterInValue(const wxString
& str
)
1338 strResult
.Alloc(str
.Len());
1340 bool bQuoted
= !str
.IsEmpty() && str
[0] == '"';
1342 for ( size_t n
= bQuoted
? 1 : 0; n
< str
.Len(); n
++ ) {
1343 if ( str
[n
] == _T('\\') ) {
1344 switch ( str
[++n
] ) {
1346 strResult
+= _T('\n');
1350 strResult
+= _T('\r');
1354 strResult
+= _T('\t');
1358 strResult
+= _T('\\');
1362 strResult
+= _T('"');
1367 if ( str
[n
] != _T('"') || !bQuoted
)
1368 strResult
+= str
[n
];
1369 else if ( n
!= str
.Len() - 1 ) {
1370 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1373 //else: it's the last quote of a quoted string, ok
1380 // quote the string before writing it to file
1381 static wxString
FilterOutValue(const wxString
& str
)
1387 strResult
.Alloc(str
.Len());
1389 // quoting is necessary to preserve spaces in the beginning of the string
1390 bool bQuote
= wxIsspace(str
[0]) || str
[0] == _T('"');
1393 strResult
+= _T('"');
1396 for ( size_t n
= 0; n
< str
.Len(); n
++ ) {
1419 //else: fall through
1422 strResult
+= str
[n
];
1423 continue; // nothing special to do
1426 // we get here only for special characters
1427 strResult
<< _T('\\') << c
;
1431 strResult
+= _T('"');
1436 // undo FilterOutEntryName
1437 static wxString
FilterInEntryName(const wxString
& str
)
1440 strResult
.Alloc(str
.Len());
1442 for ( const wxChar
*pc
= str
.c_str(); *pc
!= '\0'; pc
++ ) {
1443 if ( *pc
== _T('\\') )
1452 // sanitize entry or group name: insert '\\' before any special characters
1453 static wxString
FilterOutEntryName(const wxString
& str
)
1456 strResult
.Alloc(str
.Len());
1458 for ( const wxChar
*pc
= str
.c_str(); *pc
!= _T('\0'); pc
++ ) {
1461 // we explicitly allow some of "safe" chars and 8bit ASCII characters
1462 // which will probably never have special meaning
1463 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
1464 // should *not* be quoted
1465 if ( !wxIsalnum(c
) && !wxStrchr(_T("@_/-!.*%"), c
) && ((c
& 0x80) == 0) )
1466 strResult
+= _T('\\');
1474 // we can't put ?: in the ctor initializer list because it confuses some
1475 // broken compilers (Borland C++)
1476 static wxString
GetAppName(const wxString
& appName
)
1478 if ( !appName
&& wxTheApp
)
1479 return wxTheApp
->GetAppName();