1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: implementation of wxFileConfig derivation of wxConfig
4 // Author: Vadim Zeitlin
6 // Created: 07.04.98 (adapted from appconf.cpp)
8 // Copyright: (c) 1997 Karsten Ballüder & Vadim Zeitlin
9 // Ballueder@usa.net <zeitlin@dptmaths.ens-cachan.fr>
10 // Licence: wxWindows license
11 ///////////////////////////////////////////////////////////////////////////////
14 #pragma implementation "fileconf.h"
17 // ----------------------------------------------------------------------------
19 // ----------------------------------------------------------------------------
21 #include "wx/wxprec.h"
30 #include "wx/string.h"
35 #include "wx/dynarray.h"
38 #include "wx/textfile.h"
39 #include "wx/config.h"
40 #include "wx/fileconf.h"
42 #include "wx/utils.h" // for wxGetHomeDir
44 // _WINDOWS_ is defined when windows.h is included,
45 // __WXMSW__ is defined for MS Windows compilation
46 #if defined(__WXMSW__) && !defined(_WINDOWS_)
57 // headers needed for umask()
59 #include <sys/types.h>
63 // ----------------------------------------------------------------------------
65 // ----------------------------------------------------------------------------
66 #define CONST_CAST ((wxFileConfig *)this)->
68 // ----------------------------------------------------------------------------
70 // ----------------------------------------------------------------------------
75 // ----------------------------------------------------------------------------
76 // global functions declarations
77 // ----------------------------------------------------------------------------
79 // compare functions for sorting the arrays
80 static int LINKAGEMODE
CompareEntries(ConfigEntry
*p1
, ConfigEntry
*p2
);
81 static int LINKAGEMODE
CompareGroups(ConfigGroup
*p1
, ConfigGroup
*p2
);
84 static wxString
FilterInValue(const wxString
& str
);
85 static wxString
FilterOutValue(const wxString
& str
);
87 static wxString
FilterInEntryName(const wxString
& str
);
88 static wxString
FilterOutEntryName(const wxString
& str
);
90 // get the name to use in wxFileConfig ctor
91 static wxString
GetAppName(const wxString
& appname
);
93 // ============================================================================
95 // ============================================================================
97 // ----------------------------------------------------------------------------
99 // ----------------------------------------------------------------------------
100 wxString
wxFileConfig::GetGlobalDir()
104 #ifdef __VMS__ // Note if __VMS is defined __UNIX is also defined
105 strDir
= wxT("sys$manager:");
106 #elif defined( __UNIX__ )
107 strDir
= wxT("/etc/");
108 #elif defined(__WXPM__)
109 ULONG aulSysInfo
[QSV_MAX
] = {0};
113 rc
= DosQuerySysInfo( 1L, QSV_MAX
, (PVOID
)aulSysInfo
, sizeof(ULONG
)*QSV_MAX
);
116 drive
= aulSysInfo
[QSV_BOOT_DRIVE
- 1];
120 strDir
= "A:\\OS2\\";
123 strDir
= "B:\\OS2\\";
126 strDir
= "C:\\OS2\\";
129 strDir
= "D:\\OS2\\";
132 strDir
= "E:\\OS2\\";
135 strDir
= "F:\\OS2\\";
138 strDir
= "G:\\OS2\\";
141 strDir
= "H:\\OS2\\";
144 strDir
= "I:\\OS2\\";
147 strDir
= "J:\\OS2\\";
150 strDir
= "K:\\OS2\\";
153 strDir
= "L:\\OS2\\";
156 strDir
= "M:\\OS2\\";
159 strDir
= "N:\\OS2\\";
162 strDir
= "O:\\OS2\\";
165 strDir
= "P:\\OS2\\";
168 strDir
= "Q:\\OS2\\";
171 strDir
= "R:\\OS2\\";
174 strDir
= "S:\\OS2\\";
177 strDir
= "T:\\OS2\\";
180 strDir
= "U:\\OS2\\";
183 strDir
= "V:\\OS2\\";
186 strDir
= "W:\\OS2\\";
189 strDir
= "X:\\OS2\\";
192 strDir
= "Y:\\OS2\\";
195 strDir
= "Z:\\OS2\\";
199 #elif defined(__WXSTUBS__)
200 wxASSERT_MSG( FALSE
, wxT("TODO") ) ;
201 #elif defined(__WXMAC__)
206 if ( FindFolder( (short) kOnSystemDisk
, kPreferencesFolderType
, kDontCreateFolder
, &vRefNum
, &dirID
) == noErr
)
209 if ( FSMakeFSSpec( vRefNum
, dirID
, "\p" , &file
) == noErr
)
211 strDir
= wxMacFSSpec2UnixFilename( &file
) + "/" ;
216 wxChar szWinDir
[MAX_PATH
];
217 ::GetWindowsDirectory(szWinDir
, MAX_PATH
);
221 #endif // Unix/Windows
226 wxString
wxFileConfig::GetLocalDir()
231 wxGetHomeDir(&strDir
);
235 if (strDir
.Last() != wxT('/')) strDir
<< wxT('/');
237 if (strDir
.Last() != wxT('\\')) strDir
<< wxT('\\');
241 // no local dir concept on mac
242 return GetGlobalDir() ;
248 wxString
wxFileConfig::GetGlobalFileName(const wxChar
*szFile
)
250 wxString str
= GetGlobalDir();
253 if ( wxStrchr(szFile
, wxT('.')) == NULL
)
256 #elif defined( __WXMAC__ )
257 str
<< " Preferences";
265 wxString
wxFileConfig::GetLocalFileName(const wxChar
*szFile
)
267 #ifdef __VMS__ // On VMS I saw the problem that the home directory was appended
268 // twice for the configuration file. Does that also happen for other
270 wxString str
= wxT( ' ' );
272 wxString str
= GetLocalDir();
282 if ( wxStrchr(szFile
, wxT('.')) == NULL
)
288 str
<< " Preferences";
293 // ----------------------------------------------------------------------------
295 // ----------------------------------------------------------------------------
297 void wxFileConfig::Init()
300 m_pRootGroup
= new ConfigGroup(NULL
, "", this);
305 // it's not an error if (one of the) file(s) doesn't exist
307 // parse the global file
308 if ( !m_strGlobalFile
.IsEmpty() && wxFile::Exists(m_strGlobalFile
) ) {
309 wxTextFile
fileGlobal(m_strGlobalFile
);
311 if ( fileGlobal
.Open() ) {
312 Parse(fileGlobal
, FALSE
/* global */);
316 wxLogWarning(_("can't open global configuration file '%s'."),
317 m_strGlobalFile
.c_str());
320 // parse the local file
321 if ( !m_strLocalFile
.IsEmpty() && wxFile::Exists(m_strLocalFile
) ) {
322 wxTextFile
fileLocal(m_strLocalFile
);
323 if ( fileLocal
.Open() ) {
324 Parse(fileLocal
, TRUE
/* local */);
328 wxLogWarning(_("can't open user configuration file '%s'."),
329 m_strLocalFile
.c_str());
333 // constructor supports creation of wxFileConfig objects of any type
334 wxFileConfig::wxFileConfig(const wxString
& appName
, const wxString
& vendorName
,
335 const wxString
& strLocal
, const wxString
& strGlobal
,
337 : wxConfigBase(::GetAppName(appName
), vendorName
,
340 m_strLocalFile(strLocal
), m_strGlobalFile(strGlobal
)
342 // Make up names for files if empty
343 if ( m_strLocalFile
.IsEmpty() && (style
& wxCONFIG_USE_LOCAL_FILE
) )
345 m_strLocalFile
= GetLocalFileName(GetAppName());
348 if ( m_strGlobalFile
.IsEmpty() && (style
& wxCONFIG_USE_GLOBAL_FILE
) )
350 m_strGlobalFile
= GetGlobalFileName(GetAppName());
353 // Check if styles are not supplied, but filenames are, in which case
354 // add the correct styles.
355 if ( !m_strLocalFile
.IsEmpty() )
356 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
358 if ( !m_strGlobalFile
.IsEmpty() )
359 SetStyle(GetStyle() | wxCONFIG_USE_GLOBAL_FILE
);
361 // if the path is not absolute, prepend the standard directory to it
362 // UNLESS wxCONFIG_USE_RELATIVE_PATH style is set
363 if ( !(style
& wxCONFIG_USE_RELATIVE_PATH
) )
365 if ( !m_strLocalFile
.IsEmpty() && !wxIsAbsolutePath(m_strLocalFile
) )
367 wxString strLocal
= m_strLocalFile
;
368 m_strLocalFile
= GetLocalDir();
369 m_strLocalFile
<< strLocal
;
372 if ( !m_strGlobalFile
.IsEmpty() && !wxIsAbsolutePath(m_strGlobalFile
) )
374 wxString strGlobal
= m_strGlobalFile
;
375 m_strGlobalFile
= GetGlobalDir();
376 m_strGlobalFile
<< strGlobal
;
385 void wxFileConfig::CleanUp()
389 LineList
*pCur
= m_linesHead
;
390 while ( pCur
!= NULL
) {
391 LineList
*pNext
= pCur
->Next();
397 wxFileConfig::~wxFileConfig()
404 // ----------------------------------------------------------------------------
405 // parse a config file
406 // ----------------------------------------------------------------------------
408 void wxFileConfig::Parse(wxTextFile
& file
, bool bLocal
)
410 const wxChar
*pStart
;
414 size_t nLineCount
= file
.GetLineCount();
415 for ( size_t n
= 0; n
< nLineCount
; n
++ ) {
418 // add the line to linked list
420 LineListAppend(strLine
);
422 // skip leading spaces
423 for ( pStart
= strLine
; wxIsspace(*pStart
); pStart
++ )
426 // skip blank/comment lines
427 if ( *pStart
== wxT('\0')|| *pStart
== wxT(';') || *pStart
== wxT('#') )
430 if ( *pStart
== wxT('[') ) { // a new group
433 while ( *++pEnd
!= wxT(']') ) {
434 if ( *pEnd
== wxT('\\') ) {
435 // the next char is escaped, so skip it even if it is ']'
439 if ( *pEnd
== wxT('\n') || *pEnd
== wxT('\0') ) {
440 // we reached the end of line, break out of the loop
445 if ( *pEnd
!= wxT(']') ) {
446 wxLogError(_("file '%s': unexpected character %c at line %d."),
447 file
.GetName(), *pEnd
, n
+ 1);
448 continue; // skip this line
451 // group name here is always considered as abs path
454 strGroup
<< wxCONFIG_PATH_SEPARATOR
455 << FilterInEntryName(wxString(pStart
, pEnd
- pStart
));
457 // will create it if doesn't yet exist
461 m_pCurrentGroup
->SetLine(m_linesTail
);
463 // check that there is nothing except comments left on this line
465 while ( *++pEnd
!= wxT('\0') && bCont
) {
474 // ignore whitespace ('\n' impossible here)
478 wxLogWarning(_("file '%s', line %d: '%s' ignored after group header."),
479 file
.GetName(), n
+ 1, pEnd
);
485 const wxChar
*pEnd
= pStart
;
486 while ( *pEnd
&& *pEnd
!= wxT('=') && !wxIsspace(*pEnd
) ) {
487 if ( *pEnd
== wxT('\\') ) {
488 // next character may be space or not - still take it because it's
489 // quoted (unless there is nothing)
492 // the error message will be given below anyhow
500 wxString
strKey(FilterInEntryName(wxString(pStart
, pEnd
)));
503 while ( wxIsspace(*pEnd
) )
506 if ( *pEnd
++ != wxT('=') ) {
507 wxLogError(_("file '%s', line %d: '=' expected."),
508 file
.GetName(), n
+ 1);
511 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strKey
);
513 if ( pEntry
== NULL
) {
515 pEntry
= m_pCurrentGroup
->AddEntry(strKey
, n
);
518 pEntry
->SetLine(m_linesTail
);
521 if ( bLocal
&& pEntry
->IsImmutable() ) {
522 // immutable keys can't be changed by user
523 wxLogWarning(_("file '%s', line %d: value for immutable key '%s' ignored."),
524 file
.GetName(), n
+ 1, strKey
.c_str());
527 // the condition below catches the cases (a) and (b) but not (c):
528 // (a) global key found second time in global file
529 // (b) key found second (or more) time in local file
530 // (c) key from global file now found in local one
531 // which is exactly what we want.
532 else if ( !bLocal
|| pEntry
->IsLocal() ) {
533 wxLogWarning(_("file '%s', line %d: key '%s' was first found at line %d."),
534 file
.GetName(), n
+ 1, strKey
.c_str(), pEntry
->Line());
537 pEntry
->SetLine(m_linesTail
);
542 while ( wxIsspace(*pEnd
) )
545 pEntry
->SetValue(FilterInValue(pEnd
), FALSE
/* read from file */);
551 // ----------------------------------------------------------------------------
553 // ----------------------------------------------------------------------------
555 void wxFileConfig::SetRootPath()
558 m_pCurrentGroup
= m_pRootGroup
;
561 void wxFileConfig::SetPath(const wxString
& strPath
)
563 wxArrayString aParts
;
565 if ( strPath
.IsEmpty() ) {
570 if ( strPath
[0] == wxCONFIG_PATH_SEPARATOR
) {
572 wxSplitPath(aParts
, strPath
);
575 // relative path, combine with current one
576 wxString strFullPath
= m_strPath
;
577 strFullPath
<< wxCONFIG_PATH_SEPARATOR
<< strPath
;
578 wxSplitPath(aParts
, strFullPath
);
581 // change current group
583 m_pCurrentGroup
= m_pRootGroup
;
584 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
585 ConfigGroup
*pNextGroup
= m_pCurrentGroup
->FindSubgroup(aParts
[n
]);
586 if ( pNextGroup
== NULL
)
587 pNextGroup
= m_pCurrentGroup
->AddSubgroup(aParts
[n
]);
588 m_pCurrentGroup
= pNextGroup
;
591 // recombine path parts in one variable
593 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
594 m_strPath
<< wxCONFIG_PATH_SEPARATOR
<< aParts
[n
];
598 // ----------------------------------------------------------------------------
600 // ----------------------------------------------------------------------------
602 bool wxFileConfig::GetFirstGroup(wxString
& str
, long& lIndex
) const
605 return GetNextGroup(str
, lIndex
);
608 bool wxFileConfig::GetNextGroup (wxString
& str
, long& lIndex
) const
610 if ( size_t(lIndex
) < m_pCurrentGroup
->Groups().Count() ) {
611 str
= m_pCurrentGroup
->Groups()[(size_t)lIndex
++]->Name();
618 bool wxFileConfig::GetFirstEntry(wxString
& str
, long& lIndex
) const
621 return GetNextEntry(str
, lIndex
);
624 bool wxFileConfig::GetNextEntry (wxString
& str
, long& lIndex
) const
626 if ( size_t(lIndex
) < m_pCurrentGroup
->Entries().Count() ) {
627 str
= m_pCurrentGroup
->Entries()[(size_t)lIndex
++]->Name();
634 size_t wxFileConfig::GetNumberOfEntries(bool bRecursive
) const
636 size_t n
= m_pCurrentGroup
->Entries().Count();
638 ConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
639 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
640 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
641 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
642 n
+= GetNumberOfEntries(TRUE
);
643 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
650 size_t wxFileConfig::GetNumberOfGroups(bool bRecursive
) const
652 size_t n
= m_pCurrentGroup
->Groups().Count();
654 ConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
655 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
656 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
657 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
658 n
+= GetNumberOfGroups(TRUE
);
659 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
666 // ----------------------------------------------------------------------------
667 // tests for existence
668 // ----------------------------------------------------------------------------
670 bool wxFileConfig::HasGroup(const wxString
& strName
) const
672 wxConfigPathChanger
path(this, strName
);
674 ConfigGroup
*pGroup
= m_pCurrentGroup
->FindSubgroup(path
.Name());
675 return pGroup
!= NULL
;
678 bool wxFileConfig::HasEntry(const wxString
& strName
) const
680 wxConfigPathChanger
path(this, strName
);
682 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
683 return pEntry
!= NULL
;
686 // ----------------------------------------------------------------------------
688 // ----------------------------------------------------------------------------
690 bool wxFileConfig::Read(const wxString
& key
,
691 wxString
* pStr
) const
693 wxConfigPathChanger
path(this, key
);
695 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
696 if (pEntry
== NULL
) {
700 *pStr
= ExpandEnvVars(pEntry
->Value());
704 bool wxFileConfig::Read(const wxString
& key
,
705 wxString
* pStr
, const wxString
& defVal
) const
707 wxConfigPathChanger
path(this, key
);
709 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
711 if (pEntry
== NULL
) {
712 if( IsRecordingDefaults() )
713 ((wxFileConfig
*)this)->Write(key
,defVal
);
714 *pStr
= ExpandEnvVars(defVal
);
718 *pStr
= ExpandEnvVars(pEntry
->Value());
725 bool wxFileConfig::Read(const wxString
& key
, long *pl
) const
728 if ( !Read(key
, & str
) )
737 bool wxFileConfig::Write(const wxString
& key
, const wxString
& szValue
)
739 wxConfigPathChanger
path(this, key
);
741 wxString strName
= path
.Name();
742 if ( strName
.IsEmpty() ) {
743 // setting the value of a group is an error
744 wxASSERT_MSG( wxIsEmpty(szValue
), wxT("can't set value of a group!") );
746 // ... except if it's empty in which case it's a way to force it's creation
747 m_pCurrentGroup
->SetDirty();
749 // this will add a line for this group if it didn't have it before
750 (void)m_pCurrentGroup
->GetGroupLine();
755 // check that the name is reasonable
756 if ( strName
[0u] == wxCONFIG_IMMUTABLE_PREFIX
) {
757 wxLogError(_("Config entry name cannot start with '%c'."),
758 wxCONFIG_IMMUTABLE_PREFIX
);
762 ConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strName
);
763 if ( pEntry
== NULL
)
764 pEntry
= m_pCurrentGroup
->AddEntry(strName
);
766 pEntry
->SetValue(szValue
);
772 bool wxFileConfig::Write(const wxString
& key
, long lValue
)
774 // ltoa() is not ANSI :-(
776 buf
.Printf(wxT("%ld"), lValue
);
777 return Write(key
, buf
);
780 bool wxFileConfig::Flush(bool /* bCurrentOnly */)
782 if ( LineListIsEmpty() || !m_pRootGroup
->IsDirty() || !m_strLocalFile
)
786 // set the umask if needed
790 umaskOld
= umask((mode_t
)m_umask
);
794 wxTempFile
file(m_strLocalFile
);
796 if ( !file
.IsOpened() ) {
797 wxLogError(_("can't open user configuration file."));
801 // write all strings to file
802 for ( LineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() ) {
803 if ( !file
.Write(p
->Text() + wxTextFile::GetEOL()) ) {
804 wxLogError(_("can't write user configuration file."));
809 bool ret
= file
.Commit();
816 wxUnixFilename2FSSpec( m_strLocalFile
, &spec
) ;
818 if ( FSpGetFInfo( &spec
, &finfo
) == noErr
)
820 finfo
.fdType
= 'TEXT' ;
821 finfo
.fdCreator
= 'ttxt' ;
822 FSpSetFInfo( &spec
, &finfo
) ;
828 // restore the old umask if we changed it
831 (void)umask(umaskOld
);
838 // ----------------------------------------------------------------------------
839 // renaming groups/entries
840 // ----------------------------------------------------------------------------
842 bool wxFileConfig::RenameEntry(const wxString
& oldName
,
843 const wxString
& newName
)
845 // check that the entry exists
846 ConfigEntry
*oldEntry
= m_pCurrentGroup
->FindEntry(oldName
);
850 // check that the new entry doesn't already exist
851 if ( m_pCurrentGroup
->FindEntry(newName
) )
854 // delete the old entry, create the new one
855 wxString value
= oldEntry
->Value();
856 if ( !m_pCurrentGroup
->DeleteEntry(oldName
) )
859 ConfigEntry
*newEntry
= m_pCurrentGroup
->AddEntry(newName
);
860 newEntry
->SetValue(value
);
865 bool wxFileConfig::RenameGroup(const wxString
& oldName
,
866 const wxString
& newName
)
868 // check that the group exists
869 ConfigGroup
*group
= m_pCurrentGroup
->FindSubgroup(oldName
);
873 // check that the new group doesn't already exist
874 if ( m_pCurrentGroup
->FindSubgroup(newName
) )
877 group
->Rename(newName
);
882 // ----------------------------------------------------------------------------
883 // delete groups/entries
884 // ----------------------------------------------------------------------------
886 bool wxFileConfig::DeleteEntry(const wxString
& key
, bool bGroupIfEmptyAlso
)
888 wxConfigPathChanger
path(this, key
);
890 if ( !m_pCurrentGroup
->DeleteEntry(path
.Name()) )
893 if ( bGroupIfEmptyAlso
&& m_pCurrentGroup
->IsEmpty() ) {
894 if ( m_pCurrentGroup
!= m_pRootGroup
) {
895 ConfigGroup
*pGroup
= m_pCurrentGroup
;
896 SetPath(wxT("..")); // changes m_pCurrentGroup!
897 m_pCurrentGroup
->DeleteSubgroupByName(pGroup
->Name());
899 //else: never delete the root group
905 bool wxFileConfig::DeleteGroup(const wxString
& key
)
907 wxConfigPathChanger
path(this, key
);
909 return m_pCurrentGroup
->DeleteSubgroupByName(path
.Name());
912 bool wxFileConfig::DeleteAll()
916 if ( wxRemove(m_strLocalFile
) == -1 )
917 wxLogSysError(_("can't delete user configuration file '%s'"), m_strLocalFile
.c_str());
919 m_strLocalFile
= m_strGlobalFile
= wxT("");
925 // ----------------------------------------------------------------------------
926 // linked list functions
927 // ----------------------------------------------------------------------------
929 // append a new line to the end of the list
930 LineList
*wxFileConfig::LineListAppend(const wxString
& str
)
932 LineList
*pLine
= new LineList(str
);
934 if ( m_linesTail
== NULL
) {
940 m_linesTail
->SetNext(pLine
);
941 pLine
->SetPrev(m_linesTail
);
948 // insert a new line after the given one or in the very beginning if !pLine
949 LineList
*wxFileConfig::LineListInsert(const wxString
& str
,
952 if ( pLine
== m_linesTail
)
953 return LineListAppend(str
);
955 LineList
*pNewLine
= new LineList(str
);
956 if ( pLine
== NULL
) {
957 // prepend to the list
958 pNewLine
->SetNext(m_linesHead
);
959 m_linesHead
->SetPrev(pNewLine
);
960 m_linesHead
= pNewLine
;
963 // insert before pLine
964 LineList
*pNext
= pLine
->Next();
965 pNewLine
->SetNext(pNext
);
966 pNewLine
->SetPrev(pLine
);
967 pNext
->SetPrev(pNewLine
);
968 pLine
->SetNext(pNewLine
);
974 void wxFileConfig::LineListRemove(LineList
*pLine
)
976 LineList
*pPrev
= pLine
->Prev(),
977 *pNext
= pLine
->Next();
983 pPrev
->SetNext(pNext
);
989 pNext
->SetPrev(pPrev
);
994 bool wxFileConfig::LineListIsEmpty()
996 return m_linesHead
== NULL
;
999 // ============================================================================
1000 // wxFileConfig::ConfigGroup
1001 // ============================================================================
1003 // ----------------------------------------------------------------------------
1005 // ----------------------------------------------------------------------------
1008 ConfigGroup::ConfigGroup(ConfigGroup
*pParent
,
1009 const wxString
& strName
,
1010 wxFileConfig
*pConfig
)
1011 : m_aEntries(CompareEntries
),
1012 m_aSubgroups(CompareGroups
),
1015 m_pConfig
= pConfig
;
1016 m_pParent
= pParent
;
1020 m_pLastEntry
= NULL
;
1021 m_pLastGroup
= NULL
;
1024 // dtor deletes all children
1025 ConfigGroup::~ConfigGroup()
1028 size_t n
, nCount
= m_aEntries
.Count();
1029 for ( n
= 0; n
< nCount
; n
++ )
1030 delete m_aEntries
[n
];
1033 nCount
= m_aSubgroups
.Count();
1034 for ( n
= 0; n
< nCount
; n
++ )
1035 delete m_aSubgroups
[n
];
1038 // ----------------------------------------------------------------------------
1040 // ----------------------------------------------------------------------------
1042 void ConfigGroup::SetLine(LineList
*pLine
)
1044 wxASSERT( m_pLine
== NULL
); // shouldn't be called twice
1050 This is a bit complicated, so let me explain it in details. All lines that
1051 were read from the local file (the only one we will ever modify) are stored
1052 in a (doubly) linked list. Our problem is to know at which position in this
1053 list should we insert the new entries/subgroups. To solve it we keep three
1054 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1056 m_pLine points to the line containing "[group_name]"
1057 m_pLastEntry points to the last entry of this group in the local file.
1058 m_pLastGroup subgroup
1060 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1061 from the local file, the corresponding variable is set. However, if the group
1062 was read from the global file and then modified or created by the application
1063 these variables are still NULL and we need to create the corresponding lines.
1064 See the following functions (and comments preceding them) for the details of
1067 Also, when our last entry/group are deleted we need to find the new last
1068 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1069 of lines until it either founds an entry/subgroup (and this is the new last
1070 element) or the m_pLine of the group, in which case there are no more entries
1071 (or subgroups) left and m_pLast<element> becomes NULL.
1073 NB: This last problem could be avoided for entries if we added new entries
1074 immediately after m_pLine, but in this case the entries would appear
1075 backwards in the config file (OTOH, it's not that important) and as we
1076 would still need to do it for the subgroups the code wouldn't have been
1077 significantly less complicated.
1080 // Return the line which contains "[our name]". If we're still not in the list,
1081 // add our line to it immediately after the last line of our parent group if we
1082 // have it or in the very beginning if we're the root group.
1083 LineList
*ConfigGroup::GetGroupLine()
1085 if ( m_pLine
== NULL
) {
1086 ConfigGroup
*pParent
= Parent();
1088 // this group wasn't present in local config file, add it now
1089 if ( pParent
!= NULL
) {
1090 wxString strFullName
;
1091 strFullName
<< wxT("[")
1093 << FilterOutEntryName(GetFullName().c_str() + 1)
1095 m_pLine
= m_pConfig
->LineListInsert(strFullName
,
1096 pParent
->GetLastGroupLine());
1097 pParent
->SetLastGroup(this); // we're surely after all the others
1100 // we return NULL, so that LineListInsert() will insert us in the
1108 // Return the last line belonging to the subgroups of this group (after which
1109 // we can add a new subgroup), if we don't have any subgroups or entries our
1110 // last line is the group line (m_pLine) itself.
1111 LineList
*ConfigGroup::GetLastGroupLine()
1113 // if we have any subgroups, our last line is the last line of the last
1115 if ( m_pLastGroup
!= NULL
) {
1116 LineList
*pLine
= m_pLastGroup
->GetLastGroupLine();
1118 wxASSERT( pLine
!= NULL
); // last group must have !NULL associated line
1122 // no subgroups, so the last line is the line of thelast entry (if any)
1123 return GetLastEntryLine();
1126 // return the last line belonging to the entries of this group (after which
1127 // we can add a new entry), if we don't have any entries we will add the new
1128 // one immediately after the group line itself.
1129 LineList
*ConfigGroup::GetLastEntryLine()
1131 if ( m_pLastEntry
!= NULL
) {
1132 LineList
*pLine
= m_pLastEntry
->GetLine();
1134 wxASSERT( pLine
!= NULL
); // last entry must have !NULL associated line
1138 // no entries: insert after the group header
1139 return GetGroupLine();
1142 // ----------------------------------------------------------------------------
1144 // ----------------------------------------------------------------------------
1146 void ConfigGroup::Rename(const wxString
& newName
)
1148 m_strName
= newName
;
1150 LineList
*line
= GetGroupLine();
1151 wxString strFullName
;
1152 strFullName
<< wxT("[") << (GetFullName().c_str() + 1) << wxT("]"); // +1: no '/'
1153 line
->SetText(strFullName
);
1158 wxString
ConfigGroup::GetFullName() const
1161 return Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR
+ Name();
1166 // ----------------------------------------------------------------------------
1168 // ----------------------------------------------------------------------------
1170 // use binary search because the array is sorted
1172 ConfigGroup::FindEntry(const wxChar
*szName
) const
1176 hi
= m_aEntries
.Count();
1178 ConfigEntry
*pEntry
;
1182 pEntry
= m_aEntries
[i
];
1184 #if wxCONFIG_CASE_SENSITIVE
1185 res
= wxStrcmp(pEntry
->Name(), szName
);
1187 res
= wxStricmp(pEntry
->Name(), szName
);
1202 ConfigGroup::FindSubgroup(const wxChar
*szName
) const
1206 hi
= m_aSubgroups
.Count();
1208 ConfigGroup
*pGroup
;
1212 pGroup
= m_aSubgroups
[i
];
1214 #if wxCONFIG_CASE_SENSITIVE
1215 res
= wxStrcmp(pGroup
->Name(), szName
);
1217 res
= wxStricmp(pGroup
->Name(), szName
);
1231 // ----------------------------------------------------------------------------
1232 // create a new item
1233 // ----------------------------------------------------------------------------
1235 // create a new entry and add it to the current group
1237 ConfigGroup::AddEntry(const wxString
& strName
, int nLine
)
1239 wxASSERT( FindEntry(strName
) == NULL
);
1241 ConfigEntry
*pEntry
= new ConfigEntry(this, strName
, nLine
);
1242 m_aEntries
.Add(pEntry
);
1247 // create a new group and add it to the current group
1249 ConfigGroup::AddSubgroup(const wxString
& strName
)
1251 wxASSERT( FindSubgroup(strName
) == NULL
);
1253 ConfigGroup
*pGroup
= new ConfigGroup(this, strName
, m_pConfig
);
1254 m_aSubgroups
.Add(pGroup
);
1259 // ----------------------------------------------------------------------------
1261 // ----------------------------------------------------------------------------
1264 The delete operations are _very_ slow if we delete the last item of this
1265 group (see comments before GetXXXLineXXX functions for more details),
1266 so it's much better to start with the first entry/group if we want to
1267 delete several of them.
1270 bool ConfigGroup::DeleteSubgroupByName(const wxChar
*szName
)
1272 return DeleteSubgroup(FindSubgroup(szName
));
1275 // doesn't delete the subgroup itself, but does remove references to it from
1276 // all other data structures (and normally the returned pointer should be
1277 // deleted a.s.a.p. because there is nothing much to be done with it anyhow)
1278 bool ConfigGroup::DeleteSubgroup(ConfigGroup
*pGroup
)
1280 wxCHECK( pGroup
!= NULL
, FALSE
); // deleting non existing group?
1282 // delete all entries
1283 size_t nCount
= pGroup
->m_aEntries
.Count();
1284 for ( size_t nEntry
= 0; nEntry
< nCount
; nEntry
++ ) {
1285 LineList
*pLine
= pGroup
->m_aEntries
[nEntry
]->GetLine();
1286 if ( pLine
!= NULL
)
1287 m_pConfig
->LineListRemove(pLine
);
1290 // and subgroups of this sungroup
1291 nCount
= pGroup
->m_aSubgroups
.Count();
1292 for ( size_t nGroup
= 0; nGroup
< nCount
; nGroup
++ ) {
1293 pGroup
->DeleteSubgroup(pGroup
->m_aSubgroups
[0]);
1296 LineList
*pLine
= pGroup
->m_pLine
;
1297 if ( pLine
!= NULL
) {
1298 // notice that we may do this test inside the previous "if" because the
1299 // last entry's line is surely !NULL
1300 if ( pGroup
== m_pLastGroup
) {
1301 // our last entry is being deleted - find the last one which stays
1302 wxASSERT( m_pLine
!= NULL
); // we have a subgroup with !NULL pLine...
1304 // go back until we find a subgroup or reach the group's line
1305 ConfigGroup
*pNewLast
= NULL
;
1306 size_t n
, nSubgroups
= m_aSubgroups
.Count();
1308 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1309 // is it our subgroup?
1310 for ( n
= 0; (pNewLast
== NULL
) && (n
< nSubgroups
); n
++ ) {
1311 // do _not_ call GetGroupLine! we don't want to add it to the local
1312 // file if it's not already there
1313 if ( m_aSubgroups
[n
]->m_pLine
== m_pLine
)
1314 pNewLast
= m_aSubgroups
[n
];
1317 if ( pNewLast
!= NULL
) // found?
1321 if ( pl
== m_pLine
) {
1322 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1324 // we've reached the group line without finding any subgroups
1325 m_pLastGroup
= NULL
;
1328 m_pLastGroup
= pNewLast
;
1331 m_pConfig
->LineListRemove(pLine
);
1336 m_aSubgroups
.Remove(pGroup
);
1342 bool ConfigGroup::DeleteEntry(const wxChar
*szName
)
1344 ConfigEntry
*pEntry
= FindEntry(szName
);
1345 wxCHECK( pEntry
!= NULL
, FALSE
); // deleting non existing item?
1347 LineList
*pLine
= pEntry
->GetLine();
1348 if ( pLine
!= NULL
) {
1349 // notice that we may do this test inside the previous "if" because the
1350 // last entry's line is surely !NULL
1351 if ( pEntry
== m_pLastEntry
) {
1352 // our last entry is being deleted - find the last one which stays
1353 wxASSERT( m_pLine
!= NULL
); // if we have an entry with !NULL pLine...
1355 // go back until we find another entry or reach the group's line
1356 ConfigEntry
*pNewLast
= NULL
;
1357 size_t n
, nEntries
= m_aEntries
.Count();
1359 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1360 // is it our subgroup?
1361 for ( n
= 0; (pNewLast
== NULL
) && (n
< nEntries
); n
++ ) {
1362 if ( m_aEntries
[n
]->GetLine() == m_pLine
)
1363 pNewLast
= m_aEntries
[n
];
1366 if ( pNewLast
!= NULL
) // found?
1370 if ( pl
== m_pLine
) {
1371 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1373 // we've reached the group line without finding any subgroups
1374 m_pLastEntry
= NULL
;
1377 m_pLastEntry
= pNewLast
;
1380 m_pConfig
->LineListRemove(pLine
);
1383 // we must be written back for the changes to be saved
1386 m_aEntries
.Remove(pEntry
);
1392 // ----------------------------------------------------------------------------
1394 // ----------------------------------------------------------------------------
1395 void ConfigGroup::SetDirty()
1398 if ( Parent() != NULL
) // propagate upwards
1399 Parent()->SetDirty();
1402 // ============================================================================
1403 // wxFileConfig::ConfigEntry
1404 // ============================================================================
1406 // ----------------------------------------------------------------------------
1408 // ----------------------------------------------------------------------------
1409 ConfigEntry::ConfigEntry(ConfigGroup
*pParent
,
1410 const wxString
& strName
,
1412 : m_strName(strName
)
1414 wxASSERT( !strName
.IsEmpty() );
1416 m_pParent
= pParent
;
1422 m_bImmutable
= strName
[0] == wxCONFIG_IMMUTABLE_PREFIX
;
1424 m_strName
.erase(0, 1); // remove first character
1427 // ----------------------------------------------------------------------------
1429 // ----------------------------------------------------------------------------
1431 void ConfigEntry::SetLine(LineList
*pLine
)
1433 if ( m_pLine
!= NULL
) {
1434 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1435 Name().c_str(), m_pParent
->GetFullName().c_str());
1439 Group()->SetLastEntry(this);
1442 // second parameter is FALSE if we read the value from file and prevents the
1443 // entry from being marked as 'dirty'
1444 void ConfigEntry::SetValue(const wxString
& strValue
, bool bUser
)
1446 if ( bUser
&& IsImmutable() ) {
1447 wxLogWarning(_("attempt to change immutable key '%s' ignored."),
1452 // do nothing if it's the same value
1453 if ( strValue
== m_strValue
)
1456 m_strValue
= strValue
;
1459 wxString strVal
= FilterOutValue(strValue
);
1461 strLine
<< FilterOutEntryName(m_strName
) << wxT('=') << strVal
;
1463 if ( m_pLine
!= NULL
) {
1464 // entry was read from the local config file, just modify the line
1465 m_pLine
->SetText(strLine
);
1468 // add a new line to the file
1469 wxASSERT( m_nLine
== wxNOT_FOUND
); // consistency check
1471 m_pLine
= Group()->Config()->LineListInsert(strLine
,
1472 Group()->GetLastEntryLine());
1473 Group()->SetLastEntry(this);
1480 void ConfigEntry::SetDirty()
1483 Group()->SetDirty();
1486 // ============================================================================
1488 // ============================================================================
1490 // ----------------------------------------------------------------------------
1491 // compare functions for array sorting
1492 // ----------------------------------------------------------------------------
1494 int CompareEntries(ConfigEntry
*p1
,
1497 #if wxCONFIG_CASE_SENSITIVE
1498 return wxStrcmp(p1
->Name(), p2
->Name());
1500 return wxStricmp(p1
->Name(), p2
->Name());
1504 int CompareGroups(ConfigGroup
*p1
,
1507 #if wxCONFIG_CASE_SENSITIVE
1508 return wxStrcmp(p1
->Name(), p2
->Name());
1510 return wxStricmp(p1
->Name(), p2
->Name());
1514 // ----------------------------------------------------------------------------
1516 // ----------------------------------------------------------------------------
1518 // undo FilterOutValue
1519 static wxString
FilterInValue(const wxString
& str
)
1522 strResult
.Alloc(str
.Len());
1524 bool bQuoted
= !str
.IsEmpty() && str
[0] == '"';
1526 for ( size_t n
= bQuoted
? 1 : 0; n
< str
.Len(); n
++ ) {
1527 if ( str
[n
] == wxT('\\') ) {
1528 switch ( str
[++n
] ) {
1530 strResult
+= wxT('\n');
1534 strResult
+= wxT('\r');
1538 strResult
+= wxT('\t');
1542 strResult
+= wxT('\\');
1546 strResult
+= wxT('"');
1551 if ( str
[n
] != wxT('"') || !bQuoted
)
1552 strResult
+= str
[n
];
1553 else if ( n
!= str
.Len() - 1 ) {
1554 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1557 //else: it's the last quote of a quoted string, ok
1564 // quote the string before writing it to file
1565 static wxString
FilterOutValue(const wxString
& str
)
1571 strResult
.Alloc(str
.Len());
1573 // quoting is necessary to preserve spaces in the beginning of the string
1574 bool bQuote
= wxIsspace(str
[0]) || str
[0] == wxT('"');
1577 strResult
+= wxT('"');
1580 for ( size_t n
= 0; n
< str
.Len(); n
++ ) {
1603 //else: fall through
1606 strResult
+= str
[n
];
1607 continue; // nothing special to do
1610 // we get here only for special characters
1611 strResult
<< wxT('\\') << c
;
1615 strResult
+= wxT('"');
1620 // undo FilterOutEntryName
1621 static wxString
FilterInEntryName(const wxString
& str
)
1624 strResult
.Alloc(str
.Len());
1626 for ( const wxChar
*pc
= str
.c_str(); *pc
!= '\0'; pc
++ ) {
1627 if ( *pc
== wxT('\\') )
1636 // sanitize entry or group name: insert '\\' before any special characters
1637 static wxString
FilterOutEntryName(const wxString
& str
)
1640 strResult
.Alloc(str
.Len());
1642 for ( const wxChar
*pc
= str
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
1645 // we explicitly allow some of "safe" chars and 8bit ASCII characters
1646 // which will probably never have special meaning
1647 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
1648 // should *not* be quoted
1649 if ( !wxIsalnum(c
) && !wxStrchr(wxT("@_/-!.*%"), c
) && ((c
& 0x80) == 0) )
1650 strResult
+= wxT('\\');
1658 // we can't put ?: in the ctor initializer list because it confuses some
1659 // broken compilers (Borland C++)
1660 static wxString
GetAppName(const wxString
& appName
)
1662 if ( !appName
&& wxTheApp
)
1663 return wxTheApp
->GetAppName();
1668 #endif // wxUSE_CONFIG