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_)
52 #define LINKAGEMODE _Optlink
60 // ----------------------------------------------------------------------------
62 // ----------------------------------------------------------------------------
63 #define CONST_CAST ((wxFileConfig *)this)->
65 // ----------------------------------------------------------------------------
67 // ----------------------------------------------------------------------------
72 // ----------------------------------------------------------------------------
73 // global functions declarations
74 // ----------------------------------------------------------------------------
76 // compare functions for sorting the arrays
77 static int LINKAGEMODE
CompareEntries(ConfigEntry
*p1
, ConfigEntry
*p2
);
78 static int LINKAGEMODE
CompareGroups(ConfigGroup
*p1
, ConfigGroup
*p2
);
81 static wxString
FilterInValue(const wxString
& str
);
82 static wxString
FilterOutValue(const wxString
& str
);
84 static wxString
FilterInEntryName(const wxString
& str
);
85 static wxString
FilterOutEntryName(const wxString
& str
);
87 // get the name to use in wxFileConfig ctor
88 static wxString
GetAppName(const wxString
& appname
);
90 // ============================================================================
92 // ============================================================================
94 // ----------------------------------------------------------------------------
96 // ----------------------------------------------------------------------------
97 wxString
wxFileConfig::GetGlobalDir()
101 #ifdef __VMS__ // Note if __VMS is defined __UNIX is also defined
102 strDir
= wxT("sys$manager:");
103 #elif defined( __UNIX__ )
104 strDir
= wxT("/etc/");
105 #elif defined(__WXPM__)
106 ULONG aulSysInfo
[QSV_MAX
] = {0};
110 rc
= DosQuerySysInfo( 1L, QSV_MAX
, (PVOID
)aulSysInfo
, sizeof(ULONG
)*QSV_MAX
);
113 drive
= aulSysInfo
[QSV_BOOT_DRIVE
- 1];
117 strDir
= "A:\\OS2\\";
120 strDir
= "B:\\OS2\\";
123 strDir
= "C:\\OS2\\";
126 strDir
= "D:\\OS2\\";
129 strDir
= "E:\\OS2\\";
132 strDir
= "F:\\OS2\\";
135 strDir
= "G:\\OS2\\";
138 strDir
= "H:\\OS2\\";
141 strDir
= "I:\\OS2\\";
144 strDir
= "J:\\OS2\\";
147 strDir
= "K:\\OS2\\";
150 strDir
= "L:\\OS2\\";
153 strDir
= "M:\\OS2\\";
156 strDir
= "N:\\OS2\\";
159 strDir
= "O:\\OS2\\";
162 strDir
= "P:\\OS2\\";
165 strDir
= "Q:\\OS2\\";
168 strDir
= "R:\\OS2\\";
171 strDir
= "S:\\OS2\\";
174 strDir
= "T:\\OS2\\";
177 strDir
= "U:\\OS2\\";
180 strDir
= "V:\\OS2\\";
183 strDir
= "W:\\OS2\\";
186 strDir
= "X:\\OS2\\";
189 strDir
= "Y:\\OS2\\";
192 strDir
= "Z:\\OS2\\";
196 #elif defined(__WXSTUBS__)
197 wxASSERT_MSG( FALSE
, wxT("TODO") ) ;
198 #elif defined(__WXMAC__)
203 if ( FindFolder( (short) kOnSystemDisk
, kPreferencesFolderType
, kDontCreateFolder
, &vRefNum
, &dirID
) == noErr
)
206 if ( FSMakeFSSpec( vRefNum
, dirID
, "\p" , &file
) == noErr
)
208 strDir
= wxMacFSSpec2UnixFilename( &file
) + "/" ;
213 wxChar szWinDir
[MAX_PATH
];
214 ::GetWindowsDirectory(szWinDir
, MAX_PATH
);
218 #endif // Unix/Windows
223 wxString
wxFileConfig::GetLocalDir()
228 wxGetHomeDir(&strDir
);
232 if (strDir
.Last() != wxT('/')) strDir
<< wxT('/');
234 if (strDir
.Last() != wxT('\\')) strDir
<< wxT('\\');
238 // no local dir concept on mac
239 return GetGlobalDir() ;
245 wxString
wxFileConfig::GetGlobalFileName(const wxChar
*szFile
)
247 wxString str
= GetGlobalDir();
250 if ( wxStrchr(szFile
, wxT('.')) == NULL
)
253 #elif defined( __WXMAC__ )
254 str
<< " Preferences";
262 wxString
wxFileConfig::GetLocalFileName(const wxChar
*szFile
)
264 #ifdef __VMS__ // On VMS I saw the problem that the home directory was appended
265 // twice for the configuration file. Does that also happen for other
267 wxString str
= wxT( ' ' );
269 wxString str
= GetLocalDir();
279 if ( wxStrchr(szFile
, wxT('.')) == NULL
)
285 str
<< " Preferences";
290 // ----------------------------------------------------------------------------
292 // ----------------------------------------------------------------------------
294 void wxFileConfig::Init()
297 m_pRootGroup
= new ConfigGroup(NULL
, "", this);
302 // it's not an error if (one of the) file(s) doesn't exist
304 // parse the global file
305 if ( !m_strGlobalFile
.IsEmpty() && wxFile::Exists(m_strGlobalFile
) ) {
306 wxTextFile
fileGlobal(m_strGlobalFile
);
308 if ( fileGlobal
.Open() ) {
309 Parse(fileGlobal
, FALSE
/* global */);
313 wxLogWarning(_("can't open global configuration file '%s'."),
314 m_strGlobalFile
.c_str());
317 // parse the local file
318 if ( !m_strLocalFile
.IsEmpty() && wxFile::Exists(m_strLocalFile
) ) {
319 wxTextFile
fileLocal(m_strLocalFile
);
320 if ( fileLocal
.Open() ) {
321 Parse(fileLocal
, TRUE
/* local */);
325 wxLogWarning(_("can't open user configuration file '%s'."),
326 m_strLocalFile
.c_str());
330 // constructor supports creation of wxFileConfig objects of any type
331 wxFileConfig::wxFileConfig(const wxString
& appName
, const wxString
& vendorName
,
332 const wxString
& strLocal
, const wxString
& strGlobal
,
334 : wxConfigBase(::GetAppName(appName
), vendorName
,
337 m_strLocalFile(strLocal
), m_strGlobalFile(strGlobal
)
339 // Make up names for files if empty
340 if ( m_strLocalFile
.IsEmpty() && (style
& wxCONFIG_USE_LOCAL_FILE
) )
342 m_strLocalFile
= GetLocalFileName(GetAppName());
345 if ( m_strGlobalFile
.IsEmpty() && (style
& wxCONFIG_USE_GLOBAL_FILE
) )
347 m_strGlobalFile
= GetGlobalFileName(GetAppName());
350 // Check if styles are not supplied, but filenames are, in which case
351 // add the correct styles.
352 if ( !m_strLocalFile
.IsEmpty() )
353 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
355 if ( !m_strGlobalFile
.IsEmpty() )
356 SetStyle(GetStyle() | wxCONFIG_USE_GLOBAL_FILE
);
358 // if the path is not absolute, prepend the standard directory to it
359 // UNLESS wxCONFIG_USE_RELATIVE_PATH style is set
360 if ( !(style
& wxCONFIG_USE_RELATIVE_PATH
) )
362 if ( !m_strLocalFile
.IsEmpty() && !wxIsAbsolutePath(m_strLocalFile
) )
364 wxString strLocal
= m_strLocalFile
;
365 m_strLocalFile
= GetLocalDir();
366 m_strLocalFile
<< strLocal
;
369 if ( !m_strGlobalFile
.IsEmpty() && !wxIsAbsolutePath(m_strGlobalFile
) )
371 wxString strGlobal
= m_strGlobalFile
;
372 m_strGlobalFile
= GetGlobalDir();
373 m_strGlobalFile
<< strGlobal
;
380 void wxFileConfig::CleanUp()
384 LineList
*pCur
= m_linesHead
;
385 while ( pCur
!= NULL
) {
386 LineList
*pNext
= pCur
->Next();
392 wxFileConfig::~wxFileConfig()
399 // ----------------------------------------------------------------------------
400 // parse a config file
401 // ----------------------------------------------------------------------------
403 void wxFileConfig::Parse(wxTextFile
& file
, bool bLocal
)
405 const wxChar
*pStart
;
409 size_t nLineCount
= file
.GetLineCount();
410 for ( size_t n
= 0; n
< nLineCount
; n
++ ) {
413 // add the line to linked list
415 LineListAppend(strLine
);
417 // skip leading spaces
418 for ( pStart
= strLine
; wxIsspace(*pStart
); pStart
++ )
421 // skip blank/comment lines
422 if ( *pStart
== wxT('\0')|| *pStart
== wxT(';') || *pStart
== wxT('#') )
425 if ( *pStart
== wxT('[') ) { // a new group
428 while ( *++pEnd
!= wxT(']') ) {
429 if ( *pEnd
== wxT('\n') || *pEnd
== wxT('\0') )
433 if ( *pEnd
!= wxT(']') ) {
434 wxLogError(_("file '%s': unexpected character %c at line %d."),
435 file
.GetName(), *pEnd
, n
+ 1);
436 continue; // skip this line
439 // group name here is always considered as abs path
442 strGroup
<< wxCONFIG_PATH_SEPARATOR
443 << FilterInEntryName(wxString(pStart
, pEnd
- pStart
));
445 // will create it if doesn't yet exist
449 m_pCurrentGroup
->SetLine(m_linesTail
);
451 // check that there is nothing except comments left on this line
453 while ( *++pEnd
!= wxT('\0') && bCont
) {
462 // ignore whitespace ('\n' impossible here)
466 wxLogWarning(_("file '%s', line %d: '%s' "
467 "ignored after group header."),
468 file
.GetName(), n
+ 1, pEnd
);
474 const wxChar
*pEnd
= pStart
;
475 while ( *pEnd
!= wxT('=') && !wxIsspace(*pEnd
) ) {
476 if ( *pEnd
== wxT('\\') ) {
477 // next character may be space or not - still take it because it's
485 wxString
strKey(FilterInEntryName(wxString(pStart
, pEnd
)));
488 while ( isspace(*pEnd
) )
491 if ( *pEnd
++ != wxT('=') ) {
492 wxLogError(_("file '%s', line %d: '=' expected."),
493 file
.GetName(), n
+ 1);
496 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strKey
);
498 if ( pEntry
== NULL
) {
500 pEntry
= m_pCurrentGroup
->AddEntry(strKey
, n
);
503 pEntry
->SetLine(m_linesTail
);
506 if ( bLocal
&& pEntry
->IsImmutable() ) {
507 // immutable keys can't be changed by user
508 wxLogWarning(_("file '%s', line %d: value for "
509 "immutable key '%s' ignored."),
510 file
.GetName(), n
+ 1, strKey
.c_str());
513 // the condition below catches the cases (a) and (b) but not (c):
514 // (a) global key found second time in global file
515 // (b) key found second (or more) time in local file
516 // (c) key from global file now found in local one
517 // which is exactly what we want.
518 else if ( !bLocal
|| pEntry
->IsLocal() ) {
519 wxLogWarning(_("file '%s', line %d: key '%s' was first "
520 "found at line %d."),
521 file
.GetName(), n
+ 1, strKey
.c_str(), pEntry
->Line());
524 pEntry
->SetLine(m_linesTail
);
529 while ( wxIsspace(*pEnd
) )
532 pEntry
->SetValue(FilterInValue(pEnd
), FALSE
/* read from file */);
538 // ----------------------------------------------------------------------------
540 // ----------------------------------------------------------------------------
542 void wxFileConfig::SetRootPath()
545 m_pCurrentGroup
= m_pRootGroup
;
548 void wxFileConfig::SetPath(const wxString
& strPath
)
550 wxArrayString aParts
;
552 if ( strPath
.IsEmpty() ) {
557 if ( strPath
[0] == wxCONFIG_PATH_SEPARATOR
) {
559 wxSplitPath(aParts
, strPath
);
562 // relative path, combine with current one
563 wxString strFullPath
= m_strPath
;
564 strFullPath
<< wxCONFIG_PATH_SEPARATOR
<< strPath
;
565 wxSplitPath(aParts
, strFullPath
);
568 // change current group
570 m_pCurrentGroup
= m_pRootGroup
;
571 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
572 ConfigGroup
*pNextGroup
= m_pCurrentGroup
->FindSubgroup(aParts
[n
]);
573 if ( pNextGroup
== NULL
)
574 pNextGroup
= m_pCurrentGroup
->AddSubgroup(aParts
[n
]);
575 m_pCurrentGroup
= pNextGroup
;
578 // recombine path parts in one variable
580 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
581 m_strPath
<< wxCONFIG_PATH_SEPARATOR
<< aParts
[n
];
585 // ----------------------------------------------------------------------------
587 // ----------------------------------------------------------------------------
589 bool wxFileConfig::GetFirstGroup(wxString
& str
, long& lIndex
) const
592 return GetNextGroup(str
, lIndex
);
595 bool wxFileConfig::GetNextGroup (wxString
& str
, long& lIndex
) const
597 if ( size_t(lIndex
) < m_pCurrentGroup
->Groups().Count() ) {
598 str
= m_pCurrentGroup
->Groups()[(size_t)lIndex
++]->Name();
605 bool wxFileConfig::GetFirstEntry(wxString
& str
, long& lIndex
) const
608 return GetNextEntry(str
, lIndex
);
611 bool wxFileConfig::GetNextEntry (wxString
& str
, long& lIndex
) const
613 if ( size_t(lIndex
) < m_pCurrentGroup
->Entries().Count() ) {
614 str
= m_pCurrentGroup
->Entries()[(size_t)lIndex
++]->Name();
621 size_t wxFileConfig::GetNumberOfEntries(bool bRecursive
) const
623 size_t n
= m_pCurrentGroup
->Entries().Count();
625 ConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
626 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
627 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
628 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
629 n
+= GetNumberOfEntries(TRUE
);
630 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
637 size_t wxFileConfig::GetNumberOfGroups(bool bRecursive
) const
639 size_t n
= m_pCurrentGroup
->Groups().Count();
641 ConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
642 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
643 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
644 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
645 n
+= GetNumberOfGroups(TRUE
);
646 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
653 // ----------------------------------------------------------------------------
654 // tests for existence
655 // ----------------------------------------------------------------------------
657 bool wxFileConfig::HasGroup(const wxString
& strName
) const
659 wxConfigPathChanger
path(this, strName
);
661 ConfigGroup
*pGroup
= m_pCurrentGroup
->FindSubgroup(path
.Name());
662 return pGroup
!= NULL
;
665 bool wxFileConfig::HasEntry(const wxString
& strName
) const
667 wxConfigPathChanger
path(this, strName
);
669 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
670 return pEntry
!= NULL
;
673 // ----------------------------------------------------------------------------
675 // ----------------------------------------------------------------------------
677 bool wxFileConfig::Read(const wxString
& key
,
678 wxString
* pStr
) const
680 wxConfigPathChanger
path(this, key
);
682 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
683 if (pEntry
== NULL
) {
687 *pStr
= ExpandEnvVars(pEntry
->Value());
692 bool wxFileConfig::Read(const wxString
& key
,
693 wxString
* pStr
, const wxString
& defVal
) const
695 wxConfigPathChanger
path(this, key
);
697 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
698 if (pEntry
== NULL
) {
699 if( IsRecordingDefaults() )
700 ((wxFileConfig
*)this)->Write(key
,defVal
);
701 *pStr
= ExpandEnvVars(defVal
);
705 *pStr
= ExpandEnvVars(pEntry
->Value());
710 bool wxFileConfig::Read(const wxString
& key
, long *pl
) const
713 if ( Read(key
, & str
) ) {
722 bool wxFileConfig::Write(const wxString
& key
, const wxString
& szValue
)
724 wxConfigPathChanger
path(this, key
);
726 wxString strName
= path
.Name();
727 if ( strName
.IsEmpty() ) {
728 // setting the value of a group is an error
729 wxASSERT_MSG( wxIsEmpty(szValue
), wxT("can't set value of a group!") );
731 // ... except if it's empty in which case it's a way to force it's creation
732 m_pCurrentGroup
->SetDirty();
734 // this will add a line for this group if it didn't have it before
735 (void)m_pCurrentGroup
->GetGroupLine();
740 // check that the name is reasonable
741 if ( strName
[0u] == wxCONFIG_IMMUTABLE_PREFIX
) {
742 wxLogError(_("Config entry name cannot start with '%c'."),
743 wxCONFIG_IMMUTABLE_PREFIX
);
747 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strName
);
748 if ( pEntry
== NULL
)
749 pEntry
= m_pCurrentGroup
->AddEntry(strName
);
751 pEntry
->SetValue(szValue
);
757 bool wxFileConfig::Write(const wxString
& key
, long lValue
)
759 // ltoa() is not ANSI :-(
761 buf
.Printf(wxT("%ld"), lValue
);
762 return Write(key
, buf
);
765 bool wxFileConfig::Flush(bool /* bCurrentOnly */)
767 if ( LineListIsEmpty() || !m_pRootGroup
->IsDirty() )
770 wxTempFile
file(m_strLocalFile
);
772 if ( !file
.IsOpened() ) {
773 wxLogError(_("can't open user configuration file."));
777 // write all strings to file
778 for ( LineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() ) {
779 if ( !file
.Write(p
->Text() + wxTextFile::GetEOL()) ) {
780 wxLogError(_("can't write user configuration file."));
786 return file
.Commit();
788 bool ret
= file
.Commit();
793 wxUnixFilename2FSSpec( m_strLocalFile
, &spec
) ;
795 if ( FSpGetFInfo( &spec
, &finfo
) == noErr
)
797 finfo
.fdType
= 'TEXT' ;
798 finfo
.fdCreator
= 'ttxt' ;
799 FSpSetFInfo( &spec
, &finfo
) ;
806 // ----------------------------------------------------------------------------
807 // renaming groups/entries
808 // ----------------------------------------------------------------------------
810 bool wxFileConfig::RenameEntry(const wxString
& oldName
,
811 const wxString
& newName
)
813 // check that the entry exists
814 ConfigEntry
*oldEntry
= m_pCurrentGroup
->FindEntry(oldName
);
818 // check that the new entry doesn't already exist
819 if ( m_pCurrentGroup
->FindEntry(newName
) )
822 // delete the old entry, create the new one
823 wxString value
= oldEntry
->Value();
824 if ( !m_pCurrentGroup
->DeleteEntry(oldName
) )
827 ConfigEntry
*newEntry
= m_pCurrentGroup
->AddEntry(newName
);
828 newEntry
->SetValue(value
);
833 bool wxFileConfig::RenameGroup(const wxString
& oldName
,
834 const wxString
& newName
)
836 // check that the group exists
837 ConfigGroup
*group
= m_pCurrentGroup
->FindSubgroup(oldName
);
841 // check that the new group doesn't already exist
842 if ( m_pCurrentGroup
->FindSubgroup(newName
) )
845 group
->Rename(newName
);
850 // ----------------------------------------------------------------------------
851 // delete groups/entries
852 // ----------------------------------------------------------------------------
854 bool wxFileConfig::DeleteEntry(const wxString
& key
, bool bGroupIfEmptyAlso
)
856 wxConfigPathChanger
path(this, key
);
858 if ( !m_pCurrentGroup
->DeleteEntry(path
.Name()) )
861 if ( bGroupIfEmptyAlso
&& m_pCurrentGroup
->IsEmpty() ) {
862 if ( m_pCurrentGroup
!= m_pRootGroup
) {
863 ConfigGroup
*pGroup
= m_pCurrentGroup
;
864 SetPath(wxT("..")); // changes m_pCurrentGroup!
865 m_pCurrentGroup
->DeleteSubgroupByName(pGroup
->Name());
867 //else: never delete the root group
873 bool wxFileConfig::DeleteGroup(const wxString
& key
)
875 wxConfigPathChanger
path(this, key
);
877 return m_pCurrentGroup
->DeleteSubgroupByName(path
.Name());
880 bool wxFileConfig::DeleteAll()
884 if ( remove(m_strLocalFile
.fn_str()) == -1 )
885 wxLogSysError(_("can't delete user configuration file '%s'"), m_strLocalFile
.c_str());
887 m_strLocalFile
= m_strGlobalFile
= wxT("");
893 // ----------------------------------------------------------------------------
894 // linked list functions
895 // ----------------------------------------------------------------------------
897 // append a new line to the end of the list
898 LineList
*wxFileConfig::LineListAppend(const wxString
& str
)
900 LineList
*pLine
= new LineList(str
);
902 if ( m_linesTail
== NULL
) {
908 m_linesTail
->SetNext(pLine
);
909 pLine
->SetPrev(m_linesTail
);
916 // insert a new line after the given one or in the very beginning if !pLine
917 LineList
*wxFileConfig::LineListInsert(const wxString
& str
,
920 if ( pLine
== m_linesTail
)
921 return LineListAppend(str
);
923 LineList
*pNewLine
= new LineList(str
);
924 if ( pLine
== NULL
) {
925 // prepend to the list
926 pNewLine
->SetNext(m_linesHead
);
927 m_linesHead
->SetPrev(pNewLine
);
928 m_linesHead
= pNewLine
;
931 // insert before pLine
932 LineList
*pNext
= pLine
->Next();
933 pNewLine
->SetNext(pNext
);
934 pNewLine
->SetPrev(pLine
);
935 pNext
->SetPrev(pNewLine
);
936 pLine
->SetNext(pNewLine
);
942 void wxFileConfig::LineListRemove(LineList
*pLine
)
944 LineList
*pPrev
= pLine
->Prev(),
945 *pNext
= pLine
->Next();
951 pPrev
->SetNext(pNext
);
957 pNext
->SetPrev(pPrev
);
962 bool wxFileConfig::LineListIsEmpty()
964 return m_linesHead
== NULL
;
967 // ============================================================================
968 // wxFileConfig::ConfigGroup
969 // ============================================================================
971 // ----------------------------------------------------------------------------
973 // ----------------------------------------------------------------------------
976 ConfigGroup::ConfigGroup(ConfigGroup
*pParent
,
977 const wxString
& strName
,
978 wxFileConfig
*pConfig
)
979 : m_aEntries(CompareEntries
),
980 m_aSubgroups(CompareGroups
),
992 // dtor deletes all children
993 ConfigGroup::~ConfigGroup()
996 size_t n
, nCount
= m_aEntries
.Count();
997 for ( n
= 0; n
< nCount
; n
++ )
998 delete m_aEntries
[n
];
1001 nCount
= m_aSubgroups
.Count();
1002 for ( n
= 0; n
< nCount
; n
++ )
1003 delete m_aSubgroups
[n
];
1006 // ----------------------------------------------------------------------------
1008 // ----------------------------------------------------------------------------
1010 void ConfigGroup::SetLine(LineList
*pLine
)
1012 wxASSERT( m_pLine
== NULL
); // shouldn't be called twice
1018 This is a bit complicated, so let me explain it in details. All lines that
1019 were read from the local file (the only one we will ever modify) are stored
1020 in a (doubly) linked list. Our problem is to know at which position in this
1021 list should we insert the new entries/subgroups. To solve it we keep three
1022 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1024 m_pLine points to the line containing "[group_name]"
1025 m_pLastEntry points to the last entry of this group in the local file.
1026 m_pLastGroup subgroup
1028 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1029 from the local file, the corresponding variable is set. However, if the group
1030 was read from the global file and then modified or created by the application
1031 these variables are still NULL and we need to create the corresponding lines.
1032 See the following functions (and comments preceding them) for the details of
1035 Also, when our last entry/group are deleted we need to find the new last
1036 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1037 of lines until it either founds an entry/subgroup (and this is the new last
1038 element) or the m_pLine of the group, in which case there are no more entries
1039 (or subgroups) left and m_pLast<element> becomes NULL.
1041 NB: This last problem could be avoided for entries if we added new entries
1042 immediately after m_pLine, but in this case the entries would appear
1043 backwards in the config file (OTOH, it's not that important) and as we
1044 would still need to do it for the subgroups the code wouldn't have been
1045 significantly less complicated.
1048 // Return the line which contains "[our name]". If we're still not in the list,
1049 // add our line to it immediately after the last line of our parent group if we
1050 // have it or in the very beginning if we're the root group.
1051 LineList
*ConfigGroup::GetGroupLine()
1053 if ( m_pLine
== NULL
) {
1054 ConfigGroup
*pParent
= Parent();
1056 // this group wasn't present in local config file, add it now
1057 if ( pParent
!= NULL
) {
1058 wxString strFullName
;
1059 strFullName
<< wxT("[")
1061 << FilterOutEntryName(GetFullName().c_str() + 1)
1063 m_pLine
= m_pConfig
->LineListInsert(strFullName
,
1064 pParent
->GetLastGroupLine());
1065 pParent
->SetLastGroup(this); // we're surely after all the others
1068 // we return NULL, so that LineListInsert() will insert us in the
1076 // Return the last line belonging to the subgroups of this group (after which
1077 // we can add a new subgroup), if we don't have any subgroups or entries our
1078 // last line is the group line (m_pLine) itself.
1079 LineList
*ConfigGroup::GetLastGroupLine()
1081 // if we have any subgroups, our last line is the last line of the last
1083 if ( m_pLastGroup
!= NULL
) {
1084 LineList
*pLine
= m_pLastGroup
->GetLastGroupLine();
1086 wxASSERT( pLine
!= NULL
); // last group must have !NULL associated line
1090 // no subgroups, so the last line is the line of thelast entry (if any)
1091 return GetLastEntryLine();
1094 // return the last line belonging to the entries of this group (after which
1095 // we can add a new entry), if we don't have any entries we will add the new
1096 // one immediately after the group line itself.
1097 LineList
*ConfigGroup::GetLastEntryLine()
1099 if ( m_pLastEntry
!= NULL
) {
1100 LineList
*pLine
= m_pLastEntry
->GetLine();
1102 wxASSERT( pLine
!= NULL
); // last entry must have !NULL associated line
1106 // no entries: insert after the group header
1107 return GetGroupLine();
1110 // ----------------------------------------------------------------------------
1112 // ----------------------------------------------------------------------------
1114 void ConfigGroup::Rename(const wxString
& newName
)
1116 m_strName
= newName
;
1118 LineList
*line
= GetGroupLine();
1119 wxString strFullName
;
1120 strFullName
<< wxT("[") << (GetFullName().c_str() + 1) << wxT("]"); // +1: no '/'
1121 line
->SetText(strFullName
);
1126 wxString
ConfigGroup::GetFullName() const
1129 return Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR
+ Name();
1134 // ----------------------------------------------------------------------------
1136 // ----------------------------------------------------------------------------
1138 // use binary search because the array is sorted
1140 ConfigGroup::FindEntry(const wxChar
*szName
) const
1144 hi
= m_aEntries
.Count();
1146 ConfigEntry
*pEntry
;
1150 pEntry
= m_aEntries
[i
];
1152 #if wxCONFIG_CASE_SENSITIVE
1153 res
= wxStrcmp(pEntry
->Name(), szName
);
1155 res
= wxStricmp(pEntry
->Name(), szName
);
1170 ConfigGroup::FindSubgroup(const wxChar
*szName
) const
1174 hi
= m_aSubgroups
.Count();
1176 ConfigGroup
*pGroup
;
1180 pGroup
= m_aSubgroups
[i
];
1182 #if wxCONFIG_CASE_SENSITIVE
1183 res
= wxStrcmp(pGroup
->Name(), szName
);
1185 res
= wxStricmp(pGroup
->Name(), szName
);
1199 // ----------------------------------------------------------------------------
1200 // create a new item
1201 // ----------------------------------------------------------------------------
1203 // create a new entry and add it to the current group
1205 ConfigGroup::AddEntry(const wxString
& strName
, int nLine
)
1207 wxASSERT( FindEntry(strName
) == NULL
);
1209 ConfigEntry
*pEntry
= new ConfigEntry(this, strName
, nLine
);
1210 m_aEntries
.Add(pEntry
);
1215 // create a new group and add it to the current group
1217 ConfigGroup::AddSubgroup(const wxString
& strName
)
1219 wxASSERT( FindSubgroup(strName
) == NULL
);
1221 ConfigGroup
*pGroup
= new ConfigGroup(this, strName
, m_pConfig
);
1222 m_aSubgroups
.Add(pGroup
);
1227 // ----------------------------------------------------------------------------
1229 // ----------------------------------------------------------------------------
1232 The delete operations are _very_ slow if we delete the last item of this
1233 group (see comments before GetXXXLineXXX functions for more details),
1234 so it's much better to start with the first entry/group if we want to
1235 delete several of them.
1238 bool ConfigGroup::DeleteSubgroupByName(const wxChar
*szName
)
1240 return DeleteSubgroup(FindSubgroup(szName
));
1243 // doesn't delete the subgroup itself, but does remove references to it from
1244 // all other data structures (and normally the returned pointer should be
1245 // deleted a.s.a.p. because there is nothing much to be done with it anyhow)
1246 bool ConfigGroup::DeleteSubgroup(ConfigGroup
*pGroup
)
1248 wxCHECK( pGroup
!= NULL
, FALSE
); // deleting non existing group?
1250 // delete all entries
1251 size_t nCount
= pGroup
->m_aEntries
.Count();
1252 for ( size_t nEntry
= 0; nEntry
< nCount
; nEntry
++ ) {
1253 LineList
*pLine
= pGroup
->m_aEntries
[nEntry
]->GetLine();
1254 if ( pLine
!= NULL
)
1255 m_pConfig
->LineListRemove(pLine
);
1258 // and subgroups of this sungroup
1259 nCount
= pGroup
->m_aSubgroups
.Count();
1260 for ( size_t nGroup
= 0; nGroup
< nCount
; nGroup
++ ) {
1261 pGroup
->DeleteSubgroup(pGroup
->m_aSubgroups
[0]);
1264 LineList
*pLine
= pGroup
->m_pLine
;
1265 if ( pLine
!= NULL
) {
1266 // notice that we may do this test inside the previous "if" because the
1267 // last entry's line is surely !NULL
1268 if ( pGroup
== m_pLastGroup
) {
1269 // our last entry is being deleted - find the last one which stays
1270 wxASSERT( m_pLine
!= NULL
); // we have a subgroup with !NULL pLine...
1272 // go back until we find a subgroup or reach the group's line
1273 ConfigGroup
*pNewLast
= NULL
;
1274 size_t n
, nSubgroups
= m_aSubgroups
.Count();
1276 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1277 // is it our subgroup?
1278 for ( n
= 0; (pNewLast
== NULL
) && (n
< nSubgroups
); n
++ ) {
1279 // do _not_ call GetGroupLine! we don't want to add it to the local
1280 // file if it's not already there
1281 if ( m_aSubgroups
[n
]->m_pLine
== m_pLine
)
1282 pNewLast
= m_aSubgroups
[n
];
1285 if ( pNewLast
!= NULL
) // found?
1289 if ( pl
== m_pLine
) {
1290 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1292 // we've reached the group line without finding any subgroups
1293 m_pLastGroup
= NULL
;
1296 m_pLastGroup
= pNewLast
;
1299 m_pConfig
->LineListRemove(pLine
);
1304 m_aSubgroups
.Remove(pGroup
);
1310 bool ConfigGroup::DeleteEntry(const wxChar
*szName
)
1312 ConfigEntry
*pEntry
= FindEntry(szName
);
1313 wxCHECK( pEntry
!= NULL
, FALSE
); // deleting non existing item?
1315 LineList
*pLine
= pEntry
->GetLine();
1316 if ( pLine
!= NULL
) {
1317 // notice that we may do this test inside the previous "if" because the
1318 // last entry's line is surely !NULL
1319 if ( pEntry
== m_pLastEntry
) {
1320 // our last entry is being deleted - find the last one which stays
1321 wxASSERT( m_pLine
!= NULL
); // if we have an entry with !NULL pLine...
1323 // go back until we find another entry or reach the group's line
1324 ConfigEntry
*pNewLast
= NULL
;
1325 size_t n
, nEntries
= m_aEntries
.Count();
1327 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1328 // is it our subgroup?
1329 for ( n
= 0; (pNewLast
== NULL
) && (n
< nEntries
); n
++ ) {
1330 if ( m_aEntries
[n
]->GetLine() == m_pLine
)
1331 pNewLast
= m_aEntries
[n
];
1334 if ( pNewLast
!= NULL
) // found?
1338 if ( pl
== m_pLine
) {
1339 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1341 // we've reached the group line without finding any subgroups
1342 m_pLastEntry
= NULL
;
1345 m_pLastEntry
= pNewLast
;
1348 m_pConfig
->LineListRemove(pLine
);
1351 // we must be written back for the changes to be saved
1354 m_aEntries
.Remove(pEntry
);
1360 // ----------------------------------------------------------------------------
1362 // ----------------------------------------------------------------------------
1363 void ConfigGroup::SetDirty()
1366 if ( Parent() != NULL
) // propagate upwards
1367 Parent()->SetDirty();
1370 // ============================================================================
1371 // wxFileConfig::ConfigEntry
1372 // ============================================================================
1374 // ----------------------------------------------------------------------------
1376 // ----------------------------------------------------------------------------
1377 ConfigEntry::ConfigEntry(ConfigGroup
*pParent
,
1378 const wxString
& strName
,
1380 : m_strName(strName
)
1382 wxASSERT( !strName
.IsEmpty() );
1384 m_pParent
= pParent
;
1390 m_bImmutable
= strName
[0] == wxCONFIG_IMMUTABLE_PREFIX
;
1392 m_strName
.erase(0, 1); // remove first character
1395 // ----------------------------------------------------------------------------
1397 // ----------------------------------------------------------------------------
1399 void ConfigEntry::SetLine(LineList
*pLine
)
1401 if ( m_pLine
!= NULL
) {
1402 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1403 Name().c_str(), m_pParent
->GetFullName().c_str());
1407 Group()->SetLastEntry(this);
1410 // second parameter is FALSE if we read the value from file and prevents the
1411 // entry from being marked as 'dirty'
1412 void ConfigEntry::SetValue(const wxString
& strValue
, bool bUser
)
1414 if ( bUser
&& IsImmutable() ) {
1415 wxLogWarning(_("attempt to change immutable key '%s' ignored."),
1420 // do nothing if it's the same value
1421 if ( strValue
== m_strValue
)
1424 m_strValue
= strValue
;
1427 wxString strVal
= FilterOutValue(strValue
);
1429 strLine
<< FilterOutEntryName(m_strName
) << wxT('=') << strVal
;
1431 if ( m_pLine
!= NULL
) {
1432 // entry was read from the local config file, just modify the line
1433 m_pLine
->SetText(strLine
);
1436 // add a new line to the file
1437 wxASSERT( m_nLine
== wxNOT_FOUND
); // consistency check
1439 m_pLine
= Group()->Config()->LineListInsert(strLine
,
1440 Group()->GetLastEntryLine());
1441 Group()->SetLastEntry(this);
1448 void ConfigEntry::SetDirty()
1451 Group()->SetDirty();
1454 // ============================================================================
1456 // ============================================================================
1458 // ----------------------------------------------------------------------------
1459 // compare functions for array sorting
1460 // ----------------------------------------------------------------------------
1462 int CompareEntries(ConfigEntry
*p1
,
1465 #if wxCONFIG_CASE_SENSITIVE
1466 return wxStrcmp(p1
->Name(), p2
->Name());
1468 return wxStricmp(p1
->Name(), p2
->Name());
1472 int CompareGroups(ConfigGroup
*p1
,
1475 #if wxCONFIG_CASE_SENSITIVE
1476 return wxStrcmp(p1
->Name(), p2
->Name());
1478 return wxStricmp(p1
->Name(), p2
->Name());
1482 // ----------------------------------------------------------------------------
1484 // ----------------------------------------------------------------------------
1486 // undo FilterOutValue
1487 static wxString
FilterInValue(const wxString
& str
)
1490 strResult
.Alloc(str
.Len());
1492 bool bQuoted
= !str
.IsEmpty() && str
[0] == '"';
1494 for ( size_t n
= bQuoted
? 1 : 0; n
< str
.Len(); n
++ ) {
1495 if ( str
[n
] == wxT('\\') ) {
1496 switch ( str
[++n
] ) {
1498 strResult
+= wxT('\n');
1502 strResult
+= wxT('\r');
1506 strResult
+= wxT('\t');
1510 strResult
+= wxT('\\');
1514 strResult
+= wxT('"');
1519 if ( str
[n
] != wxT('"') || !bQuoted
)
1520 strResult
+= str
[n
];
1521 else if ( n
!= str
.Len() - 1 ) {
1522 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1525 //else: it's the last quote of a quoted string, ok
1532 // quote the string before writing it to file
1533 static wxString
FilterOutValue(const wxString
& str
)
1539 strResult
.Alloc(str
.Len());
1541 // quoting is necessary to preserve spaces in the beginning of the string
1542 bool bQuote
= wxIsspace(str
[0]) || str
[0] == wxT('"');
1545 strResult
+= wxT('"');
1548 for ( size_t n
= 0; n
< str
.Len(); n
++ ) {
1571 //else: fall through
1574 strResult
+= str
[n
];
1575 continue; // nothing special to do
1578 // we get here only for special characters
1579 strResult
<< wxT('\\') << c
;
1583 strResult
+= wxT('"');
1588 // undo FilterOutEntryName
1589 static wxString
FilterInEntryName(const wxString
& str
)
1592 strResult
.Alloc(str
.Len());
1594 for ( const wxChar
*pc
= str
.c_str(); *pc
!= '\0'; pc
++ ) {
1595 if ( *pc
== wxT('\\') )
1604 // sanitize entry or group name: insert '\\' before any special characters
1605 static wxString
FilterOutEntryName(const wxString
& str
)
1608 strResult
.Alloc(str
.Len());
1610 for ( const wxChar
*pc
= str
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
1613 // we explicitly allow some of "safe" chars and 8bit ASCII characters
1614 // which will probably never have special meaning
1615 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
1616 // should *not* be quoted
1617 if ( !wxIsalnum(c
) && !wxStrchr(wxT("@_/-!.*%"), c
) && ((c
& 0x80) == 0) )
1618 strResult
+= wxT('\\');
1626 // we can't put ?: in the ctor initializer list because it confuses some
1627 // broken compilers (Borland C++)
1628 static wxString
GetAppName(const wxString
& appName
)
1630 if ( !appName
&& wxTheApp
)
1631 return wxTheApp
->GetAppName();
1636 #endif // wxUSE_CONFIG