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 #include "wx/stdpaths.h"
47 #if defined(__WXMAC__)
48 #include "wx/mac/private.h" // includes mac headers
51 #if defined(__WXMSW__)
52 #include "wx/msw/private.h"
62 // ----------------------------------------------------------------------------
64 // ----------------------------------------------------------------------------
65 #define CONST_CAST ((wxFileConfig *)this)->
67 // ----------------------------------------------------------------------------
69 // ----------------------------------------------------------------------------
75 #define FILECONF_TRACE_MASK _T("fileconf")
77 // ----------------------------------------------------------------------------
78 // global functions declarations
79 // ----------------------------------------------------------------------------
81 // compare functions for sorting the arrays
82 static int LINKAGEMODE
CompareEntries(wxFileConfigEntry
*p1
, wxFileConfigEntry
*p2
);
83 static int LINKAGEMODE
CompareGroups(wxFileConfigGroup
*p1
, wxFileConfigGroup
*p2
);
86 static wxString
FilterInValue(const wxString
& str
);
87 static wxString
FilterOutValue(const wxString
& str
);
89 static wxString
FilterInEntryName(const wxString
& str
);
90 static wxString
FilterOutEntryName(const wxString
& str
);
92 // get the name to use in wxFileConfig ctor
93 static wxString
GetAppName(const wxString
& appname
);
95 // ============================================================================
97 // ============================================================================
99 // ----------------------------------------------------------------------------
100 // "template" array types
101 // ----------------------------------------------------------------------------
103 #ifdef WXMAKINGDLL_BASE
104 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(wxFileConfigEntry
*, ArrayEntries
,
106 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(wxFileConfigGroup
*, ArrayGroups
,
109 WX_DEFINE_SORTED_ARRAY(wxFileConfigEntry
*, ArrayEntries
);
110 WX_DEFINE_SORTED_ARRAY(wxFileConfigGroup
*, ArrayGroups
);
113 // ----------------------------------------------------------------------------
114 // wxFileConfigLineList
115 // ----------------------------------------------------------------------------
117 // we store all lines of the local config file as a linked list in memory
118 class wxFileConfigLineList
121 void SetNext(wxFileConfigLineList
*pNext
) { m_pNext
= pNext
; }
122 void SetPrev(wxFileConfigLineList
*pPrev
) { m_pPrev
= pPrev
; }
125 wxFileConfigLineList(const wxString
& str
,
126 wxFileConfigLineList
*pNext
= NULL
) : m_strLine(str
)
127 { SetNext(pNext
); SetPrev(NULL
); }
129 // next/prev nodes in the linked list
130 wxFileConfigLineList
*Next() const { return m_pNext
; }
131 wxFileConfigLineList
*Prev() const { return m_pPrev
; }
133 // get/change lines text
134 void SetText(const wxString
& str
) { m_strLine
= str
; }
135 const wxString
& Text() const { return m_strLine
; }
138 wxString m_strLine
; // line contents
139 wxFileConfigLineList
*m_pNext
, // next node
140 *m_pPrev
; // previous one
142 DECLARE_NO_COPY_CLASS(wxFileConfigLineList
)
145 // ----------------------------------------------------------------------------
146 // wxFileConfigEntry: a name/value pair
147 // ----------------------------------------------------------------------------
149 class wxFileConfigEntry
152 wxFileConfigGroup
*m_pParent
; // group that contains us
154 wxString m_strName
, // entry name
156 bool m_bImmutable
:1, // can be overriden locally?
157 m_bHasValue
:1; // set after first call to SetValue()
159 int m_nLine
; // used if m_pLine == NULL only
161 // pointer to our line in the linked list or NULL if it was found in global
162 // file (which we don't modify)
163 wxFileConfigLineList
*m_pLine
;
166 wxFileConfigEntry(wxFileConfigGroup
*pParent
,
167 const wxString
& strName
, int nLine
);
170 const wxString
& Name() const { return m_strName
; }
171 const wxString
& Value() const { return m_strValue
; }
172 wxFileConfigGroup
*Group() const { return m_pParent
; }
173 bool IsImmutable() const { return m_bImmutable
; }
174 bool IsLocal() const { return m_pLine
!= 0; }
175 int Line() const { return m_nLine
; }
176 wxFileConfigLineList
*
177 GetLine() const { return m_pLine
; }
179 // modify entry attributes
180 void SetValue(const wxString
& strValue
, bool bUser
= true);
181 void SetLine(wxFileConfigLineList
*pLine
);
183 DECLARE_NO_COPY_CLASS(wxFileConfigEntry
)
186 // ----------------------------------------------------------------------------
187 // wxFileConfigGroup: container of entries and other groups
188 // ----------------------------------------------------------------------------
190 class wxFileConfigGroup
193 wxFileConfig
*m_pConfig
; // config object we belong to
194 wxFileConfigGroup
*m_pParent
; // parent group (NULL for root group)
195 ArrayEntries m_aEntries
; // entries in this group
196 ArrayGroups m_aSubgroups
; // subgroups
197 wxString m_strName
; // group's name
198 wxFileConfigLineList
*m_pLine
; // pointer to our line in the linked list
199 wxFileConfigEntry
*m_pLastEntry
; // last entry/subgroup of this group in the
200 wxFileConfigGroup
*m_pLastGroup
; // local file (we insert new ones after it)
202 // DeleteSubgroupByName helper
203 bool DeleteSubgroup(wxFileConfigGroup
*pGroup
);
206 void UpdateGroupAndSubgroupsLines();
210 wxFileConfigGroup(wxFileConfigGroup
*pParent
, const wxString
& strName
, wxFileConfig
*);
212 // dtor deletes all entries and subgroups also
213 ~wxFileConfigGroup();
216 const wxString
& Name() const { return m_strName
; }
217 wxFileConfigGroup
*Parent() const { return m_pParent
; }
218 wxFileConfig
*Config() const { return m_pConfig
; }
220 const ArrayEntries
& Entries() const { return m_aEntries
; }
221 const ArrayGroups
& Groups() const { return m_aSubgroups
; }
222 bool IsEmpty() const { return Entries().IsEmpty() && Groups().IsEmpty(); }
224 // find entry/subgroup (NULL if not found)
225 wxFileConfigGroup
*FindSubgroup(const wxString
& name
) const;
226 wxFileConfigEntry
*FindEntry (const wxString
& name
) const;
228 // delete entry/subgroup, return false if doesn't exist
229 bool DeleteSubgroupByName(const wxString
& name
);
230 bool DeleteEntry(const wxString
& name
);
232 // create new entry/subgroup returning pointer to newly created element
233 wxFileConfigGroup
*AddSubgroup(const wxString
& strName
);
234 wxFileConfigEntry
*AddEntry (const wxString
& strName
, int nLine
= wxNOT_FOUND
);
236 void SetLine(wxFileConfigLineList
*pLine
);
238 // rename: no checks are done to ensure that the name is unique!
239 void Rename(const wxString
& newName
);
242 wxString
GetFullName() const;
244 // get the last line belonging to an entry/subgroup of this group
245 wxFileConfigLineList
*GetGroupLine(); // line which contains [group]
246 wxFileConfigLineList
*GetLastEntryLine(); // after which our subgroups start
247 wxFileConfigLineList
*GetLastGroupLine(); // after which the next group starts
249 // called by entries/subgroups when they're created/deleted
250 void SetLastEntry(wxFileConfigEntry
*pEntry
);
251 void SetLastGroup(wxFileConfigGroup
*pGroup
)
252 { m_pLastGroup
= pGroup
; }
254 DECLARE_NO_COPY_CLASS(wxFileConfigGroup
)
257 // ============================================================================
259 // ============================================================================
261 // ----------------------------------------------------------------------------
263 // ----------------------------------------------------------------------------
265 // this function modifies in place the given wxFileName object if it doesn't
266 // already have an extension
268 // note that it's slightly misnamed under Mac as there it doesn't add an
269 // extension but modifies the file name instead, so you shouldn't suppose that
270 // fn.HasExt() is true after it returns
271 static void AddConfFileExtIfNeeded(wxFileName
& fn
)
275 #if defined( __WXMAC__ )
276 fn
.SetName(fn
.GetName() + wxT(" Preferences"));
277 #elif defined( __UNIX__ )
278 fn
.SetExt(wxT(".conf"));
280 fn
.SetExt(wxT(".ini"));
285 wxString
wxFileConfig::GetGlobalDir()
287 return wxStandardPaths::Get().GetConfigDir();
290 wxString
wxFileConfig::GetLocalDir(int style
)
294 wxStandardPathsBase
& stdp
= wxStandardPaths::Get();
296 // it so happens that user data directory is a subdirectory of user config
297 // directory on all supported platforms, which explains why we use it here
298 return style
& wxCONFIG_USE_SUBDIR
? stdp
.GetUserDataDir()
299 : stdp
.GetUserConfigDir();
302 wxFileName
wxFileConfig::GetGlobalFile(const wxString
& szFile
)
304 wxFileName
fn(GetGlobalDir(), szFile
);
306 AddConfFileExtIfNeeded(fn
);
311 wxFileName
wxFileConfig::GetLocalFile(const wxString
& szFile
, int style
)
313 wxFileName
fn(GetLocalDir(style
), szFile
);
316 if ( !(style
& wxCONFIG_USE_SUBDIR
) )
318 // dot-files under Unix start with, well, a dot (but OTOH they usually
319 // don't have any specific extension)
320 fn
.SetName(wxT('.') + fn
.GetName());
322 else // we do append ".conf" extension to config files in subdirectories
325 AddConfFileExtIfNeeded(fn
);
331 // ----------------------------------------------------------------------------
333 // ----------------------------------------------------------------------------
334 IMPLEMENT_ABSTRACT_CLASS(wxFileConfig
, wxConfigBase
)
336 void wxFileConfig::Init()
339 m_pRootGroup
= new wxFileConfigGroup(NULL
, wxEmptyString
, this);
344 // It's not an error if (one of the) file(s) doesn't exist.
346 // parse the global file
347 if ( m_fnGlobalFile
.IsOk() && m_fnGlobalFile
.FileExists() )
349 wxTextFile
fileGlobal(m_fnGlobalFile
.GetFullPath());
351 if ( fileGlobal
.Open(*m_conv
/*ignored in ANSI build*/) )
353 Parse(fileGlobal
, false /* global */);
358 wxLogWarning(_("can't open global configuration file '%s'."), m_fnGlobalFile
.GetFullPath().c_str());
362 // parse the local file
363 if ( m_fnLocalFile
.IsOk() && m_fnLocalFile
.FileExists() )
365 wxTextFile
fileLocal(m_fnLocalFile
.GetFullPath());
366 if ( fileLocal
.Open(*m_conv
/*ignored in ANSI build*/) )
368 Parse(fileLocal
, true /* local */);
373 wxLogWarning(_("can't open user configuration file '%s'."), m_fnLocalFile
.GetFullPath().c_str() );
380 // constructor supports creation of wxFileConfig objects of any type
381 wxFileConfig::wxFileConfig(const wxString
& appName
, const wxString
& vendorName
,
382 const wxString
& strLocal
, const wxString
& strGlobal
,
384 const wxMBConv
& conv
)
385 : wxConfigBase(::GetAppName(appName
), vendorName
,
388 m_fnLocalFile(strLocal
),
389 m_fnGlobalFile(strGlobal
),
392 // Make up names for files if empty
393 if ( !m_fnLocalFile
.IsOk() && (style
& wxCONFIG_USE_LOCAL_FILE
) )
394 m_fnLocalFile
= GetLocalFile(GetAppName(), style
);
396 if ( !m_fnGlobalFile
.IsOk() && (style
& wxCONFIG_USE_GLOBAL_FILE
) )
397 m_fnGlobalFile
= GetGlobalFile(GetAppName());
399 // Check if styles are not supplied, but filenames are, in which case
400 // add the correct styles.
401 if ( m_fnLocalFile
.IsOk() )
402 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
404 if ( m_fnGlobalFile
.IsOk() )
405 SetStyle(GetStyle() | wxCONFIG_USE_GLOBAL_FILE
);
407 // if the path is not absolute, prepend the standard directory to it
408 // unless explicitly asked not to
409 if ( !(style
& wxCONFIG_USE_RELATIVE_PATH
) )
411 if ( m_fnLocalFile
.IsOk() )
412 m_fnLocalFile
.MakeAbsolute(GetLocalDir(style
));
414 if ( m_fnGlobalFile
.IsOk() )
415 m_fnGlobalFile
.MakeAbsolute(GetGlobalDir());
425 wxFileConfig::wxFileConfig(wxInputStream
&inStream
, const wxMBConv
& conv
)
426 : m_conv(conv
.Clone())
428 // always local_file when this constructor is called (?)
429 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
432 m_pRootGroup
= new wxFileConfigGroup(NULL
, wxEmptyString
, this);
437 // read the entire stream contents in memory
440 static const size_t chunkLen
= 1024;
442 wxMemoryBuffer
buf(chunkLen
);
445 inStream
.Read(buf
.GetAppendBuf(chunkLen
), chunkLen
);
446 buf
.UngetAppendBuf(inStream
.LastRead());
448 const wxStreamError err
= inStream
.GetLastError();
450 if ( err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
)
452 wxLogError(_("Error reading config options."));
456 while ( !inStream
.Eof() );
460 str
= conv
.cMB2WC((char *)buf
.GetData(), buf
.GetDataLen(), &len
);
461 if ( !len
&& buf
.GetDataLen() )
463 wxLogError(_("Failed to read config options."));
465 #else // !wxUSE_UNICODE
466 // no need for conversion
467 str
.assign((char *)buf
.GetData(), buf
.GetDataLen());
468 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
472 // translate everything to the current (platform-dependent) line
473 // termination character
474 str
= wxTextBuffer::Translate(str
);
476 wxMemoryText memText
;
478 // Now we can add the text to the memory text. To do this we extract line
479 // by line from the translated string, until we've reached the end.
481 // VZ: all this is horribly inefficient, we should do the translation on
482 // the fly in one pass saving both memory and time (TODO)
484 const wxChar
*pEOL
= wxTextBuffer::GetEOL(wxTextBuffer::typeDefault
);
485 const size_t EOLLen
= wxStrlen(pEOL
);
487 int posLineStart
= str
.Find(pEOL
);
488 while ( posLineStart
!= -1 )
490 wxString
line(str
.Left(posLineStart
));
492 memText
.AddLine(line
);
494 str
= str
.Mid(posLineStart
+ EOLLen
);
496 posLineStart
= str
.Find(pEOL
);
499 // also add whatever we have left in the translated string.
501 memText
.AddLine(str
);
503 // Finally we can parse it all.
504 Parse(memText
, true /* local */);
510 #endif // wxUSE_STREAMS
512 void wxFileConfig::CleanUp()
516 wxFileConfigLineList
*pCur
= m_linesHead
;
517 while ( pCur
!= NULL
) {
518 wxFileConfigLineList
*pNext
= pCur
->Next();
524 wxFileConfig::~wxFileConfig()
533 // ----------------------------------------------------------------------------
534 // parse a config file
535 // ----------------------------------------------------------------------------
537 void wxFileConfig::Parse(const wxTextBuffer
& buffer
, bool bLocal
)
540 size_t nLineCount
= buffer
.GetLineCount();
542 for ( size_t n
= 0; n
< nLineCount
; n
++ )
544 wxString strLine
= buffer
[n
];
545 // FIXME-UTF8: rewrite using iterators, without this buffer
546 wxWxCharBuffer
buf(strLine
.c_str());
547 const wxChar
*pStart
;
550 // add the line to linked list
553 LineListAppend(strLine
);
555 // let the root group have its start line as well
558 m_pCurrentGroup
->SetLine(m_linesTail
);
563 // skip leading spaces
564 for ( pStart
= buf
; wxIsspace(*pStart
); pStart
++ )
567 // skip blank/comment lines
568 if ( *pStart
== wxT('\0')|| *pStart
== wxT(';') || *pStart
== wxT('#') )
571 if ( *pStart
== wxT('[') ) { // a new group
574 while ( *++pEnd
!= wxT(']') ) {
575 if ( *pEnd
== wxT('\\') ) {
576 // the next char is escaped, so skip it even if it is ']'
580 if ( *pEnd
== wxT('\n') || *pEnd
== wxT('\0') ) {
581 // we reached the end of line, break out of the loop
586 if ( *pEnd
!= wxT(']') ) {
587 wxLogError(_("file '%s': unexpected character %c at line %d."),
588 buffer
.GetName(), *pEnd
, n
+ 1);
589 continue; // skip this line
592 // group name here is always considered as abs path
595 strGroup
<< wxCONFIG_PATH_SEPARATOR
596 << FilterInEntryName(wxString(pStart
, pEnd
- pStart
));
598 // will create it if doesn't yet exist
603 if ( m_pCurrentGroup
->Parent() )
604 m_pCurrentGroup
->Parent()->SetLastGroup(m_pCurrentGroup
);
605 m_pCurrentGroup
->SetLine(m_linesTail
);
608 // check that there is nothing except comments left on this line
610 while ( *++pEnd
!= wxT('\0') && bCont
) {
619 // ignore whitespace ('\n' impossible here)
623 wxLogWarning(_("file '%s', line %d: '%s' ignored after group header."),
624 buffer
.GetName(), n
+ 1, pEnd
);
631 while ( *pEnd
&& *pEnd
!= wxT('=') /* && !wxIsspace(*pEnd)*/ ) {
632 if ( *pEnd
== wxT('\\') ) {
633 // next character may be space or not - still take it because it's
634 // quoted (unless there is nothing)
637 // the error message will be given below anyhow
645 wxString
strKey(FilterInEntryName(wxString(pStart
, pEnd
).Trim()));
648 while ( wxIsspace(*pEnd
) )
651 if ( *pEnd
++ != wxT('=') ) {
652 wxLogError(_("file '%s', line %d: '=' expected."),
653 buffer
.GetName(), n
+ 1);
656 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strKey
);
658 if ( pEntry
== NULL
) {
660 pEntry
= m_pCurrentGroup
->AddEntry(strKey
, n
);
663 if ( bLocal
&& pEntry
->IsImmutable() ) {
664 // immutable keys can't be changed by user
665 wxLogWarning(_("file '%s', line %d: value for immutable key '%s' ignored."),
666 buffer
.GetName(), n
+ 1, strKey
.c_str());
669 // the condition below catches the cases (a) and (b) but not (c):
670 // (a) global key found second time in global file
671 // (b) key found second (or more) time in local file
672 // (c) key from global file now found in local one
673 // which is exactly what we want.
674 else if ( !bLocal
|| pEntry
->IsLocal() ) {
675 wxLogWarning(_("file '%s', line %d: key '%s' was first found at line %d."),
676 buffer
.GetName(), n
+ 1, strKey
.c_str(), pEntry
->Line());
682 pEntry
->SetLine(m_linesTail
);
685 while ( wxIsspace(*pEnd
) )
688 wxString value
= pEnd
;
689 if ( !(GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS
) )
690 value
= FilterInValue(value
);
692 pEntry
->SetValue(value
, false);
698 // ----------------------------------------------------------------------------
700 // ----------------------------------------------------------------------------
702 void wxFileConfig::SetRootPath()
705 m_pCurrentGroup
= m_pRootGroup
;
709 wxFileConfig::DoSetPath(const wxString
& strPath
, bool createMissingComponents
)
711 wxArrayString aParts
;
713 if ( strPath
.empty() ) {
718 if ( strPath
[0] == wxCONFIG_PATH_SEPARATOR
) {
720 wxSplitPath(aParts
, strPath
);
723 // relative path, combine with current one
724 wxString strFullPath
= m_strPath
;
725 strFullPath
<< wxCONFIG_PATH_SEPARATOR
<< strPath
;
726 wxSplitPath(aParts
, strFullPath
);
729 // change current group
731 m_pCurrentGroup
= m_pRootGroup
;
732 for ( n
= 0; n
< aParts
.GetCount(); n
++ ) {
733 wxFileConfigGroup
*pNextGroup
= m_pCurrentGroup
->FindSubgroup(aParts
[n
]);
734 if ( pNextGroup
== NULL
)
736 if ( !createMissingComponents
)
739 pNextGroup
= m_pCurrentGroup
->AddSubgroup(aParts
[n
]);
742 m_pCurrentGroup
= pNextGroup
;
745 // recombine path parts in one variable
747 for ( n
= 0; n
< aParts
.GetCount(); n
++ ) {
748 m_strPath
<< wxCONFIG_PATH_SEPARATOR
<< aParts
[n
];
754 void wxFileConfig::SetPath(const wxString
& strPath
)
756 DoSetPath(strPath
, true /* create missing path components */);
759 // ----------------------------------------------------------------------------
761 // ----------------------------------------------------------------------------
763 bool wxFileConfig::GetFirstGroup(wxString
& str
, long& lIndex
) const
766 return GetNextGroup(str
, lIndex
);
769 bool wxFileConfig::GetNextGroup (wxString
& str
, long& lIndex
) const
771 if ( size_t(lIndex
) < m_pCurrentGroup
->Groups().GetCount() ) {
772 str
= m_pCurrentGroup
->Groups()[(size_t)lIndex
++]->Name();
779 bool wxFileConfig::GetFirstEntry(wxString
& str
, long& lIndex
) const
782 return GetNextEntry(str
, lIndex
);
785 bool wxFileConfig::GetNextEntry (wxString
& str
, long& lIndex
) const
787 if ( size_t(lIndex
) < m_pCurrentGroup
->Entries().GetCount() ) {
788 str
= m_pCurrentGroup
->Entries()[(size_t)lIndex
++]->Name();
795 size_t wxFileConfig::GetNumberOfEntries(bool bRecursive
) const
797 size_t n
= m_pCurrentGroup
->Entries().GetCount();
799 wxFileConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
800 size_t nSubgroups
= m_pCurrentGroup
->Groups().GetCount();
801 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
802 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
803 n
+= GetNumberOfEntries(true);
804 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
811 size_t wxFileConfig::GetNumberOfGroups(bool bRecursive
) const
813 size_t n
= m_pCurrentGroup
->Groups().GetCount();
815 wxFileConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
816 size_t nSubgroups
= m_pCurrentGroup
->Groups().GetCount();
817 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
818 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
819 n
+= GetNumberOfGroups(true);
820 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
827 // ----------------------------------------------------------------------------
828 // tests for existence
829 // ----------------------------------------------------------------------------
831 bool wxFileConfig::HasGroup(const wxString
& strName
) const
833 // special case: DoSetPath("") does work as it's equivalent to DoSetPath("/")
834 // but there is no group with empty name so treat this separately
835 if ( strName
.empty() )
838 const wxString pathOld
= GetPath();
840 wxFileConfig
*self
= wx_const_cast(wxFileConfig
*, this);
842 rc
= self
->DoSetPath(strName
, false /* don't create missing components */);
844 self
->SetPath(pathOld
);
849 bool wxFileConfig::HasEntry(const wxString
& entry
) const
851 // path is the part before the last "/"
852 wxString path
= entry
.BeforeLast(wxCONFIG_PATH_SEPARATOR
);
854 // except in the special case of "/keyname" when there is nothing before "/"
855 if ( path
.empty() && *entry
.c_str() == wxCONFIG_PATH_SEPARATOR
)
857 path
= wxCONFIG_PATH_SEPARATOR
;
860 // change to the path of the entry if necessary and remember the old path
861 // to restore it later
863 wxFileConfig
* const self
= wx_const_cast(wxFileConfig
*, this);
867 if ( pathOld
.empty() )
868 pathOld
= wxCONFIG_PATH_SEPARATOR
;
870 if ( !self
->DoSetPath(path
, false /* don't create if doesn't exist */) )
876 // check if the entry exists in this group
877 const bool exists
= m_pCurrentGroup
->FindEntry(
878 entry
.AfterLast(wxCONFIG_PATH_SEPARATOR
)) != NULL
;
880 // restore the old path if we changed it above
881 if ( !pathOld
.empty() )
883 self
->SetPath(pathOld
);
889 // ----------------------------------------------------------------------------
891 // ----------------------------------------------------------------------------
893 bool wxFileConfig::DoReadString(const wxString
& key
, wxString
* pStr
) const
895 wxConfigPathChanger
path(this, key
);
897 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
898 if (pEntry
== NULL
) {
902 *pStr
= pEntry
->Value();
907 bool wxFileConfig::DoReadLong(const wxString
& key
, long *pl
) const
910 if ( !Read(key
, &str
) )
913 // extra spaces shouldn't prevent us from reading numeric values
916 return str
.ToLong(pl
);
919 bool wxFileConfig::DoWriteString(const wxString
& key
, const wxString
& szValue
)
921 wxConfigPathChanger
path(this, key
);
922 wxString strName
= path
.Name();
924 wxLogTrace( FILECONF_TRACE_MASK
,
925 _T(" Writing String '%s' = '%s' to Group '%s'"),
930 if ( strName
.empty() )
932 // setting the value of a group is an error
934 wxASSERT_MSG( szValue
.empty(), wxT("can't set value of a group!") );
936 // ... except if it's empty in which case it's a way to force it's creation
938 wxLogTrace( FILECONF_TRACE_MASK
,
939 _T(" Creating group %s"),
940 m_pCurrentGroup
->Name().c_str() );
944 // this will add a line for this group if it didn't have it before
946 (void)m_pCurrentGroup
->GetGroupLine();
950 // writing an entry check that the name is reasonable
951 if ( strName
[0u] == wxCONFIG_IMMUTABLE_PREFIX
)
953 wxLogError( _("Config entry name cannot start with '%c'."),
954 wxCONFIG_IMMUTABLE_PREFIX
);
958 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strName
);
962 wxLogTrace( FILECONF_TRACE_MASK
,
963 _T(" Adding Entry %s"),
965 pEntry
= m_pCurrentGroup
->AddEntry(strName
);
968 wxLogTrace( FILECONF_TRACE_MASK
,
969 _T(" Setting value %s"),
971 pEntry
->SetValue(szValue
);
979 bool wxFileConfig::DoWriteLong(const wxString
& key
, long lValue
)
981 return Write(key
, wxString::Format(_T("%ld"), lValue
));
984 bool wxFileConfig::Flush(bool /* bCurrentOnly */)
986 if ( !IsDirty() || !m_fnLocalFile
.GetFullPath() )
989 // set the umask if needed
990 wxCHANGE_UMASK(m_umask
);
992 wxTempFile
file(m_fnLocalFile
.GetFullPath());
994 if ( !file
.IsOpened() )
996 wxLogError(_("can't open user configuration file."));
1000 // write all strings to file
1002 filetext
.reserve(4096);
1003 for ( wxFileConfigLineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() )
1005 filetext
<< p
->Text() << wxTextFile::GetEOL();
1008 if ( !file
.Write(filetext
, *m_conv
) )
1010 wxLogError(_("can't write user configuration file."));
1014 if ( !file
.Commit() )
1016 wxLogError(_("Failed to update user configuration file."));
1023 #if defined(__WXMAC__)
1024 m_fnLocalFile
.MacSetTypeAndCreator('TEXT', 'ttxt');
1032 bool wxFileConfig::Save(wxOutputStream
& os
, const wxMBConv
& conv
)
1034 // save unconditionally, even if not dirty
1035 for ( wxFileConfigLineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() )
1037 wxString line
= p
->Text();
1038 line
+= wxTextFile::GetEOL();
1040 wxCharBuffer
buf(line
.mb_str(conv
));
1041 if ( !os
.Write(buf
, strlen(buf
)) )
1043 wxLogError(_("Error saving user configuration data."));
1054 #endif // wxUSE_STREAMS
1056 // ----------------------------------------------------------------------------
1057 // renaming groups/entries
1058 // ----------------------------------------------------------------------------
1060 bool wxFileConfig::RenameEntry(const wxString
& oldName
,
1061 const wxString
& newName
)
1063 wxASSERT_MSG( oldName
.find(wxCONFIG_PATH_SEPARATOR
) == wxString::npos
,
1064 _T("RenameEntry(): paths are not supported") );
1066 // check that the entry exists
1067 wxFileConfigEntry
*oldEntry
= m_pCurrentGroup
->FindEntry(oldName
);
1071 // check that the new entry doesn't already exist
1072 if ( m_pCurrentGroup
->FindEntry(newName
) )
1075 // delete the old entry, create the new one
1076 wxString value
= oldEntry
->Value();
1077 if ( !m_pCurrentGroup
->DeleteEntry(oldName
) )
1082 wxFileConfigEntry
*newEntry
= m_pCurrentGroup
->AddEntry(newName
);
1083 newEntry
->SetValue(value
);
1088 bool wxFileConfig::RenameGroup(const wxString
& oldName
,
1089 const wxString
& newName
)
1091 // check that the group exists
1092 wxFileConfigGroup
*group
= m_pCurrentGroup
->FindSubgroup(oldName
);
1096 // check that the new group doesn't already exist
1097 if ( m_pCurrentGroup
->FindSubgroup(newName
) )
1100 group
->Rename(newName
);
1107 // ----------------------------------------------------------------------------
1108 // delete groups/entries
1109 // ----------------------------------------------------------------------------
1111 bool wxFileConfig::DeleteEntry(const wxString
& key
, bool bGroupIfEmptyAlso
)
1113 wxConfigPathChanger
path(this, key
);
1115 if ( !m_pCurrentGroup
->DeleteEntry(path
.Name()) )
1120 if ( bGroupIfEmptyAlso
&& m_pCurrentGroup
->IsEmpty() ) {
1121 if ( m_pCurrentGroup
!= m_pRootGroup
) {
1122 wxFileConfigGroup
*pGroup
= m_pCurrentGroup
;
1123 SetPath(wxT("..")); // changes m_pCurrentGroup!
1124 m_pCurrentGroup
->DeleteSubgroupByName(pGroup
->Name());
1126 //else: never delete the root group
1132 bool wxFileConfig::DeleteGroup(const wxString
& key
)
1134 wxConfigPathChanger
path(this, RemoveTrailingSeparator(key
));
1136 if ( !m_pCurrentGroup
->DeleteSubgroupByName(path
.Name()) )
1139 path
.UpdateIfDeleted();
1146 bool wxFileConfig::DeleteAll()
1150 if ( m_fnLocalFile
.IsOk() )
1152 if ( m_fnLocalFile
.FileExists() &&
1153 !wxRemoveFile(m_fnLocalFile
.GetFullPath()) )
1155 wxLogSysError(_("can't delete user configuration file '%s'"),
1156 m_fnLocalFile
.GetFullPath().c_str());
1166 // ----------------------------------------------------------------------------
1167 // linked list functions
1168 // ----------------------------------------------------------------------------
1170 // append a new line to the end of the list
1172 wxFileConfigLineList
*wxFileConfig::LineListAppend(const wxString
& str
)
1174 wxLogTrace( FILECONF_TRACE_MASK
,
1175 _T(" ** Adding Line '%s'"),
1177 wxLogTrace( FILECONF_TRACE_MASK
,
1179 ((m_linesHead
) ? (const wxChar
*)m_linesHead
->Text().c_str()
1181 wxLogTrace( FILECONF_TRACE_MASK
,
1183 ((m_linesTail
) ? (const wxChar
*)m_linesTail
->Text().c_str()
1186 wxFileConfigLineList
*pLine
= new wxFileConfigLineList(str
);
1188 if ( m_linesTail
== NULL
)
1191 m_linesHead
= pLine
;
1196 m_linesTail
->SetNext(pLine
);
1197 pLine
->SetPrev(m_linesTail
);
1200 m_linesTail
= pLine
;
1202 wxLogTrace( FILECONF_TRACE_MASK
,
1204 ((m_linesHead
) ? (const wxChar
*)m_linesHead
->Text().c_str()
1206 wxLogTrace( FILECONF_TRACE_MASK
,
1208 ((m_linesTail
) ? (const wxChar
*)m_linesTail
->Text().c_str()
1214 // insert a new line after the given one or in the very beginning if !pLine
1215 wxFileConfigLineList
*wxFileConfig::LineListInsert(const wxString
& str
,
1216 wxFileConfigLineList
*pLine
)
1218 wxLogTrace( FILECONF_TRACE_MASK
,
1219 _T(" ** Inserting Line '%s' after '%s'"),
1221 ((pLine
) ? (const wxChar
*)pLine
->Text().c_str()
1223 wxLogTrace( FILECONF_TRACE_MASK
,
1225 ((m_linesHead
) ? (const wxChar
*)m_linesHead
->Text().c_str()
1227 wxLogTrace( FILECONF_TRACE_MASK
,
1229 ((m_linesTail
) ? (const wxChar
*)m_linesTail
->Text().c_str()
1232 if ( pLine
== m_linesTail
)
1233 return LineListAppend(str
);
1235 wxFileConfigLineList
*pNewLine
= new wxFileConfigLineList(str
);
1236 if ( pLine
== NULL
)
1238 // prepend to the list
1239 pNewLine
->SetNext(m_linesHead
);
1240 m_linesHead
->SetPrev(pNewLine
);
1241 m_linesHead
= pNewLine
;
1245 // insert before pLine
1246 wxFileConfigLineList
*pNext
= pLine
->Next();
1247 pNewLine
->SetNext(pNext
);
1248 pNewLine
->SetPrev(pLine
);
1249 pNext
->SetPrev(pNewLine
);
1250 pLine
->SetNext(pNewLine
);
1253 wxLogTrace( FILECONF_TRACE_MASK
,
1255 ((m_linesHead
) ? (const wxChar
*)m_linesHead
->Text().c_str()
1257 wxLogTrace( FILECONF_TRACE_MASK
,
1259 ((m_linesTail
) ? (const wxChar
*)m_linesTail
->Text().c_str()
1265 void wxFileConfig::LineListRemove(wxFileConfigLineList
*pLine
)
1267 wxLogTrace( FILECONF_TRACE_MASK
,
1268 _T(" ** Removing Line '%s'"),
1269 pLine
->Text().c_str() );
1270 wxLogTrace( FILECONF_TRACE_MASK
,
1272 ((m_linesHead
) ? (const wxChar
*)m_linesHead
->Text().c_str()
1274 wxLogTrace( FILECONF_TRACE_MASK
,
1276 ((m_linesTail
) ? (const wxChar
*)m_linesTail
->Text().c_str()
1279 wxFileConfigLineList
*pPrev
= pLine
->Prev(),
1280 *pNext
= pLine
->Next();
1284 if ( pPrev
== NULL
)
1285 m_linesHead
= pNext
;
1287 pPrev
->SetNext(pNext
);
1291 if ( pNext
== NULL
)
1292 m_linesTail
= pPrev
;
1294 pNext
->SetPrev(pPrev
);
1296 if ( m_pRootGroup
->GetGroupLine() == pLine
)
1297 m_pRootGroup
->SetLine(m_linesHead
);
1299 wxLogTrace( FILECONF_TRACE_MASK
,
1301 ((m_linesHead
) ? (const wxChar
*)m_linesHead
->Text().c_str()
1303 wxLogTrace( FILECONF_TRACE_MASK
,
1305 ((m_linesTail
) ? (const wxChar
*)m_linesTail
->Text().c_str()
1311 bool wxFileConfig::LineListIsEmpty()
1313 return m_linesHead
== NULL
;
1316 // ============================================================================
1317 // wxFileConfig::wxFileConfigGroup
1318 // ============================================================================
1320 // ----------------------------------------------------------------------------
1322 // ----------------------------------------------------------------------------
1325 wxFileConfigGroup::wxFileConfigGroup(wxFileConfigGroup
*pParent
,
1326 const wxString
& strName
,
1327 wxFileConfig
*pConfig
)
1328 : m_aEntries(CompareEntries
),
1329 m_aSubgroups(CompareGroups
),
1332 m_pConfig
= pConfig
;
1333 m_pParent
= pParent
;
1336 m_pLastEntry
= NULL
;
1337 m_pLastGroup
= NULL
;
1340 // dtor deletes all children
1341 wxFileConfigGroup::~wxFileConfigGroup()
1344 size_t n
, nCount
= m_aEntries
.GetCount();
1345 for ( n
= 0; n
< nCount
; n
++ )
1346 delete m_aEntries
[n
];
1349 nCount
= m_aSubgroups
.GetCount();
1350 for ( n
= 0; n
< nCount
; n
++ )
1351 delete m_aSubgroups
[n
];
1354 // ----------------------------------------------------------------------------
1356 // ----------------------------------------------------------------------------
1358 void wxFileConfigGroup::SetLine(wxFileConfigLineList
*pLine
)
1360 // for a normal (i.e. not root) group this method shouldn't be called twice
1361 // unless we are resetting the line
1362 wxASSERT_MSG( !m_pParent
|| !m_pLine
|| !pLine
,
1363 _T("changing line for a non-root group?") );
1369 This is a bit complicated, so let me explain it in details. All lines that
1370 were read from the local file (the only one we will ever modify) are stored
1371 in a (doubly) linked list. Our problem is to know at which position in this
1372 list should we insert the new entries/subgroups. To solve it we keep three
1373 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1375 m_pLine points to the line containing "[group_name]"
1376 m_pLastEntry points to the last entry of this group in the local file.
1377 m_pLastGroup subgroup
1379 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1380 from the local file, the corresponding variable is set. However, if the group
1381 was read from the global file and then modified or created by the application
1382 these variables are still NULL and we need to create the corresponding lines.
1383 See the following functions (and comments preceding them) for the details of
1386 Also, when our last entry/group are deleted we need to find the new last
1387 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1388 of lines until it either founds an entry/subgroup (and this is the new last
1389 element) or the m_pLine of the group, in which case there are no more entries
1390 (or subgroups) left and m_pLast<element> becomes NULL.
1392 NB: This last problem could be avoided for entries if we added new entries
1393 immediately after m_pLine, but in this case the entries would appear
1394 backwards in the config file (OTOH, it's not that important) and as we
1395 would still need to do it for the subgroups the code wouldn't have been
1396 significantly less complicated.
1399 // Return the line which contains "[our name]". If we're still not in the list,
1400 // add our line to it immediately after the last line of our parent group if we
1401 // have it or in the very beginning if we're the root group.
1402 wxFileConfigLineList
*wxFileConfigGroup::GetGroupLine()
1404 wxLogTrace( FILECONF_TRACE_MASK
,
1405 _T(" GetGroupLine() for Group '%s'"),
1410 wxLogTrace( FILECONF_TRACE_MASK
,
1411 _T(" Getting Line item pointer") );
1413 wxFileConfigGroup
*pParent
= Parent();
1415 // this group wasn't present in local config file, add it now
1418 wxLogTrace( FILECONF_TRACE_MASK
,
1419 _T(" checking parent '%s'"),
1420 pParent
->Name().c_str() );
1422 wxString strFullName
;
1424 // add 1 to the name because we don't want to start with '/'
1425 strFullName
<< wxT("[")
1426 << FilterOutEntryName(GetFullName().c_str() + 1)
1428 m_pLine
= m_pConfig
->LineListInsert(strFullName
,
1429 pParent
->GetLastGroupLine());
1430 pParent
->SetLastGroup(this); // we're surely after all the others
1432 //else: this is the root group and so we return NULL because we don't
1433 // have any group line
1439 // Return the last line belonging to the subgroups of this group (after which
1440 // we can add a new subgroup), if we don't have any subgroups or entries our
1441 // last line is the group line (m_pLine) itself.
1442 wxFileConfigLineList
*wxFileConfigGroup::GetLastGroupLine()
1444 // if we have any subgroups, our last line is the last line of the last
1448 wxFileConfigLineList
*pLine
= m_pLastGroup
->GetLastGroupLine();
1450 wxASSERT_MSG( pLine
, _T("last group must have !NULL associated line") );
1455 // no subgroups, so the last line is the line of thelast entry (if any)
1456 return GetLastEntryLine();
1459 // return the last line belonging to the entries of this group (after which
1460 // we can add a new entry), if we don't have any entries we will add the new
1461 // one immediately after the group line itself.
1462 wxFileConfigLineList
*wxFileConfigGroup::GetLastEntryLine()
1464 wxLogTrace( FILECONF_TRACE_MASK
,
1465 _T(" GetLastEntryLine() for Group '%s'"),
1470 wxFileConfigLineList
*pLine
= m_pLastEntry
->GetLine();
1472 wxASSERT_MSG( pLine
, _T("last entry must have !NULL associated line") );
1477 // no entries: insert after the group header, if any
1478 return GetGroupLine();
1481 void wxFileConfigGroup::SetLastEntry(wxFileConfigEntry
*pEntry
)
1483 m_pLastEntry
= pEntry
;
1487 // the only situation in which a group without its own line can have
1488 // an entry is when the first entry is added to the initially empty
1489 // root pseudo-group
1490 wxASSERT_MSG( !m_pParent
, _T("unexpected for non root group") );
1492 // let the group know that it does have a line in the file now
1493 m_pLine
= pEntry
->GetLine();
1497 // ----------------------------------------------------------------------------
1499 // ----------------------------------------------------------------------------
1501 void wxFileConfigGroup::UpdateGroupAndSubgroupsLines()
1503 // update the line of this group
1504 wxFileConfigLineList
*line
= GetGroupLine();
1505 wxCHECK_RET( line
, _T("a non root group must have a corresponding line!") );
1507 // +1: skip the leading '/'
1508 line
->SetText(wxString::Format(_T("[%s]"), GetFullName().c_str() + 1));
1511 // also update all subgroups as they have this groups name in their lines
1512 const size_t nCount
= m_aSubgroups
.GetCount();
1513 for ( size_t n
= 0; n
< nCount
; n
++ )
1515 m_aSubgroups
[n
]->UpdateGroupAndSubgroupsLines();
1519 void wxFileConfigGroup::Rename(const wxString
& newName
)
1521 wxCHECK_RET( m_pParent
, _T("the root group can't be renamed") );
1523 if ( newName
== m_strName
)
1526 // we need to remove the group from the parent and it back under the new
1527 // name to keep the parents array of subgroups alphabetically sorted
1528 m_pParent
->m_aSubgroups
.Remove(this);
1530 m_strName
= newName
;
1532 m_pParent
->m_aSubgroups
.Add(this);
1534 // update the group lines recursively
1535 UpdateGroupAndSubgroupsLines();
1538 wxString
wxFileConfigGroup::GetFullName() const
1542 fullname
= Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR
+ Name();
1547 // ----------------------------------------------------------------------------
1549 // ----------------------------------------------------------------------------
1551 // use binary search because the array is sorted
1553 wxFileConfigGroup::FindEntry(const wxString
& name
) const
1557 hi
= m_aEntries
.GetCount();
1559 wxFileConfigEntry
*pEntry
;
1563 pEntry
= m_aEntries
[i
];
1565 #if wxCONFIG_CASE_SENSITIVE
1566 res
= pEntry
->Name().compare(name
);
1568 res
= pEntry
->Name().CmpNoCase(name
);
1583 wxFileConfigGroup::FindSubgroup(const wxString
& name
) const
1587 hi
= m_aSubgroups
.GetCount();
1589 wxFileConfigGroup
*pGroup
;
1593 pGroup
= m_aSubgroups
[i
];
1595 #if wxCONFIG_CASE_SENSITIVE
1596 res
= pGroup
->Name().compare(name
);
1598 res
= pGroup
->Name().CmpNoCase(name
);
1612 // ----------------------------------------------------------------------------
1613 // create a new item
1614 // ----------------------------------------------------------------------------
1616 // create a new entry and add it to the current group
1617 wxFileConfigEntry
*wxFileConfigGroup::AddEntry(const wxString
& strName
, int nLine
)
1619 wxASSERT( FindEntry(strName
) == 0 );
1621 wxFileConfigEntry
*pEntry
= new wxFileConfigEntry(this, strName
, nLine
);
1623 m_aEntries
.Add(pEntry
);
1627 // create a new group and add it to the current group
1628 wxFileConfigGroup
*wxFileConfigGroup::AddSubgroup(const wxString
& strName
)
1630 wxASSERT( FindSubgroup(strName
) == 0 );
1632 wxFileConfigGroup
*pGroup
= new wxFileConfigGroup(this, strName
, m_pConfig
);
1634 m_aSubgroups
.Add(pGroup
);
1638 // ----------------------------------------------------------------------------
1640 // ----------------------------------------------------------------------------
1643 The delete operations are _very_ slow if we delete the last item of this
1644 group (see comments before GetXXXLineXXX functions for more details),
1645 so it's much better to start with the first entry/group if we want to
1646 delete several of them.
1649 bool wxFileConfigGroup::DeleteSubgroupByName(const wxString
& name
)
1651 wxFileConfigGroup
* const pGroup
= FindSubgroup(name
);
1653 return pGroup
? DeleteSubgroup(pGroup
) : false;
1656 // Delete the subgroup and remove all references to it from
1657 // other data structures.
1658 bool wxFileConfigGroup::DeleteSubgroup(wxFileConfigGroup
*pGroup
)
1660 wxCHECK_MSG( pGroup
, false, _T("deleting non existing group?") );
1662 wxLogTrace( FILECONF_TRACE_MASK
,
1663 _T("Deleting group '%s' from '%s'"),
1664 pGroup
->Name().c_str(),
1667 wxLogTrace( FILECONF_TRACE_MASK
,
1668 _T(" (m_pLine) = prev: %p, this %p, next %p"),
1669 m_pLine
? wx_static_cast(void*, m_pLine
->Prev()) : 0,
1670 wx_static_cast(void*, m_pLine
),
1671 m_pLine
? wx_static_cast(void*, m_pLine
->Next()) : 0 );
1672 wxLogTrace( FILECONF_TRACE_MASK
,
1674 m_pLine
? (const wxChar
*)m_pLine
->Text().c_str()
1677 // delete all entries...
1678 size_t nCount
= pGroup
->m_aEntries
.GetCount();
1680 wxLogTrace(FILECONF_TRACE_MASK
,
1681 _T("Removing %lu entries"), (unsigned long)nCount
);
1683 for ( size_t nEntry
= 0; nEntry
< nCount
; nEntry
++ )
1685 wxFileConfigLineList
*pLine
= pGroup
->m_aEntries
[nEntry
]->GetLine();
1689 wxLogTrace( FILECONF_TRACE_MASK
,
1691 pLine
->Text().c_str() );
1692 m_pConfig
->LineListRemove(pLine
);
1696 // ...and subgroups of this subgroup
1697 nCount
= pGroup
->m_aSubgroups
.GetCount();
1699 wxLogTrace( FILECONF_TRACE_MASK
,
1700 _T("Removing %lu subgroups"), (unsigned long)nCount
);
1702 for ( size_t nGroup
= 0; nGroup
< nCount
; nGroup
++ )
1704 pGroup
->DeleteSubgroup(pGroup
->m_aSubgroups
[0]);
1707 // and then finally the group itself
1708 wxFileConfigLineList
*pLine
= pGroup
->m_pLine
;
1711 wxLogTrace( FILECONF_TRACE_MASK
,
1712 _T(" Removing line for group '%s' : '%s'"),
1713 pGroup
->Name().c_str(),
1714 pLine
->Text().c_str() );
1715 wxLogTrace( FILECONF_TRACE_MASK
,
1716 _T(" Removing from group '%s' : '%s'"),
1718 ((m_pLine
) ? (const wxChar
*)m_pLine
->Text().c_str()
1721 // notice that we may do this test inside the previous "if"
1722 // because the last entry's line is surely !NULL
1723 if ( pGroup
== m_pLastGroup
)
1725 wxLogTrace( FILECONF_TRACE_MASK
,
1726 _T(" Removing last group") );
1728 // our last entry is being deleted, so find the last one which
1729 // stays by going back until we find a subgroup or reach the
1731 const size_t nSubgroups
= m_aSubgroups
.GetCount();
1733 m_pLastGroup
= NULL
;
1734 for ( wxFileConfigLineList
*pl
= pLine
->Prev();
1735 pl
&& !m_pLastGroup
;
1738 // does this line belong to our subgroup?
1739 for ( size_t n
= 0; n
< nSubgroups
; n
++ )
1741 // do _not_ call GetGroupLine! we don't want to add it to
1742 // the local file if it's not already there
1743 if ( m_aSubgroups
[n
]->m_pLine
== pl
)
1745 m_pLastGroup
= m_aSubgroups
[n
];
1750 if ( pl
== m_pLine
)
1755 m_pConfig
->LineListRemove(pLine
);
1759 wxLogTrace( FILECONF_TRACE_MASK
,
1760 _T(" No line entry for Group '%s'?"),
1761 pGroup
->Name().c_str() );
1764 m_aSubgroups
.Remove(pGroup
);
1770 bool wxFileConfigGroup::DeleteEntry(const wxString
& name
)
1772 wxFileConfigEntry
*pEntry
= FindEntry(name
);
1775 // entry doesn't exist, nothing to do
1779 wxFileConfigLineList
*pLine
= pEntry
->GetLine();
1780 if ( pLine
!= NULL
) {
1781 // notice that we may do this test inside the previous "if" because the
1782 // last entry's line is surely !NULL
1783 if ( pEntry
== m_pLastEntry
) {
1784 // our last entry is being deleted - find the last one which stays
1785 wxASSERT( m_pLine
!= NULL
); // if we have an entry with !NULL pLine...
1787 // go back until we find another entry or reach the group's line
1788 wxFileConfigEntry
*pNewLast
= NULL
;
1789 size_t n
, nEntries
= m_aEntries
.GetCount();
1790 wxFileConfigLineList
*pl
;
1791 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1792 // is it our subgroup?
1793 for ( n
= 0; (pNewLast
== NULL
) && (n
< nEntries
); n
++ ) {
1794 if ( m_aEntries
[n
]->GetLine() == m_pLine
)
1795 pNewLast
= m_aEntries
[n
];
1798 if ( pNewLast
!= NULL
) // found?
1802 if ( pl
== m_pLine
) {
1803 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1805 // we've reached the group line without finding any subgroups
1806 m_pLastEntry
= NULL
;
1809 m_pLastEntry
= pNewLast
;
1812 m_pConfig
->LineListRemove(pLine
);
1815 m_aEntries
.Remove(pEntry
);
1821 // ============================================================================
1822 // wxFileConfig::wxFileConfigEntry
1823 // ============================================================================
1825 // ----------------------------------------------------------------------------
1827 // ----------------------------------------------------------------------------
1828 wxFileConfigEntry::wxFileConfigEntry(wxFileConfigGroup
*pParent
,
1829 const wxString
& strName
,
1831 : m_strName(strName
)
1833 wxASSERT( !strName
.empty() );
1835 m_pParent
= pParent
;
1839 m_bHasValue
= false;
1841 m_bImmutable
= strName
[0] == wxCONFIG_IMMUTABLE_PREFIX
;
1843 m_strName
.erase(0, 1); // remove first character
1846 // ----------------------------------------------------------------------------
1848 // ----------------------------------------------------------------------------
1850 void wxFileConfigEntry::SetLine(wxFileConfigLineList
*pLine
)
1852 if ( m_pLine
!= NULL
) {
1853 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1854 Name().c_str(), m_pParent
->GetFullName().c_str());
1858 Group()->SetLastEntry(this);
1861 // second parameter is false if we read the value from file and prevents the
1862 // entry from being marked as 'dirty'
1863 void wxFileConfigEntry::SetValue(const wxString
& strValue
, bool bUser
)
1865 if ( bUser
&& IsImmutable() )
1867 wxLogWarning( _("attempt to change immutable key '%s' ignored."),
1872 // do nothing if it's the same value: but don't test for it if m_bHasValue
1873 // hadn't been set yet or we'd never write empty values to the file
1874 if ( m_bHasValue
&& strValue
== m_strValue
)
1878 m_strValue
= strValue
;
1882 wxString strValFiltered
;
1884 if ( Group()->Config()->GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS
)
1886 strValFiltered
= strValue
;
1889 strValFiltered
= FilterOutValue(strValue
);
1893 strLine
<< FilterOutEntryName(m_strName
) << wxT('=') << strValFiltered
;
1897 // entry was read from the local config file, just modify the line
1898 m_pLine
->SetText(strLine
);
1900 else // this entry didn't exist in the local file
1902 // add a new line to the file: note that line returned by
1903 // GetLastEntryLine() may be NULL if we're in the root group and it
1904 // doesn't have any entries yet, but this is ok as passing NULL
1905 // line to LineListInsert() means to prepend new line to the list
1906 wxFileConfigLineList
*line
= Group()->GetLastEntryLine();
1907 m_pLine
= Group()->Config()->LineListInsert(strLine
, line
);
1909 Group()->SetLastEntry(this);
1914 // ============================================================================
1916 // ============================================================================
1918 // ----------------------------------------------------------------------------
1919 // compare functions for array sorting
1920 // ----------------------------------------------------------------------------
1922 int CompareEntries(wxFileConfigEntry
*p1
, wxFileConfigEntry
*p2
)
1924 #if wxCONFIG_CASE_SENSITIVE
1925 return p1
->Name().compare(p2
->Name());
1927 return p1
->Name().CmpNoCase(p2
->Name());
1931 int CompareGroups(wxFileConfigGroup
*p1
, wxFileConfigGroup
*p2
)
1933 #if wxCONFIG_CASE_SENSITIVE
1934 return p1
->Name().compare(p2
->Name());
1936 return p1
->Name().CmpNoCase(p2
->Name());
1940 // ----------------------------------------------------------------------------
1942 // ----------------------------------------------------------------------------
1944 // undo FilterOutValue
1945 static wxString
FilterInValue(const wxString
& str
)
1948 strResult
.Alloc(str
.Len());
1950 bool bQuoted
= !str
.empty() && str
[0] == '"';
1952 for ( size_t n
= bQuoted
? 1 : 0; n
< str
.Len(); n
++ ) {
1953 if ( str
[n
] == wxT('\\') ) {
1954 switch ( str
[++n
].GetValue() ) {
1956 strResult
+= wxT('\n');
1960 strResult
+= wxT('\r');
1964 strResult
+= wxT('\t');
1968 strResult
+= wxT('\\');
1972 strResult
+= wxT('"');
1977 if ( str
[n
] != wxT('"') || !bQuoted
)
1978 strResult
+= str
[n
];
1979 else if ( n
!= str
.Len() - 1 ) {
1980 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1983 //else: it's the last quote of a quoted string, ok
1990 // quote the string before writing it to file
1991 static wxString
FilterOutValue(const wxString
& str
)
1997 strResult
.Alloc(str
.Len());
1999 // quoting is necessary to preserve spaces in the beginning of the string
2000 bool bQuote
= wxIsspace(str
[0]) || str
[0] == wxT('"');
2003 strResult
+= wxT('"');
2006 for ( size_t n
= 0; n
< str
.Len(); n
++ ) {
2007 switch ( str
[n
].GetValue() ) {
2029 //else: fall through
2032 strResult
+= str
[n
];
2033 continue; // nothing special to do
2036 // we get here only for special characters
2037 strResult
<< wxT('\\') << c
;
2041 strResult
+= wxT('"');
2046 // undo FilterOutEntryName
2047 static wxString
FilterInEntryName(const wxString
& str
)
2050 strResult
.Alloc(str
.Len());
2052 for ( const wxChar
*pc
= str
.c_str(); *pc
!= '\0'; pc
++ ) {
2053 if ( *pc
== wxT('\\') ) {
2054 // we need to test it here or we'd skip past the NUL in the loop line
2055 if ( *++pc
== _T('\0') )
2065 // sanitize entry or group name: insert '\\' before any special characters
2066 static wxString
FilterOutEntryName(const wxString
& str
)
2069 strResult
.Alloc(str
.Len());
2071 for ( const wxChar
*pc
= str
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
2072 const wxChar c
= *pc
;
2074 // we explicitly allow some of "safe" chars and 8bit ASCII characters
2075 // which will probably never have special meaning and with which we can't
2076 // use isalnum() anyhow (in ASCII built, in Unicode it's just fine)
2078 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
2079 // should *not* be quoted
2082 ((unsigned char)c
< 127) &&
2084 !wxIsalnum(c
) && !wxStrchr(wxT("@_/-!.*%"), c
) )
2086 strResult
+= wxT('\\');
2095 // we can't put ?: in the ctor initializer list because it confuses some
2096 // broken compilers (Borland C++)
2097 static wxString
GetAppName(const wxString
& appName
)
2099 if ( !appName
&& wxTheApp
)
2100 return wxTheApp
->GetAppName();
2105 #endif // wxUSE_CONFIG