1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/fileconf.cpp
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 licence
11 ///////////////////////////////////////////////////////////////////////////////
13 // ----------------------------------------------------------------------------
15 // ----------------------------------------------------------------------------
17 // For compilers that support precompilation, includes "wx.h".
18 #include "wx/wxprec.h"
24 #if wxUSE_CONFIG && wxUSE_FILECONFIG
27 #include "wx/dynarray.h"
28 #include "wx/string.h"
32 #include "wx/utils.h" // for wxGetHomeDir
34 #include "wx/stream.h"
35 #endif // wxUSE_STREAMS
39 #include "wx/textfile.h"
40 #include "wx/memtext.h"
41 #include "wx/config.h"
42 #include "wx/fileconf.h"
43 #include "wx/filefn.h"
45 #if defined(__WXMAC__)
46 #include "wx/mac/private.h" // includes mac headers
47 #include "wx/filename.h" // for MacSetTypeAndCreator
50 #if defined(__WXMSW__)
51 #include "wx/msw/private.h"
61 // ----------------------------------------------------------------------------
63 // ----------------------------------------------------------------------------
64 #define CONST_CAST ((wxFileConfig *)this)->
66 // ----------------------------------------------------------------------------
68 // ----------------------------------------------------------------------------
74 #define FILECONF_TRACE_MASK _T("fileconf")
76 // ----------------------------------------------------------------------------
77 // global functions declarations
78 // ----------------------------------------------------------------------------
80 // compare functions for sorting the arrays
81 static int LINKAGEMODE
CompareEntries(wxFileConfigEntry
*p1
, wxFileConfigEntry
*p2
);
82 static int LINKAGEMODE
CompareGroups(wxFileConfigGroup
*p1
, wxFileConfigGroup
*p2
);
85 static wxString
FilterInValue(const wxString
& str
);
86 static wxString
FilterOutValue(const wxString
& str
);
88 static wxString
FilterInEntryName(const wxString
& str
);
89 static wxString
FilterOutEntryName(const wxString
& str
);
91 // get the name to use in wxFileConfig ctor
92 static wxString
GetAppName(const wxString
& appname
);
94 // ============================================================================
96 // ============================================================================
98 // ----------------------------------------------------------------------------
99 // "template" array types
100 // ----------------------------------------------------------------------------
102 #ifdef WXMAKINGDLL_BASE
103 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(wxFileConfigEntry
*, ArrayEntries
,
105 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(wxFileConfigGroup
*, ArrayGroups
,
108 WX_DEFINE_SORTED_ARRAY(wxFileConfigEntry
*, ArrayEntries
);
109 WX_DEFINE_SORTED_ARRAY(wxFileConfigGroup
*, ArrayGroups
);
112 // ----------------------------------------------------------------------------
113 // wxFileConfigLineList
114 // ----------------------------------------------------------------------------
116 // we store all lines of the local config file as a linked list in memory
117 class wxFileConfigLineList
120 void SetNext(wxFileConfigLineList
*pNext
) { m_pNext
= pNext
; }
121 void SetPrev(wxFileConfigLineList
*pPrev
) { m_pPrev
= pPrev
; }
124 wxFileConfigLineList(const wxString
& str
,
125 wxFileConfigLineList
*pNext
= NULL
) : m_strLine(str
)
126 { SetNext(pNext
); SetPrev(NULL
); }
128 // next/prev nodes in the linked list
129 wxFileConfigLineList
*Next() const { return m_pNext
; }
130 wxFileConfigLineList
*Prev() const { return m_pPrev
; }
132 // get/change lines text
133 void SetText(const wxString
& str
) { m_strLine
= str
; }
134 const wxString
& Text() const { return m_strLine
; }
137 wxString m_strLine
; // line contents
138 wxFileConfigLineList
*m_pNext
, // next node
139 *m_pPrev
; // previous one
141 DECLARE_NO_COPY_CLASS(wxFileConfigLineList
)
144 // ----------------------------------------------------------------------------
145 // wxFileConfigEntry: a name/value pair
146 // ----------------------------------------------------------------------------
148 class wxFileConfigEntry
151 wxFileConfigGroup
*m_pParent
; // group that contains us
153 wxString m_strName
, // entry name
155 bool m_bImmutable
:1, // can be overriden locally?
156 m_bHasValue
:1; // set after first call to SetValue()
158 int m_nLine
; // used if m_pLine == NULL only
160 // pointer to our line in the linked list or NULL if it was found in global
161 // file (which we don't modify)
162 wxFileConfigLineList
*m_pLine
;
165 wxFileConfigEntry(wxFileConfigGroup
*pParent
,
166 const wxString
& strName
, int nLine
);
169 const wxString
& Name() const { return m_strName
; }
170 const wxString
& Value() const { return m_strValue
; }
171 wxFileConfigGroup
*Group() const { return m_pParent
; }
172 bool IsImmutable() const { return m_bImmutable
; }
173 bool IsLocal() const { return m_pLine
!= 0; }
174 int Line() const { return m_nLine
; }
175 wxFileConfigLineList
*
176 GetLine() const { return m_pLine
; }
178 // modify entry attributes
179 void SetValue(const wxString
& strValue
, bool bUser
= true);
180 void SetLine(wxFileConfigLineList
*pLine
);
182 DECLARE_NO_COPY_CLASS(wxFileConfigEntry
)
185 // ----------------------------------------------------------------------------
186 // wxFileConfigGroup: container of entries and other groups
187 // ----------------------------------------------------------------------------
189 class wxFileConfigGroup
192 wxFileConfig
*m_pConfig
; // config object we belong to
193 wxFileConfigGroup
*m_pParent
; // parent group (NULL for root group)
194 ArrayEntries m_aEntries
; // entries in this group
195 ArrayGroups m_aSubgroups
; // subgroups
196 wxString m_strName
; // group's name
197 wxFileConfigLineList
*m_pLine
; // pointer to our line in the linked list
198 wxFileConfigEntry
*m_pLastEntry
; // last entry/subgroup of this group in the
199 wxFileConfigGroup
*m_pLastGroup
; // local file (we insert new ones after it)
201 // DeleteSubgroupByName helper
202 bool DeleteSubgroup(wxFileConfigGroup
*pGroup
);
205 void UpdateGroupAndSubgroupsLines();
209 wxFileConfigGroup(wxFileConfigGroup
*pParent
, const wxString
& strName
, wxFileConfig
*);
211 // dtor deletes all entries and subgroups also
212 ~wxFileConfigGroup();
215 const wxString
& Name() const { return m_strName
; }
216 wxFileConfigGroup
*Parent() const { return m_pParent
; }
217 wxFileConfig
*Config() const { return m_pConfig
; }
219 const ArrayEntries
& Entries() const { return m_aEntries
; }
220 const ArrayGroups
& Groups() const { return m_aSubgroups
; }
221 bool IsEmpty() const { return Entries().IsEmpty() && Groups().IsEmpty(); }
223 // find entry/subgroup (NULL if not found)
224 wxFileConfigGroup
*FindSubgroup(const wxChar
*szName
) const;
225 wxFileConfigEntry
*FindEntry (const wxChar
*szName
) const;
227 // delete entry/subgroup, return false if doesn't exist
228 bool DeleteSubgroupByName(const wxChar
*szName
);
229 bool DeleteEntry(const wxChar
*szName
);
231 // create new entry/subgroup returning pointer to newly created element
232 wxFileConfigGroup
*AddSubgroup(const wxString
& strName
);
233 wxFileConfigEntry
*AddEntry (const wxString
& strName
, int nLine
= wxNOT_FOUND
);
235 void SetLine(wxFileConfigLineList
*pLine
);
237 // rename: no checks are done to ensure that the name is unique!
238 void Rename(const wxString
& newName
);
241 wxString
GetFullName() const;
243 // get the last line belonging to an entry/subgroup of this group
244 wxFileConfigLineList
*GetGroupLine(); // line which contains [group]
245 wxFileConfigLineList
*GetLastEntryLine(); // after which our subgroups start
246 wxFileConfigLineList
*GetLastGroupLine(); // after which the next group starts
248 // called by entries/subgroups when they're created/deleted
249 void SetLastEntry(wxFileConfigEntry
*pEntry
);
250 void SetLastGroup(wxFileConfigGroup
*pGroup
)
251 { m_pLastGroup
= pGroup
; }
253 DECLARE_NO_COPY_CLASS(wxFileConfigGroup
)
256 // ============================================================================
258 // ============================================================================
260 // ----------------------------------------------------------------------------
262 // ----------------------------------------------------------------------------
263 wxString
wxFileConfig::GetGlobalDir()
267 #ifdef __VMS__ // Note if __VMS is defined __UNIX is also defined
268 strDir
= wxT("sys$manager:");
269 #elif defined(__WXMAC__)
270 strDir
= wxMacFindFolder( (short) kOnSystemDisk
, kPreferencesFolderType
, kDontCreateFolder
) ;
271 #elif defined( __UNIX__ )
272 strDir
= wxT("/etc/");
273 #elif defined(__OS2__)
274 ULONG aulSysInfo
[QSV_MAX
] = {0};
278 rc
= DosQuerySysInfo( 1L, QSV_MAX
, (PVOID
)aulSysInfo
, sizeof(ULONG
)*QSV_MAX
);
281 drive
= aulSysInfo
[QSV_BOOT_DRIVE
- 1];
282 strDir
.Printf(wxT("%c:\\OS2\\"), 'A'+drive
-1);
284 #elif defined(__WXSTUBS__)
285 wxFAIL_MSG( wxT("TODO") );
286 #elif defined(__DOS__)
287 // There's no such thing as global cfg dir in MS-DOS, let's return
288 // current directory (FIXME_MGL?)
290 #elif defined(__WXWINCE__)
291 strDir
= wxT("\\Windows\\");
294 wxChar szWinDir
[MAX_PATH
];
295 ::GetWindowsDirectory(szWinDir
, MAX_PATH
);
299 #endif // Unix/Windows
304 wxString
wxFileConfig::GetLocalDir()
308 #if defined(__WXMAC__) || defined(__DOS__)
309 // no local dir concept on Mac OS 9 or MS-DOS
310 strDir
<< GetGlobalDir() ;
312 wxGetHomeDir(&strDir
);
316 (strDir
.Last() != wxT('/'))
318 && (strDir
.Last() != wxT(']'))
323 if (strDir
.Last() != wxT('\\'))
331 wxString
wxFileConfig::GetGlobalFileName(const wxString
& file
)
333 wxString str
= GetGlobalDir();
336 if ( wxStrchr(file
, wxT('.')) == NULL
)
337 #if defined( __WXMAC__ )
338 str
<< wxT(" Preferences") ;
339 #elif defined( __UNIX__ )
348 wxString
wxFileConfig::GetLocalFileName(const wxString
& file
)
351 // On VMS I saw the problem that the home directory was appended
352 // twice for the configuration file. Does that also happen for
354 wxString str
= wxT( '.' );
356 wxString str
= GetLocalDir();
359 #if defined( __UNIX__ ) && !defined( __VMS ) && !defined( __WXMAC__ )
365 #if defined(__WINDOWS__) || defined(__DOS__)
366 if ( wxStrchr(file
, wxT('.')) == NULL
)
371 str
<< wxT(" Preferences") ;
377 // ----------------------------------------------------------------------------
379 // ----------------------------------------------------------------------------
380 IMPLEMENT_ABSTRACT_CLASS(wxFileConfig
, wxConfigBase
)
382 void wxFileConfig::Init()
385 m_pRootGroup
= new wxFileConfigGroup(NULL
, wxEmptyString
, this);
390 // It's not an error if (one of the) file(s) doesn't exist.
392 // parse the global file
393 if ( !m_strGlobalFile
.empty() && wxFile::Exists(m_strGlobalFile
) )
395 wxTextFile
fileGlobal(m_strGlobalFile
);
397 if ( fileGlobal
.Open(*m_conv
/*ignored in ANSI build*/) )
399 Parse(fileGlobal
, false /* global */);
404 wxLogWarning(_("can't open global configuration file '%s'."), m_strGlobalFile
.c_str());
408 // parse the local file
409 if ( !m_strLocalFile
.empty() && wxFile::Exists(m_strLocalFile
) )
411 wxTextFile
fileLocal(m_strLocalFile
);
412 if ( fileLocal
.Open(*m_conv
/*ignored in ANSI build*/) )
414 Parse(fileLocal
, true /* local */);
419 wxLogWarning(_("can't open user configuration file '%s'."), m_strLocalFile
.c_str() );
426 // constructor supports creation of wxFileConfig objects of any type
427 wxFileConfig::wxFileConfig(const wxString
& appName
, const wxString
& vendorName
,
428 const wxString
& strLocal
, const wxString
& strGlobal
,
430 const wxMBConv
& conv
)
431 : wxConfigBase(::GetAppName(appName
), vendorName
,
434 m_strLocalFile(strLocal
), m_strGlobalFile(strGlobal
),
437 // Make up names for files if empty
438 if ( m_strLocalFile
.empty() && (style
& wxCONFIG_USE_LOCAL_FILE
) )
440 m_strLocalFile
= GetLocalFileName(GetAppName());
441 #if defined(__UNIX__) && !defined(__VMS)
442 if ( style
& wxCONFIG_USE_SUBDIR
)
443 m_strLocalFile
<< wxFILE_SEP_PATH
<< GetAppName() << _T(".conf");
447 if ( m_strGlobalFile
.empty() && (style
& wxCONFIG_USE_GLOBAL_FILE
) )
448 m_strGlobalFile
= GetGlobalFileName(GetAppName());
450 // Check if styles are not supplied, but filenames are, in which case
451 // add the correct styles.
452 if ( !m_strLocalFile
.empty() )
453 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
455 if ( !m_strGlobalFile
.empty() )
456 SetStyle(GetStyle() | wxCONFIG_USE_GLOBAL_FILE
);
458 // if the path is not absolute, prepend the standard directory to it
459 // UNLESS wxCONFIG_USE_RELATIVE_PATH style is set
460 if ( !(style
& wxCONFIG_USE_RELATIVE_PATH
) )
462 if ( !m_strLocalFile
.empty() && !wxIsAbsolutePath(m_strLocalFile
) )
464 const wxString strLocalOrig
= m_strLocalFile
;
465 m_strLocalFile
= GetLocalDir();
466 m_strLocalFile
<< strLocalOrig
;
469 if ( !m_strGlobalFile
.empty() && !wxIsAbsolutePath(m_strGlobalFile
) )
471 const wxString strGlobalOrig
= m_strGlobalFile
;
472 m_strGlobalFile
= GetGlobalDir();
473 m_strGlobalFile
<< strGlobalOrig
;
484 wxFileConfig::wxFileConfig(wxInputStream
&inStream
, const wxMBConv
& conv
)
485 : m_conv(conv
.Clone())
487 // always local_file when this constructor is called (?)
488 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
491 m_pRootGroup
= new wxFileConfigGroup(NULL
, wxEmptyString
, this);
496 // read the entire stream contents in memory
499 static const size_t chunkLen
= 1024;
501 wxMemoryBuffer
buf(chunkLen
);
504 inStream
.Read(buf
.GetAppendBuf(chunkLen
), chunkLen
);
505 buf
.UngetAppendBuf(inStream
.LastRead());
507 const wxStreamError err
= inStream
.GetLastError();
509 if ( err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
)
511 wxLogError(_("Error reading config options."));
515 while ( !inStream
.Eof() );
519 str
= conv
.cMB2WC((char *)buf
.GetData(), buf
.GetDataLen(), &len
);
520 if ( !len
&& buf
.GetDataLen() )
522 wxLogError(_("Failed to read config options."));
524 #else // !wxUSE_UNICODE
525 // no need for conversion
526 str
.assign((char *)buf
.GetData(), buf
.GetDataLen());
527 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
531 // translate everything to the current (platform-dependent) line
532 // termination character
533 str
= wxTextBuffer::Translate(str
);
535 wxMemoryText memText
;
537 // Now we can add the text to the memory text. To do this we extract line
538 // by line from the translated string, until we've reached the end.
540 // VZ: all this is horribly inefficient, we should do the translation on
541 // the fly in one pass saving both memory and time (TODO)
543 const wxChar
*pEOL
= wxTextBuffer::GetEOL(wxTextBuffer::typeDefault
);
544 const size_t EOLLen
= wxStrlen(pEOL
);
546 int posLineStart
= str
.Find(pEOL
);
547 while ( posLineStart
!= -1 )
549 wxString
line(str
.Left(posLineStart
));
551 memText
.AddLine(line
);
553 str
= str
.Mid(posLineStart
+ EOLLen
);
555 posLineStart
= str
.Find(pEOL
);
558 // also add whatever we have left in the translated string.
560 memText
.AddLine(str
);
562 // Finally we can parse it all.
563 Parse(memText
, true /* local */);
569 #endif // wxUSE_STREAMS
571 void wxFileConfig::CleanUp()
575 wxFileConfigLineList
*pCur
= m_linesHead
;
576 while ( pCur
!= NULL
) {
577 wxFileConfigLineList
*pNext
= pCur
->Next();
583 wxFileConfig::~wxFileConfig()
592 // ----------------------------------------------------------------------------
593 // parse a config file
594 // ----------------------------------------------------------------------------
596 void wxFileConfig::Parse(const wxTextBuffer
& buffer
, bool bLocal
)
598 const wxChar
*pStart
;
602 size_t nLineCount
= buffer
.GetLineCount();
604 for ( size_t n
= 0; n
< nLineCount
; n
++ )
608 // add the line to linked list
611 LineListAppend(strLine
);
613 // let the root group have its start line as well
616 m_pCurrentGroup
->SetLine(m_linesTail
);
621 // skip leading spaces
622 for ( pStart
= strLine
; wxIsspace(*pStart
); pStart
++ )
625 // skip blank/comment lines
626 if ( *pStart
== wxT('\0')|| *pStart
== wxT(';') || *pStart
== wxT('#') )
629 if ( *pStart
== wxT('[') ) { // a new group
632 while ( *++pEnd
!= wxT(']') ) {
633 if ( *pEnd
== wxT('\\') ) {
634 // the next char is escaped, so skip it even if it is ']'
638 if ( *pEnd
== wxT('\n') || *pEnd
== wxT('\0') ) {
639 // we reached the end of line, break out of the loop
644 if ( *pEnd
!= wxT(']') ) {
645 wxLogError(_("file '%s': unexpected character %c at line %d."),
646 buffer
.GetName(), *pEnd
, n
+ 1);
647 continue; // skip this line
650 // group name here is always considered as abs path
653 strGroup
<< wxCONFIG_PATH_SEPARATOR
654 << FilterInEntryName(wxString(pStart
, pEnd
- pStart
));
656 // will create it if doesn't yet exist
661 if ( m_pCurrentGroup
->Parent() )
662 m_pCurrentGroup
->Parent()->SetLastGroup(m_pCurrentGroup
);
663 m_pCurrentGroup
->SetLine(m_linesTail
);
666 // check that there is nothing except comments left on this line
668 while ( *++pEnd
!= wxT('\0') && bCont
) {
677 // ignore whitespace ('\n' impossible here)
681 wxLogWarning(_("file '%s', line %d: '%s' ignored after group header."),
682 buffer
.GetName(), n
+ 1, pEnd
);
689 while ( *pEnd
&& *pEnd
!= wxT('=') /* && !wxIsspace(*pEnd)*/ ) {
690 if ( *pEnd
== wxT('\\') ) {
691 // next character may be space or not - still take it because it's
692 // quoted (unless there is nothing)
695 // the error message will be given below anyhow
703 wxString
strKey(FilterInEntryName(wxString(pStart
, pEnd
).Trim()));
706 while ( wxIsspace(*pEnd
) )
709 if ( *pEnd
++ != wxT('=') ) {
710 wxLogError(_("file '%s', line %d: '=' expected."),
711 buffer
.GetName(), n
+ 1);
714 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strKey
);
716 if ( pEntry
== NULL
) {
718 pEntry
= m_pCurrentGroup
->AddEntry(strKey
, n
);
721 if ( bLocal
&& pEntry
->IsImmutable() ) {
722 // immutable keys can't be changed by user
723 wxLogWarning(_("file '%s', line %d: value for immutable key '%s' ignored."),
724 buffer
.GetName(), n
+ 1, strKey
.c_str());
727 // the condition below catches the cases (a) and (b) but not (c):
728 // (a) global key found second time in global file
729 // (b) key found second (or more) time in local file
730 // (c) key from global file now found in local one
731 // which is exactly what we want.
732 else if ( !bLocal
|| pEntry
->IsLocal() ) {
733 wxLogWarning(_("file '%s', line %d: key '%s' was first found at line %d."),
734 buffer
.GetName(), n
+ 1, strKey
.c_str(), pEntry
->Line());
740 pEntry
->SetLine(m_linesTail
);
743 while ( wxIsspace(*pEnd
) )
746 wxString value
= pEnd
;
747 if ( !(GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS
) )
748 value
= FilterInValue(value
);
750 pEntry
->SetValue(value
, false);
756 // ----------------------------------------------------------------------------
758 // ----------------------------------------------------------------------------
760 void wxFileConfig::SetRootPath()
763 m_pCurrentGroup
= m_pRootGroup
;
767 wxFileConfig::DoSetPath(const wxString
& strPath
, bool createMissingComponents
)
769 wxArrayString aParts
;
771 if ( strPath
.empty() ) {
776 if ( strPath
[0] == wxCONFIG_PATH_SEPARATOR
) {
778 wxSplitPath(aParts
, strPath
);
781 // relative path, combine with current one
782 wxString strFullPath
= m_strPath
;
783 strFullPath
<< wxCONFIG_PATH_SEPARATOR
<< strPath
;
784 wxSplitPath(aParts
, strFullPath
);
787 // change current group
789 m_pCurrentGroup
= m_pRootGroup
;
790 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
791 wxFileConfigGroup
*pNextGroup
= m_pCurrentGroup
->FindSubgroup(aParts
[n
]);
792 if ( pNextGroup
== NULL
)
794 if ( !createMissingComponents
)
797 pNextGroup
= m_pCurrentGroup
->AddSubgroup(aParts
[n
]);
800 m_pCurrentGroup
= pNextGroup
;
803 // recombine path parts in one variable
805 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
806 m_strPath
<< wxCONFIG_PATH_SEPARATOR
<< aParts
[n
];
812 void wxFileConfig::SetPath(const wxString
& strPath
)
814 DoSetPath(strPath
, true /* create missing path components */);
817 // ----------------------------------------------------------------------------
819 // ----------------------------------------------------------------------------
821 bool wxFileConfig::GetFirstGroup(wxString
& str
, long& lIndex
) const
824 return GetNextGroup(str
, lIndex
);
827 bool wxFileConfig::GetNextGroup (wxString
& str
, long& lIndex
) const
829 if ( size_t(lIndex
) < m_pCurrentGroup
->Groups().Count() ) {
830 str
= m_pCurrentGroup
->Groups()[(size_t)lIndex
++]->Name();
837 bool wxFileConfig::GetFirstEntry(wxString
& str
, long& lIndex
) const
840 return GetNextEntry(str
, lIndex
);
843 bool wxFileConfig::GetNextEntry (wxString
& str
, long& lIndex
) const
845 if ( size_t(lIndex
) < m_pCurrentGroup
->Entries().Count() ) {
846 str
= m_pCurrentGroup
->Entries()[(size_t)lIndex
++]->Name();
853 size_t wxFileConfig::GetNumberOfEntries(bool bRecursive
) const
855 size_t n
= m_pCurrentGroup
->Entries().Count();
857 wxFileConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
858 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
859 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
860 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
861 n
+= GetNumberOfEntries(true);
862 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
869 size_t wxFileConfig::GetNumberOfGroups(bool bRecursive
) const
871 size_t n
= m_pCurrentGroup
->Groups().Count();
873 wxFileConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
874 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
875 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
876 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
877 n
+= GetNumberOfGroups(true);
878 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
885 // ----------------------------------------------------------------------------
886 // tests for existence
887 // ----------------------------------------------------------------------------
889 bool wxFileConfig::HasGroup(const wxString
& strName
) const
891 // special case: DoSetPath("") does work as it's equivalent to DoSetPath("/")
892 // but there is no group with empty name so treat this separately
893 if ( strName
.empty() )
896 const wxString pathOld
= GetPath();
898 wxFileConfig
*self
= wx_const_cast(wxFileConfig
*, this);
900 rc
= self
->DoSetPath(strName
, false /* don't create missing components */);
902 self
->SetPath(pathOld
);
907 bool wxFileConfig::HasEntry(const wxString
& entry
) const
909 // path is the part before the last "/"
910 wxString path
= entry
.BeforeLast(wxCONFIG_PATH_SEPARATOR
);
912 // except in the special case of "/keyname" when there is nothing before "/"
913 if ( path
.empty() && *entry
.c_str() == wxCONFIG_PATH_SEPARATOR
)
915 path
= wxCONFIG_PATH_SEPARATOR
;
918 // change to the path of the entry if necessary and remember the old path
919 // to restore it later
921 wxFileConfig
* const self
= wx_const_cast(wxFileConfig
*, this);
925 if ( pathOld
.empty() )
926 pathOld
= wxCONFIG_PATH_SEPARATOR
;
928 if ( !self
->DoSetPath(path
, false /* don't create if doesn't exist */) )
934 // check if the entry exists in this group
935 const bool exists
= m_pCurrentGroup
->FindEntry(
936 entry
.AfterLast(wxCONFIG_PATH_SEPARATOR
)) != NULL
;
938 // restore the old path if we changed it above
939 if ( !pathOld
.empty() )
941 self
->SetPath(pathOld
);
947 // ----------------------------------------------------------------------------
949 // ----------------------------------------------------------------------------
951 bool wxFileConfig::DoReadString(const wxString
& key
, wxString
* pStr
) const
953 wxConfigPathChanger
path(this, key
);
955 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
956 if (pEntry
== NULL
) {
960 *pStr
= pEntry
->Value();
965 bool wxFileConfig::DoReadLong(const wxString
& key
, long *pl
) const
968 if ( !Read(key
, &str
) )
971 // extra spaces shouldn't prevent us from reading numeric values
974 return str
.ToLong(pl
);
977 bool wxFileConfig::DoWriteString(const wxString
& key
, const wxString
& szValue
)
979 wxConfigPathChanger
path(this, key
);
980 wxString strName
= path
.Name();
982 wxLogTrace( FILECONF_TRACE_MASK
,
983 _T(" Writing String '%s' = '%s' to Group '%s'"),
988 if ( strName
.empty() )
990 // setting the value of a group is an error
992 wxASSERT_MSG( szValue
.empty(), wxT("can't set value of a group!") );
994 // ... except if it's empty in which case it's a way to force it's creation
996 wxLogTrace( FILECONF_TRACE_MASK
,
997 _T(" Creating group %s"),
998 m_pCurrentGroup
->Name().c_str() );
1002 // this will add a line for this group if it didn't have it before
1004 (void)m_pCurrentGroup
->GetGroupLine();
1008 // writing an entry check that the name is reasonable
1009 if ( strName
[0u] == wxCONFIG_IMMUTABLE_PREFIX
)
1011 wxLogError( _("Config entry name cannot start with '%c'."),
1012 wxCONFIG_IMMUTABLE_PREFIX
);
1016 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strName
);
1020 wxLogTrace( FILECONF_TRACE_MASK
,
1021 _T(" Adding Entry %s"),
1023 pEntry
= m_pCurrentGroup
->AddEntry(strName
);
1026 wxLogTrace( FILECONF_TRACE_MASK
,
1027 _T(" Setting value %s"),
1029 pEntry
->SetValue(szValue
);
1037 bool wxFileConfig::DoWriteLong(const wxString
& key
, long lValue
)
1039 return Write(key
, wxString::Format(_T("%ld"), lValue
));
1042 bool wxFileConfig::Flush(bool /* bCurrentOnly */)
1044 if ( !IsDirty() || !m_strLocalFile
)
1047 // set the umask if needed
1048 wxCHANGE_UMASK(m_umask
);
1050 wxTempFile
file(m_strLocalFile
);
1052 if ( !file
.IsOpened() )
1054 wxLogError(_("can't open user configuration file."));
1058 // write all strings to file
1060 filetext
.reserve(4096);
1061 for ( wxFileConfigLineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() )
1063 filetext
<< p
->Text() << wxTextFile::GetEOL();
1066 if ( !file
.Write(filetext
, *m_conv
) )
1068 wxLogError(_("can't write user configuration file."));
1072 if ( !file
.Commit() )
1074 wxLogError(_("Failed to update user configuration file."));
1081 #if defined(__WXMAC__)
1082 wxFileName(m_strLocalFile
).MacSetTypeAndCreator('TEXT', 'ttxt');
1090 bool wxFileConfig::Save(wxOutputStream
& os
, const wxMBConv
& conv
)
1092 // save unconditionally, even if not dirty
1093 for ( wxFileConfigLineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() )
1095 wxString line
= p
->Text();
1096 line
+= wxTextFile::GetEOL();
1098 wxCharBuffer
buf(line
.mb_str(conv
));
1099 if ( !os
.Write(buf
, strlen(buf
)) )
1101 wxLogError(_("Error saving user configuration data."));
1112 #endif // wxUSE_STREAMS
1114 // ----------------------------------------------------------------------------
1115 // renaming groups/entries
1116 // ----------------------------------------------------------------------------
1118 bool wxFileConfig::RenameEntry(const wxString
& oldName
,
1119 const wxString
& newName
)
1121 wxASSERT_MSG( !wxStrchr(oldName
, wxCONFIG_PATH_SEPARATOR
),
1122 _T("RenameEntry(): paths are not supported") );
1124 // check that the entry exists
1125 wxFileConfigEntry
*oldEntry
= m_pCurrentGroup
->FindEntry(oldName
);
1129 // check that the new entry doesn't already exist
1130 if ( m_pCurrentGroup
->FindEntry(newName
) )
1133 // delete the old entry, create the new one
1134 wxString value
= oldEntry
->Value();
1135 if ( !m_pCurrentGroup
->DeleteEntry(oldName
) )
1140 wxFileConfigEntry
*newEntry
= m_pCurrentGroup
->AddEntry(newName
);
1141 newEntry
->SetValue(value
);
1146 bool wxFileConfig::RenameGroup(const wxString
& oldName
,
1147 const wxString
& newName
)
1149 // check that the group exists
1150 wxFileConfigGroup
*group
= m_pCurrentGroup
->FindSubgroup(oldName
);
1154 // check that the new group doesn't already exist
1155 if ( m_pCurrentGroup
->FindSubgroup(newName
) )
1158 group
->Rename(newName
);
1165 // ----------------------------------------------------------------------------
1166 // delete groups/entries
1167 // ----------------------------------------------------------------------------
1169 bool wxFileConfig::DeleteEntry(const wxString
& key
, bool bGroupIfEmptyAlso
)
1171 wxConfigPathChanger
path(this, key
);
1173 if ( !m_pCurrentGroup
->DeleteEntry(path
.Name()) )
1178 if ( bGroupIfEmptyAlso
&& m_pCurrentGroup
->IsEmpty() ) {
1179 if ( m_pCurrentGroup
!= m_pRootGroup
) {
1180 wxFileConfigGroup
*pGroup
= m_pCurrentGroup
;
1181 SetPath(wxT("..")); // changes m_pCurrentGroup!
1182 m_pCurrentGroup
->DeleteSubgroupByName(pGroup
->Name());
1184 //else: never delete the root group
1190 bool wxFileConfig::DeleteGroup(const wxString
& key
)
1192 wxConfigPathChanger
path(this, RemoveTrailingSeparator(key
));
1194 if ( !m_pCurrentGroup
->DeleteSubgroupByName(path
.Name()) )
1197 path
.UpdateIfDeleted();
1204 bool wxFileConfig::DeleteAll()
1208 if ( !m_strLocalFile
.empty() )
1210 if ( wxFile::Exists(m_strLocalFile
) && wxRemove(m_strLocalFile
) == -1 )
1212 wxLogSysError(_("can't delete user configuration file '%s'"),
1213 m_strLocalFile
.c_str());
1223 // ----------------------------------------------------------------------------
1224 // linked list functions
1225 // ----------------------------------------------------------------------------
1227 // append a new line to the end of the list
1229 wxFileConfigLineList
*wxFileConfig::LineListAppend(const wxString
& str
)
1231 wxLogTrace( FILECONF_TRACE_MASK
,
1232 _T(" ** Adding Line '%s'"),
1234 wxLogTrace( FILECONF_TRACE_MASK
,
1236 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1237 wxLogTrace( FILECONF_TRACE_MASK
,
1239 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1241 wxFileConfigLineList
*pLine
= new wxFileConfigLineList(str
);
1243 if ( m_linesTail
== NULL
)
1246 m_linesHead
= pLine
;
1251 m_linesTail
->SetNext(pLine
);
1252 pLine
->SetPrev(m_linesTail
);
1255 m_linesTail
= pLine
;
1257 wxLogTrace( FILECONF_TRACE_MASK
,
1259 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1260 wxLogTrace( FILECONF_TRACE_MASK
,
1262 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1267 // insert a new line after the given one or in the very beginning if !pLine
1268 wxFileConfigLineList
*wxFileConfig::LineListInsert(const wxString
& str
,
1269 wxFileConfigLineList
*pLine
)
1271 wxLogTrace( FILECONF_TRACE_MASK
,
1272 _T(" ** Inserting Line '%s' after '%s'"),
1274 ((pLine
) ? pLine
->Text().c_str() : wxEmptyString
) );
1275 wxLogTrace( FILECONF_TRACE_MASK
,
1277 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1278 wxLogTrace( FILECONF_TRACE_MASK
,
1280 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1282 if ( pLine
== m_linesTail
)
1283 return LineListAppend(str
);
1285 wxFileConfigLineList
*pNewLine
= new wxFileConfigLineList(str
);
1286 if ( pLine
== NULL
)
1288 // prepend to the list
1289 pNewLine
->SetNext(m_linesHead
);
1290 m_linesHead
->SetPrev(pNewLine
);
1291 m_linesHead
= pNewLine
;
1295 // insert before pLine
1296 wxFileConfigLineList
*pNext
= pLine
->Next();
1297 pNewLine
->SetNext(pNext
);
1298 pNewLine
->SetPrev(pLine
);
1299 pNext
->SetPrev(pNewLine
);
1300 pLine
->SetNext(pNewLine
);
1303 wxLogTrace( FILECONF_TRACE_MASK
,
1305 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1306 wxLogTrace( FILECONF_TRACE_MASK
,
1308 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1313 void wxFileConfig::LineListRemove(wxFileConfigLineList
*pLine
)
1315 wxLogTrace( FILECONF_TRACE_MASK
,
1316 _T(" ** Removing Line '%s'"),
1317 pLine
->Text().c_str() );
1318 wxLogTrace( FILECONF_TRACE_MASK
,
1320 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1321 wxLogTrace( FILECONF_TRACE_MASK
,
1323 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1325 wxFileConfigLineList
*pPrev
= pLine
->Prev(),
1326 *pNext
= pLine
->Next();
1330 if ( pPrev
== NULL
)
1331 m_linesHead
= pNext
;
1333 pPrev
->SetNext(pNext
);
1337 if ( pNext
== NULL
)
1338 m_linesTail
= pPrev
;
1340 pNext
->SetPrev(pPrev
);
1342 if ( m_pRootGroup
->GetGroupLine() == pLine
)
1343 m_pRootGroup
->SetLine(m_linesHead
);
1345 wxLogTrace( FILECONF_TRACE_MASK
,
1347 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1348 wxLogTrace( FILECONF_TRACE_MASK
,
1350 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1355 bool wxFileConfig::LineListIsEmpty()
1357 return m_linesHead
== NULL
;
1360 // ============================================================================
1361 // wxFileConfig::wxFileConfigGroup
1362 // ============================================================================
1364 // ----------------------------------------------------------------------------
1366 // ----------------------------------------------------------------------------
1369 wxFileConfigGroup::wxFileConfigGroup(wxFileConfigGroup
*pParent
,
1370 const wxString
& strName
,
1371 wxFileConfig
*pConfig
)
1372 : m_aEntries(CompareEntries
),
1373 m_aSubgroups(CompareGroups
),
1376 m_pConfig
= pConfig
;
1377 m_pParent
= pParent
;
1380 m_pLastEntry
= NULL
;
1381 m_pLastGroup
= NULL
;
1384 // dtor deletes all children
1385 wxFileConfigGroup::~wxFileConfigGroup()
1388 size_t n
, nCount
= m_aEntries
.Count();
1389 for ( n
= 0; n
< nCount
; n
++ )
1390 delete m_aEntries
[n
];
1393 nCount
= m_aSubgroups
.Count();
1394 for ( n
= 0; n
< nCount
; n
++ )
1395 delete m_aSubgroups
[n
];
1398 // ----------------------------------------------------------------------------
1400 // ----------------------------------------------------------------------------
1402 void wxFileConfigGroup::SetLine(wxFileConfigLineList
*pLine
)
1404 // for a normal (i.e. not root) group this method shouldn't be called twice
1405 // unless we are resetting the line
1406 wxASSERT_MSG( !m_pParent
|| !m_pLine
|| !pLine
,
1407 _T("changing line for a non-root group?") );
1413 This is a bit complicated, so let me explain it in details. All lines that
1414 were read from the local file (the only one we will ever modify) are stored
1415 in a (doubly) linked list. Our problem is to know at which position in this
1416 list should we insert the new entries/subgroups. To solve it we keep three
1417 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1419 m_pLine points to the line containing "[group_name]"
1420 m_pLastEntry points to the last entry of this group in the local file.
1421 m_pLastGroup subgroup
1423 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1424 from the local file, the corresponding variable is set. However, if the group
1425 was read from the global file and then modified or created by the application
1426 these variables are still NULL and we need to create the corresponding lines.
1427 See the following functions (and comments preceding them) for the details of
1430 Also, when our last entry/group are deleted we need to find the new last
1431 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1432 of lines until it either founds an entry/subgroup (and this is the new last
1433 element) or the m_pLine of the group, in which case there are no more entries
1434 (or subgroups) left and m_pLast<element> becomes NULL.
1436 NB: This last problem could be avoided for entries if we added new entries
1437 immediately after m_pLine, but in this case the entries would appear
1438 backwards in the config file (OTOH, it's not that important) and as we
1439 would still need to do it for the subgroups the code wouldn't have been
1440 significantly less complicated.
1443 // Return the line which contains "[our name]". If we're still not in the list,
1444 // add our line to it immediately after the last line of our parent group if we
1445 // have it or in the very beginning if we're the root group.
1446 wxFileConfigLineList
*wxFileConfigGroup::GetGroupLine()
1448 wxLogTrace( FILECONF_TRACE_MASK
,
1449 _T(" GetGroupLine() for Group '%s'"),
1454 wxLogTrace( FILECONF_TRACE_MASK
,
1455 _T(" Getting Line item pointer") );
1457 wxFileConfigGroup
*pParent
= Parent();
1459 // this group wasn't present in local config file, add it now
1462 wxLogTrace( FILECONF_TRACE_MASK
,
1463 _T(" checking parent '%s'"),
1464 pParent
->Name().c_str() );
1466 wxString strFullName
;
1468 // add 1 to the name because we don't want to start with '/'
1469 strFullName
<< wxT("[")
1470 << FilterOutEntryName(GetFullName().c_str() + 1)
1472 m_pLine
= m_pConfig
->LineListInsert(strFullName
,
1473 pParent
->GetLastGroupLine());
1474 pParent
->SetLastGroup(this); // we're surely after all the others
1476 //else: this is the root group and so we return NULL because we don't
1477 // have any group line
1483 // Return the last line belonging to the subgroups of this group (after which
1484 // we can add a new subgroup), if we don't have any subgroups or entries our
1485 // last line is the group line (m_pLine) itself.
1486 wxFileConfigLineList
*wxFileConfigGroup::GetLastGroupLine()
1488 // if we have any subgroups, our last line is the last line of the last
1492 wxFileConfigLineList
*pLine
= m_pLastGroup
->GetLastGroupLine();
1494 wxASSERT_MSG( pLine
, _T("last group must have !NULL associated line") );
1499 // no subgroups, so the last line is the line of thelast entry (if any)
1500 return GetLastEntryLine();
1503 // return the last line belonging to the entries of this group (after which
1504 // we can add a new entry), if we don't have any entries we will add the new
1505 // one immediately after the group line itself.
1506 wxFileConfigLineList
*wxFileConfigGroup::GetLastEntryLine()
1508 wxLogTrace( FILECONF_TRACE_MASK
,
1509 _T(" GetLastEntryLine() for Group '%s'"),
1514 wxFileConfigLineList
*pLine
= m_pLastEntry
->GetLine();
1516 wxASSERT_MSG( pLine
, _T("last entry must have !NULL associated line") );
1521 // no entries: insert after the group header, if any
1522 return GetGroupLine();
1525 void wxFileConfigGroup::SetLastEntry(wxFileConfigEntry
*pEntry
)
1527 m_pLastEntry
= pEntry
;
1531 // the only situation in which a group without its own line can have
1532 // an entry is when the first entry is added to the initially empty
1533 // root pseudo-group
1534 wxASSERT_MSG( !m_pParent
, _T("unexpected for non root group") );
1536 // let the group know that it does have a line in the file now
1537 m_pLine
= pEntry
->GetLine();
1541 // ----------------------------------------------------------------------------
1543 // ----------------------------------------------------------------------------
1545 void wxFileConfigGroup::UpdateGroupAndSubgroupsLines()
1547 // update the line of this group
1548 wxFileConfigLineList
*line
= GetGroupLine();
1549 wxCHECK_RET( line
, _T("a non root group must have a corresponding line!") );
1551 // +1: skip the leading '/'
1552 line
->SetText(wxString::Format(_T("[%s]"), GetFullName().c_str() + 1));
1555 // also update all subgroups as they have this groups name in their lines
1556 const size_t nCount
= m_aSubgroups
.Count();
1557 for ( size_t n
= 0; n
< nCount
; n
++ )
1559 m_aSubgroups
[n
]->UpdateGroupAndSubgroupsLines();
1563 void wxFileConfigGroup::Rename(const wxString
& newName
)
1565 wxCHECK_RET( m_pParent
, _T("the root group can't be renamed") );
1567 if ( newName
== m_strName
)
1570 // we need to remove the group from the parent and it back under the new
1571 // name to keep the parents array of subgroups alphabetically sorted
1572 m_pParent
->m_aSubgroups
.Remove(this);
1574 m_strName
= newName
;
1576 m_pParent
->m_aSubgroups
.Add(this);
1578 // update the group lines recursively
1579 UpdateGroupAndSubgroupsLines();
1582 wxString
wxFileConfigGroup::GetFullName() const
1586 fullname
= Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR
+ Name();
1591 // ----------------------------------------------------------------------------
1593 // ----------------------------------------------------------------------------
1595 // use binary search because the array is sorted
1597 wxFileConfigGroup::FindEntry(const wxChar
*szName
) const
1601 hi
= m_aEntries
.Count();
1603 wxFileConfigEntry
*pEntry
;
1607 pEntry
= m_aEntries
[i
];
1609 #if wxCONFIG_CASE_SENSITIVE
1610 res
= wxStrcmp(pEntry
->Name(), szName
);
1612 res
= wxStricmp(pEntry
->Name(), szName
);
1627 wxFileConfigGroup::FindSubgroup(const wxChar
*szName
) const
1631 hi
= m_aSubgroups
.Count();
1633 wxFileConfigGroup
*pGroup
;
1637 pGroup
= m_aSubgroups
[i
];
1639 #if wxCONFIG_CASE_SENSITIVE
1640 res
= wxStrcmp(pGroup
->Name(), szName
);
1642 res
= wxStricmp(pGroup
->Name(), szName
);
1656 // ----------------------------------------------------------------------------
1657 // create a new item
1658 // ----------------------------------------------------------------------------
1660 // create a new entry and add it to the current group
1661 wxFileConfigEntry
*wxFileConfigGroup::AddEntry(const wxString
& strName
, int nLine
)
1663 wxASSERT( FindEntry(strName
) == 0 );
1665 wxFileConfigEntry
*pEntry
= new wxFileConfigEntry(this, strName
, nLine
);
1667 m_aEntries
.Add(pEntry
);
1671 // create a new group and add it to the current group
1672 wxFileConfigGroup
*wxFileConfigGroup::AddSubgroup(const wxString
& strName
)
1674 wxASSERT( FindSubgroup(strName
) == 0 );
1676 wxFileConfigGroup
*pGroup
= new wxFileConfigGroup(this, strName
, m_pConfig
);
1678 m_aSubgroups
.Add(pGroup
);
1682 // ----------------------------------------------------------------------------
1684 // ----------------------------------------------------------------------------
1687 The delete operations are _very_ slow if we delete the last item of this
1688 group (see comments before GetXXXLineXXX functions for more details),
1689 so it's much better to start with the first entry/group if we want to
1690 delete several of them.
1693 bool wxFileConfigGroup::DeleteSubgroupByName(const wxChar
*szName
)
1695 wxFileConfigGroup
* const pGroup
= FindSubgroup(szName
);
1697 return pGroup
? DeleteSubgroup(pGroup
) : false;
1700 // Delete the subgroup and remove all references to it from
1701 // other data structures.
1702 bool wxFileConfigGroup::DeleteSubgroup(wxFileConfigGroup
*pGroup
)
1704 wxCHECK_MSG( pGroup
, false, _T("deleting non existing group?") );
1706 wxLogTrace( FILECONF_TRACE_MASK
,
1707 _T("Deleting group '%s' from '%s'"),
1708 pGroup
->Name().c_str(),
1711 wxLogTrace( FILECONF_TRACE_MASK
,
1712 _T(" (m_pLine) = prev: %p, this %p, next %p"),
1713 m_pLine
? wx_static_cast(void*, m_pLine
->Prev()) : 0,
1714 wx_static_cast(void*, m_pLine
),
1715 m_pLine
? wx_static_cast(void*, m_pLine
->Next()) : 0 );
1716 wxLogTrace( FILECONF_TRACE_MASK
,
1718 m_pLine
? m_pLine
->Text().c_str() : wxEmptyString
);
1720 // delete all entries...
1721 size_t nCount
= pGroup
->m_aEntries
.Count();
1723 wxLogTrace(FILECONF_TRACE_MASK
,
1724 _T("Removing %lu entries"), (unsigned long)nCount
);
1726 for ( size_t nEntry
= 0; nEntry
< nCount
; nEntry
++ )
1728 wxFileConfigLineList
*pLine
= pGroup
->m_aEntries
[nEntry
]->GetLine();
1732 wxLogTrace( FILECONF_TRACE_MASK
,
1734 pLine
->Text().c_str() );
1735 m_pConfig
->LineListRemove(pLine
);
1739 // ...and subgroups of this subgroup
1740 nCount
= pGroup
->m_aSubgroups
.Count();
1742 wxLogTrace( FILECONF_TRACE_MASK
,
1743 _T("Removing %lu subgroups"), (unsigned long)nCount
);
1745 for ( size_t nGroup
= 0; nGroup
< nCount
; nGroup
++ )
1747 pGroup
->DeleteSubgroup(pGroup
->m_aSubgroups
[0]);
1750 // and then finally the group itself
1751 wxFileConfigLineList
*pLine
= pGroup
->m_pLine
;
1754 wxLogTrace( FILECONF_TRACE_MASK
,
1755 _T(" Removing line for group '%s' : '%s'"),
1756 pGroup
->Name().c_str(),
1757 pLine
->Text().c_str() );
1758 wxLogTrace( FILECONF_TRACE_MASK
,
1759 _T(" Removing from group '%s' : '%s'"),
1761 ((m_pLine
) ? m_pLine
->Text().c_str() : wxEmptyString
) );
1763 // notice that we may do this test inside the previous "if"
1764 // because the last entry's line is surely !NULL
1765 if ( pGroup
== m_pLastGroup
)
1767 wxLogTrace( FILECONF_TRACE_MASK
,
1768 _T(" Removing last group") );
1770 // our last entry is being deleted, so find the last one which
1771 // stays by going back until we find a subgroup or reach the
1773 const size_t nSubgroups
= m_aSubgroups
.Count();
1775 m_pLastGroup
= NULL
;
1776 for ( wxFileConfigLineList
*pl
= pLine
->Prev();
1777 pl
&& pl
!= m_pLine
&& !m_pLastGroup
;
1780 // does this line belong to our subgroup?
1781 for ( size_t n
= 0; n
< nSubgroups
; n
++ )
1783 // do _not_ call GetGroupLine! we don't want to add it to
1784 // the local file if it's not already there
1785 if ( m_aSubgroups
[n
]->m_pLine
== pl
)
1787 m_pLastGroup
= m_aSubgroups
[n
];
1794 m_pConfig
->LineListRemove(pLine
);
1798 wxLogTrace( FILECONF_TRACE_MASK
,
1799 _T(" No line entry for Group '%s'?"),
1800 pGroup
->Name().c_str() );
1803 m_aSubgroups
.Remove(pGroup
);
1809 bool wxFileConfigGroup::DeleteEntry(const wxChar
*szName
)
1811 wxFileConfigEntry
*pEntry
= FindEntry(szName
);
1814 // entry doesn't exist, nothing to do
1818 wxFileConfigLineList
*pLine
= pEntry
->GetLine();
1819 if ( pLine
!= NULL
) {
1820 // notice that we may do this test inside the previous "if" because the
1821 // last entry's line is surely !NULL
1822 if ( pEntry
== m_pLastEntry
) {
1823 // our last entry is being deleted - find the last one which stays
1824 wxASSERT( m_pLine
!= NULL
); // if we have an entry with !NULL pLine...
1826 // go back until we find another entry or reach the group's line
1827 wxFileConfigEntry
*pNewLast
= NULL
;
1828 size_t n
, nEntries
= m_aEntries
.Count();
1829 wxFileConfigLineList
*pl
;
1830 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1831 // is it our subgroup?
1832 for ( n
= 0; (pNewLast
== NULL
) && (n
< nEntries
); n
++ ) {
1833 if ( m_aEntries
[n
]->GetLine() == m_pLine
)
1834 pNewLast
= m_aEntries
[n
];
1837 if ( pNewLast
!= NULL
) // found?
1841 if ( pl
== m_pLine
) {
1842 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1844 // we've reached the group line without finding any subgroups
1845 m_pLastEntry
= NULL
;
1848 m_pLastEntry
= pNewLast
;
1851 m_pConfig
->LineListRemove(pLine
);
1854 m_aEntries
.Remove(pEntry
);
1860 // ============================================================================
1861 // wxFileConfig::wxFileConfigEntry
1862 // ============================================================================
1864 // ----------------------------------------------------------------------------
1866 // ----------------------------------------------------------------------------
1867 wxFileConfigEntry::wxFileConfigEntry(wxFileConfigGroup
*pParent
,
1868 const wxString
& strName
,
1870 : m_strName(strName
)
1872 wxASSERT( !strName
.empty() );
1874 m_pParent
= pParent
;
1878 m_bHasValue
= false;
1880 m_bImmutable
= strName
[0] == wxCONFIG_IMMUTABLE_PREFIX
;
1882 m_strName
.erase(0, 1); // remove first character
1885 // ----------------------------------------------------------------------------
1887 // ----------------------------------------------------------------------------
1889 void wxFileConfigEntry::SetLine(wxFileConfigLineList
*pLine
)
1891 if ( m_pLine
!= NULL
) {
1892 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1893 Name().c_str(), m_pParent
->GetFullName().c_str());
1897 Group()->SetLastEntry(this);
1900 // second parameter is false if we read the value from file and prevents the
1901 // entry from being marked as 'dirty'
1902 void wxFileConfigEntry::SetValue(const wxString
& strValue
, bool bUser
)
1904 if ( bUser
&& IsImmutable() )
1906 wxLogWarning( _("attempt to change immutable key '%s' ignored."),
1911 // do nothing if it's the same value: but don't test for it if m_bHasValue
1912 // hadn't been set yet or we'd never write empty values to the file
1913 if ( m_bHasValue
&& strValue
== m_strValue
)
1917 m_strValue
= strValue
;
1921 wxString strValFiltered
;
1923 if ( Group()->Config()->GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS
)
1925 strValFiltered
= strValue
;
1928 strValFiltered
= FilterOutValue(strValue
);
1932 strLine
<< FilterOutEntryName(m_strName
) << wxT('=') << strValFiltered
;
1936 // entry was read from the local config file, just modify the line
1937 m_pLine
->SetText(strLine
);
1939 else // this entry didn't exist in the local file
1941 // add a new line to the file: note that line returned by
1942 // GetLastEntryLine() may be NULL if we're in the root group and it
1943 // doesn't have any entries yet, but this is ok as passing NULL
1944 // line to LineListInsert() means to prepend new line to the list
1945 wxFileConfigLineList
*line
= Group()->GetLastEntryLine();
1946 m_pLine
= Group()->Config()->LineListInsert(strLine
, line
);
1948 Group()->SetLastEntry(this);
1953 // ============================================================================
1955 // ============================================================================
1957 // ----------------------------------------------------------------------------
1958 // compare functions for array sorting
1959 // ----------------------------------------------------------------------------
1961 int CompareEntries(wxFileConfigEntry
*p1
, wxFileConfigEntry
*p2
)
1963 #if wxCONFIG_CASE_SENSITIVE
1964 return wxStrcmp(p1
->Name(), p2
->Name());
1966 return wxStricmp(p1
->Name(), p2
->Name());
1970 int CompareGroups(wxFileConfigGroup
*p1
, wxFileConfigGroup
*p2
)
1972 #if wxCONFIG_CASE_SENSITIVE
1973 return wxStrcmp(p1
->Name(), p2
->Name());
1975 return wxStricmp(p1
->Name(), p2
->Name());
1979 // ----------------------------------------------------------------------------
1981 // ----------------------------------------------------------------------------
1983 // undo FilterOutValue
1984 static wxString
FilterInValue(const wxString
& str
)
1987 strResult
.Alloc(str
.Len());
1989 bool bQuoted
= !str
.empty() && str
[0] == '"';
1991 for ( size_t n
= bQuoted
? 1 : 0; n
< str
.Len(); n
++ ) {
1992 if ( str
[n
] == wxT('\\') ) {
1993 switch ( str
[++n
] ) {
1995 strResult
+= wxT('\n');
1999 strResult
+= wxT('\r');
2003 strResult
+= wxT('\t');
2007 strResult
+= wxT('\\');
2011 strResult
+= wxT('"');
2016 if ( str
[n
] != wxT('"') || !bQuoted
)
2017 strResult
+= str
[n
];
2018 else if ( n
!= str
.Len() - 1 ) {
2019 wxLogWarning(_("unexpected \" at position %d in '%s'."),
2022 //else: it's the last quote of a quoted string, ok
2029 // quote the string before writing it to file
2030 static wxString
FilterOutValue(const wxString
& str
)
2036 strResult
.Alloc(str
.Len());
2038 // quoting is necessary to preserve spaces in the beginning of the string
2039 bool bQuote
= wxIsspace(str
[0]) || str
[0] == wxT('"');
2042 strResult
+= wxT('"');
2045 for ( size_t n
= 0; n
< str
.Len(); n
++ ) {
2068 //else: fall through
2071 strResult
+= str
[n
];
2072 continue; // nothing special to do
2075 // we get here only for special characters
2076 strResult
<< wxT('\\') << c
;
2080 strResult
+= wxT('"');
2085 // undo FilterOutEntryName
2086 static wxString
FilterInEntryName(const wxString
& str
)
2089 strResult
.Alloc(str
.Len());
2091 for ( const wxChar
*pc
= str
.c_str(); *pc
!= '\0'; pc
++ ) {
2092 if ( *pc
== wxT('\\') ) {
2093 // we need to test it here or we'd skip past the NUL in the loop line
2094 if ( *++pc
== _T('\0') )
2104 // sanitize entry or group name: insert '\\' before any special characters
2105 static wxString
FilterOutEntryName(const wxString
& str
)
2108 strResult
.Alloc(str
.Len());
2110 for ( const wxChar
*pc
= str
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
2111 const wxChar c
= *pc
;
2113 // we explicitly allow some of "safe" chars and 8bit ASCII characters
2114 // which will probably never have special meaning and with which we can't
2115 // use isalnum() anyhow (in ASCII built, in Unicode it's just fine)
2117 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
2118 // should *not* be quoted
2121 ((unsigned char)c
< 127) &&
2123 !wxIsalnum(c
) && !wxStrchr(wxT("@_/-!.*%"), c
) )
2125 strResult
+= wxT('\\');
2134 // we can't put ?: in the ctor initializer list because it confuses some
2135 // broken compilers (Borland C++)
2136 static wxString
GetAppName(const wxString
& appName
)
2138 if ( !appName
&& wxTheApp
)
2139 return wxTheApp
->GetAppName();
2144 #endif // wxUSE_CONFIG