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 #include "wx/wxprec.h"
23 #if wxUSE_CONFIG && wxUSE_FILECONFIG
26 #include "wx/string.h"
31 #include "wx/dynarray.h"
34 #include "wx/textfile.h"
35 #include "wx/memtext.h"
36 #include "wx/config.h"
37 #include "wx/fileconf.h"
38 #include "wx/filefn.h"
41 #include "wx/stream.h"
42 #endif // wxUSE_STREAMS
44 #include "wx/utils.h" // for wxGetHomeDir
46 #if defined(__WXMAC__)
47 #include "wx/mac/private.h" // includes mac headers
48 #include "wx/filename.h" // for MacSetTypeAndCreator
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 wxChar
*szName
) const;
226 wxFileConfigEntry
*FindEntry (const wxChar
*szName
) const;
228 // delete entry/subgroup, return false if doesn't exist
229 bool DeleteSubgroupByName(const wxChar
*szName
);
230 bool DeleteEntry(const wxChar
*szName
);
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 // ----------------------------------------------------------------------------
264 wxString
wxFileConfig::GetGlobalDir()
268 #ifdef __VMS__ // Note if __VMS is defined __UNIX is also defined
269 strDir
= wxT("sys$manager:");
270 #elif defined(__WXMAC__)
271 strDir
= wxMacFindFolder( (short) kOnSystemDisk
, kPreferencesFolderType
, kDontCreateFolder
) ;
272 #elif defined( __UNIX__ )
273 strDir
= wxT("/etc/");
274 #elif defined(__OS2__)
275 ULONG aulSysInfo
[QSV_MAX
] = {0};
279 rc
= DosQuerySysInfo( 1L, QSV_MAX
, (PVOID
)aulSysInfo
, sizeof(ULONG
)*QSV_MAX
);
282 drive
= aulSysInfo
[QSV_BOOT_DRIVE
- 1];
283 strDir
.Printf(wxT("%c:\\OS2\\"), 'A'+drive
-1);
285 #elif defined(__WXSTUBS__)
286 wxASSERT_MSG( false, wxT("TODO") ) ;
287 #elif defined(__DOS__)
288 // There's no such thing as global cfg dir in MS-DOS, let's return
289 // current directory (FIXME_MGL?)
291 #elif defined(__WXWINCE__)
292 strDir
= wxT("\\Windows\\");
295 wxChar szWinDir
[MAX_PATH
];
296 ::GetWindowsDirectory(szWinDir
, MAX_PATH
);
300 #endif // Unix/Windows
305 wxString
wxFileConfig::GetLocalDir()
309 #if defined(__WXMAC__) || defined(__DOS__)
310 // no local dir concept on Mac OS 9 or MS-DOS
311 strDir
<< GetGlobalDir() ;
313 wxGetHomeDir(&strDir
);
317 (strDir
.Last() != wxT('/'))
319 && (strDir
.Last() != wxT(']'))
324 if (strDir
.Last() != wxT('\\'))
332 wxString
wxFileConfig::GetGlobalFileName(const wxChar
*szFile
)
334 wxString str
= GetGlobalDir();
337 if ( wxStrchr(szFile
, wxT('.')) == NULL
)
338 #if defined( __WXMAC__ )
339 str
<< wxT(" Preferences") ;
340 #elif defined( __UNIX__ )
349 wxString
wxFileConfig::GetLocalFileName(const wxChar
*szFile
)
352 // On VMS I saw the problem that the home directory was appended
353 // twice for the configuration file. Does that also happen for
355 wxString str
= wxT( '.' );
357 wxString str
= GetLocalDir();
360 #if defined( __UNIX__ ) && !defined( __VMS ) && !defined( __WXMAC__ )
366 #if defined(__WINDOWS__) || defined(__DOS__)
367 if ( wxStrchr(szFile
, wxT('.')) == NULL
)
372 str
<< wxT(" Preferences") ;
378 // ----------------------------------------------------------------------------
380 // ----------------------------------------------------------------------------
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
) )
439 m_strLocalFile
= GetLocalFileName(GetAppName());
441 if ( m_strGlobalFile
.empty() && (style
& wxCONFIG_USE_GLOBAL_FILE
) )
442 m_strGlobalFile
= GetGlobalFileName(GetAppName());
444 // Check if styles are not supplied, but filenames are, in which case
445 // add the correct styles.
446 if ( !m_strLocalFile
.empty() )
447 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
449 if ( !m_strGlobalFile
.empty() )
450 SetStyle(GetStyle() | wxCONFIG_USE_GLOBAL_FILE
);
452 // if the path is not absolute, prepend the standard directory to it
453 // UNLESS wxCONFIG_USE_RELATIVE_PATH style is set
454 if ( !(style
& wxCONFIG_USE_RELATIVE_PATH
) )
456 if ( !m_strLocalFile
.empty() && !wxIsAbsolutePath(m_strLocalFile
) )
458 const wxString strLocalOrig
= m_strLocalFile
;
459 m_strLocalFile
= GetLocalDir();
460 m_strLocalFile
<< strLocalOrig
;
463 if ( !m_strGlobalFile
.empty() && !wxIsAbsolutePath(m_strGlobalFile
) )
465 const wxString strGlobalOrig
= m_strGlobalFile
;
466 m_strGlobalFile
= GetGlobalDir();
467 m_strGlobalFile
<< strGlobalOrig
;
478 wxFileConfig::wxFileConfig(wxInputStream
&inStream
, const wxMBConv
& conv
)
479 : m_conv(conv
.Clone())
481 // always local_file when this constructor is called (?)
482 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
485 m_pRootGroup
= new wxFileConfigGroup(NULL
, wxEmptyString
, this);
490 // translate everything to the current (platform-dependent) line
491 // termination character
499 inStream
.Read(buf
, WXSIZEOF(buf
)-1); // leave room for the NULL
501 const wxStreamError err
= inStream
.GetLastError();
503 if ( err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
)
505 wxLogError(_("Error reading config options."));
509 // FIXME: this is broken because if we have part of multibyte
510 // character in the buffer (and another part hasn't been
511 // read yet) we're going to lose data because of conversion
513 buf
[inStream
.LastRead()] = '\0';
514 strTmp
+= conv
.cMB2WX(buf
);
516 while ( !inStream
.Eof() );
518 strTrans
= wxTextBuffer::Translate(strTmp
);
521 wxMemoryText memText
;
523 // Now we can add the text to the memory text. To do this we extract line
524 // by line from the translated string, until we've reached the end.
526 // VZ: all this is horribly inefficient, we should do the translation on
527 // the fly in one pass saving both memory and time (TODO)
529 const wxChar
*pEOL
= wxTextBuffer::GetEOL(wxTextBuffer::typeDefault
);
530 const size_t EOLLen
= wxStrlen(pEOL
);
532 int posLineStart
= strTrans
.Find(pEOL
);
533 while ( posLineStart
!= -1 )
535 wxString
line(strTrans
.Left(posLineStart
));
537 memText
.AddLine(line
);
539 strTrans
= strTrans
.Mid(posLineStart
+ EOLLen
);
541 posLineStart
= strTrans
.Find(pEOL
);
544 // also add whatever we have left in the translated string.
545 if ( !strTrans
.empty() )
546 memText
.AddLine(strTrans
);
548 // Finally we can parse it all.
549 Parse(memText
, true /* local */);
555 #endif // wxUSE_STREAMS
557 void wxFileConfig::CleanUp()
561 wxFileConfigLineList
*pCur
= m_linesHead
;
562 while ( pCur
!= NULL
) {
563 wxFileConfigLineList
*pNext
= pCur
->Next();
569 wxFileConfig::~wxFileConfig()
578 // ----------------------------------------------------------------------------
579 // parse a config file
580 // ----------------------------------------------------------------------------
582 void wxFileConfig::Parse(const wxTextBuffer
& buffer
, bool bLocal
)
584 const wxChar
*pStart
;
588 size_t nLineCount
= buffer
.GetLineCount();
590 for ( size_t n
= 0; n
< nLineCount
; n
++ )
594 // add the line to linked list
597 LineListAppend(strLine
);
599 // let the root group have its start line as well
602 m_pCurrentGroup
->SetLine(m_linesTail
);
607 // skip leading spaces
608 for ( pStart
= strLine
; wxIsspace(*pStart
); pStart
++ )
611 // skip blank/comment lines
612 if ( *pStart
== wxT('\0')|| *pStart
== wxT(';') || *pStart
== wxT('#') )
615 if ( *pStart
== wxT('[') ) { // a new group
618 while ( *++pEnd
!= wxT(']') ) {
619 if ( *pEnd
== wxT('\\') ) {
620 // the next char is escaped, so skip it even if it is ']'
624 if ( *pEnd
== wxT('\n') || *pEnd
== wxT('\0') ) {
625 // we reached the end of line, break out of the loop
630 if ( *pEnd
!= wxT(']') ) {
631 wxLogError(_("file '%s': unexpected character %c at line %d."),
632 buffer
.GetName(), *pEnd
, n
+ 1);
633 continue; // skip this line
636 // group name here is always considered as abs path
639 strGroup
<< wxCONFIG_PATH_SEPARATOR
640 << FilterInEntryName(wxString(pStart
, pEnd
- pStart
));
642 // will create it if doesn't yet exist
647 if ( m_pCurrentGroup
->Parent() )
648 m_pCurrentGroup
->Parent()->SetLastGroup(m_pCurrentGroup
);
649 m_pCurrentGroup
->SetLine(m_linesTail
);
652 // check that there is nothing except comments left on this line
654 while ( *++pEnd
!= wxT('\0') && bCont
) {
663 // ignore whitespace ('\n' impossible here)
667 wxLogWarning(_("file '%s', line %d: '%s' ignored after group header."),
668 buffer
.GetName(), n
+ 1, pEnd
);
675 while ( *pEnd
&& *pEnd
!= wxT('=') /* && !wxIsspace(*pEnd)*/ ) {
676 if ( *pEnd
== wxT('\\') ) {
677 // next character may be space or not - still take it because it's
678 // quoted (unless there is nothing)
681 // the error message will be given below anyhow
689 wxString
strKey(FilterInEntryName(wxString(pStart
, pEnd
).Trim()));
692 while ( wxIsspace(*pEnd
) )
695 if ( *pEnd
++ != wxT('=') ) {
696 wxLogError(_("file '%s', line %d: '=' expected."),
697 buffer
.GetName(), n
+ 1);
700 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strKey
);
702 if ( pEntry
== NULL
) {
704 pEntry
= m_pCurrentGroup
->AddEntry(strKey
, n
);
707 if ( bLocal
&& pEntry
->IsImmutable() ) {
708 // immutable keys can't be changed by user
709 wxLogWarning(_("file '%s', line %d: value for immutable key '%s' ignored."),
710 buffer
.GetName(), n
+ 1, strKey
.c_str());
713 // the condition below catches the cases (a) and (b) but not (c):
714 // (a) global key found second time in global file
715 // (b) key found second (or more) time in local file
716 // (c) key from global file now found in local one
717 // which is exactly what we want.
718 else if ( !bLocal
|| pEntry
->IsLocal() ) {
719 wxLogWarning(_("file '%s', line %d: key '%s' was first found at line %d."),
720 buffer
.GetName(), n
+ 1, strKey
.c_str(), pEntry
->Line());
726 pEntry
->SetLine(m_linesTail
);
729 while ( wxIsspace(*pEnd
) )
732 wxString value
= pEnd
;
733 if ( !(GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS
) )
734 value
= FilterInValue(value
);
736 pEntry
->SetValue(value
, false);
742 // ----------------------------------------------------------------------------
744 // ----------------------------------------------------------------------------
746 void wxFileConfig::SetRootPath()
749 m_pCurrentGroup
= m_pRootGroup
;
753 wxFileConfig::DoSetPath(const wxString
& strPath
, bool createMissingComponents
)
755 wxArrayString aParts
;
757 if ( strPath
.empty() ) {
762 if ( strPath
[0] == wxCONFIG_PATH_SEPARATOR
) {
764 wxSplitPath(aParts
, strPath
);
767 // relative path, combine with current one
768 wxString strFullPath
= m_strPath
;
769 strFullPath
<< wxCONFIG_PATH_SEPARATOR
<< strPath
;
770 wxSplitPath(aParts
, strFullPath
);
773 // change current group
775 m_pCurrentGroup
= m_pRootGroup
;
776 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
777 wxFileConfigGroup
*pNextGroup
= m_pCurrentGroup
->FindSubgroup(aParts
[n
]);
778 if ( pNextGroup
== NULL
)
780 if ( !createMissingComponents
)
783 pNextGroup
= m_pCurrentGroup
->AddSubgroup(aParts
[n
]);
786 m_pCurrentGroup
= pNextGroup
;
789 // recombine path parts in one variable
791 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
792 m_strPath
<< wxCONFIG_PATH_SEPARATOR
<< aParts
[n
];
798 void wxFileConfig::SetPath(const wxString
& strPath
)
800 DoSetPath(strPath
, true /* create missing path components */);
803 // ----------------------------------------------------------------------------
805 // ----------------------------------------------------------------------------
807 bool wxFileConfig::GetFirstGroup(wxString
& str
, long& lIndex
) const
810 return GetNextGroup(str
, lIndex
);
813 bool wxFileConfig::GetNextGroup (wxString
& str
, long& lIndex
) const
815 if ( size_t(lIndex
) < m_pCurrentGroup
->Groups().Count() ) {
816 str
= m_pCurrentGroup
->Groups()[(size_t)lIndex
++]->Name();
823 bool wxFileConfig::GetFirstEntry(wxString
& str
, long& lIndex
) const
826 return GetNextEntry(str
, lIndex
);
829 bool wxFileConfig::GetNextEntry (wxString
& str
, long& lIndex
) const
831 if ( size_t(lIndex
) < m_pCurrentGroup
->Entries().Count() ) {
832 str
= m_pCurrentGroup
->Entries()[(size_t)lIndex
++]->Name();
839 size_t wxFileConfig::GetNumberOfEntries(bool bRecursive
) const
841 size_t n
= m_pCurrentGroup
->Entries().Count();
843 wxFileConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
844 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
845 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
846 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
847 n
+= GetNumberOfEntries(true);
848 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
855 size_t wxFileConfig::GetNumberOfGroups(bool bRecursive
) const
857 size_t n
= m_pCurrentGroup
->Groups().Count();
859 wxFileConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
860 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
861 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
862 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
863 n
+= GetNumberOfGroups(true);
864 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
871 // ----------------------------------------------------------------------------
872 // tests for existence
873 // ----------------------------------------------------------------------------
875 bool wxFileConfig::HasGroup(const wxString
& strName
) const
877 // special case: DoSetPath("") does work as it's equivalent to DoSetPath("/")
878 // but there is no group with empty name so treat this separately
879 if ( strName
.empty() )
882 const wxString pathOld
= GetPath();
884 wxFileConfig
*self
= wx_const_cast(wxFileConfig
*, this);
886 rc
= self
->DoSetPath(strName
, false /* don't create missing components */);
888 self
->SetPath(pathOld
);
893 bool wxFileConfig::HasEntry(const wxString
& strName
) const
895 wxConfigPathChanger
path(this, strName
);
897 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
898 return pEntry
!= NULL
;
901 // ----------------------------------------------------------------------------
903 // ----------------------------------------------------------------------------
905 bool wxFileConfig::DoReadString(const wxString
& key
, wxString
* pStr
) const
907 wxConfigPathChanger
path(this, key
);
909 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
910 if (pEntry
== NULL
) {
914 *pStr
= pEntry
->Value();
919 bool wxFileConfig::DoReadLong(const wxString
& key
, long *pl
) const
922 if ( !Read(key
, &str
) )
925 // extra spaces shouldn't prevent us from reading numeric values
928 return str
.ToLong(pl
);
931 bool wxFileConfig::DoWriteString(const wxString
& key
, const wxString
& szValue
)
933 wxConfigPathChanger
path(this, key
);
934 wxString strName
= path
.Name();
936 wxLogTrace( FILECONF_TRACE_MASK
,
937 _T(" Writing String '%s' = '%s' to Group '%s'"),
942 if ( strName
.empty() )
944 // setting the value of a group is an error
946 wxASSERT_MSG( szValue
.empty(), wxT("can't set value of a group!") );
948 // ... except if it's empty in which case it's a way to force it's creation
950 wxLogTrace( FILECONF_TRACE_MASK
,
951 _T(" Creating group %s"),
952 m_pCurrentGroup
->Name().c_str() );
956 // this will add a line for this group if it didn't have it before
958 (void)m_pCurrentGroup
->GetGroupLine();
962 // writing an entry check that the name is reasonable
963 if ( strName
[0u] == wxCONFIG_IMMUTABLE_PREFIX
)
965 wxLogError( _("Config entry name cannot start with '%c'."),
966 wxCONFIG_IMMUTABLE_PREFIX
);
970 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strName
);
974 wxLogTrace( FILECONF_TRACE_MASK
,
975 _T(" Adding Entry %s"),
977 pEntry
= m_pCurrentGroup
->AddEntry(strName
);
980 wxLogTrace( FILECONF_TRACE_MASK
,
981 _T(" Setting value %s"),
983 pEntry
->SetValue(szValue
);
991 bool wxFileConfig::DoWriteLong(const wxString
& key
, long lValue
)
993 return Write(key
, wxString::Format(_T("%ld"), lValue
));
996 bool wxFileConfig::Flush(bool /* bCurrentOnly */)
998 if ( !IsDirty() || !m_strLocalFile
)
1001 // set the umask if needed
1002 wxCHANGE_UMASK(m_umask
);
1004 wxTempFile
file(m_strLocalFile
);
1006 if ( !file
.IsOpened() )
1008 wxLogError(_("can't open user configuration file."));
1012 // write all strings to file
1013 for ( wxFileConfigLineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() )
1015 wxString line
= p
->Text();
1016 line
+= wxTextFile::GetEOL();
1017 if ( !file
.Write(line
, *m_conv
) )
1019 wxLogError(_("can't write user configuration file."));
1024 if ( !file
.Commit() )
1026 wxLogError(_("Failed to update user configuration file."));
1033 #if defined(__WXMAC__)
1034 wxFileName(m_strLocalFile
).MacSetTypeAndCreator('TEXT', 'ttxt');
1042 bool wxFileConfig::Save(wxOutputStream
& os
, const wxMBConv
& conv
)
1044 // save unconditionally, even if not dirty
1045 for ( wxFileConfigLineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() )
1047 wxString line
= p
->Text();
1048 line
+= wxTextFile::GetEOL();
1050 wxCharBuffer
buf(line
.mb_str(conv
));
1051 if ( !os
.Write(buf
, strlen(buf
)) )
1053 wxLogError(_("Error saving user configuration data."));
1064 #endif // wxUSE_STREAMS
1066 // ----------------------------------------------------------------------------
1067 // renaming groups/entries
1068 // ----------------------------------------------------------------------------
1070 bool wxFileConfig::RenameEntry(const wxString
& oldName
,
1071 const wxString
& newName
)
1073 wxASSERT_MSG( !wxStrchr(oldName
, wxCONFIG_PATH_SEPARATOR
),
1074 _T("RenameEntry(): paths are not supported") );
1076 // check that the entry exists
1077 wxFileConfigEntry
*oldEntry
= m_pCurrentGroup
->FindEntry(oldName
);
1081 // check that the new entry doesn't already exist
1082 if ( m_pCurrentGroup
->FindEntry(newName
) )
1085 // delete the old entry, create the new one
1086 wxString value
= oldEntry
->Value();
1087 if ( !m_pCurrentGroup
->DeleteEntry(oldName
) )
1092 wxFileConfigEntry
*newEntry
= m_pCurrentGroup
->AddEntry(newName
);
1093 newEntry
->SetValue(value
);
1098 bool wxFileConfig::RenameGroup(const wxString
& oldName
,
1099 const wxString
& newName
)
1101 // check that the group exists
1102 wxFileConfigGroup
*group
= m_pCurrentGroup
->FindSubgroup(oldName
);
1106 // check that the new group doesn't already exist
1107 if ( m_pCurrentGroup
->FindSubgroup(newName
) )
1110 group
->Rename(newName
);
1117 // ----------------------------------------------------------------------------
1118 // delete groups/entries
1119 // ----------------------------------------------------------------------------
1121 bool wxFileConfig::DeleteEntry(const wxString
& key
, bool bGroupIfEmptyAlso
)
1123 wxConfigPathChanger
path(this, key
);
1125 if ( !m_pCurrentGroup
->DeleteEntry(path
.Name()) )
1130 if ( bGroupIfEmptyAlso
&& m_pCurrentGroup
->IsEmpty() ) {
1131 if ( m_pCurrentGroup
!= m_pRootGroup
) {
1132 wxFileConfigGroup
*pGroup
= m_pCurrentGroup
;
1133 SetPath(wxT("..")); // changes m_pCurrentGroup!
1134 m_pCurrentGroup
->DeleteSubgroupByName(pGroup
->Name());
1136 //else: never delete the root group
1142 bool wxFileConfig::DeleteGroup(const wxString
& key
)
1144 wxConfigPathChanger
path(this, key
);
1146 if ( !m_pCurrentGroup
->DeleteSubgroupByName(path
.Name()) )
1154 bool wxFileConfig::DeleteAll()
1158 if ( !m_strLocalFile
.empty() )
1160 if ( wxFile::Exists(m_strLocalFile
) && wxRemove(m_strLocalFile
) == -1 )
1162 wxLogSysError(_("can't delete user configuration file '%s'"),
1163 m_strLocalFile
.c_str());
1173 // ----------------------------------------------------------------------------
1174 // linked list functions
1175 // ----------------------------------------------------------------------------
1177 // append a new line to the end of the list
1179 wxFileConfigLineList
*wxFileConfig::LineListAppend(const wxString
& str
)
1181 wxLogTrace( FILECONF_TRACE_MASK
,
1182 _T(" ** Adding Line '%s'"),
1184 wxLogTrace( FILECONF_TRACE_MASK
,
1186 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1187 wxLogTrace( FILECONF_TRACE_MASK
,
1189 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1191 wxFileConfigLineList
*pLine
= new wxFileConfigLineList(str
);
1193 if ( m_linesTail
== NULL
)
1196 m_linesHead
= pLine
;
1201 m_linesTail
->SetNext(pLine
);
1202 pLine
->SetPrev(m_linesTail
);
1205 m_linesTail
= pLine
;
1207 wxLogTrace( FILECONF_TRACE_MASK
,
1209 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1210 wxLogTrace( FILECONF_TRACE_MASK
,
1212 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1217 // insert a new line after the given one or in the very beginning if !pLine
1218 wxFileConfigLineList
*wxFileConfig::LineListInsert(const wxString
& str
,
1219 wxFileConfigLineList
*pLine
)
1221 wxLogTrace( FILECONF_TRACE_MASK
,
1222 _T(" ** Inserting Line '%s' after '%s'"),
1224 ((pLine
) ? pLine
->Text().c_str() : wxEmptyString
) );
1225 wxLogTrace( FILECONF_TRACE_MASK
,
1227 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1228 wxLogTrace( FILECONF_TRACE_MASK
,
1230 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
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
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1256 wxLogTrace( FILECONF_TRACE_MASK
,
1258 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1263 void wxFileConfig::LineListRemove(wxFileConfigLineList
*pLine
)
1265 wxLogTrace( FILECONF_TRACE_MASK
,
1266 _T(" ** Removing Line '%s'"),
1267 pLine
->Text().c_str() );
1268 wxLogTrace( FILECONF_TRACE_MASK
,
1270 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1271 wxLogTrace( FILECONF_TRACE_MASK
,
1273 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1275 wxFileConfigLineList
*pPrev
= pLine
->Prev(),
1276 *pNext
= pLine
->Next();
1280 if ( pPrev
== NULL
)
1281 m_linesHead
= pNext
;
1283 pPrev
->SetNext(pNext
);
1287 if ( pNext
== NULL
)
1288 m_linesTail
= pPrev
;
1290 pNext
->SetPrev(pPrev
);
1292 if ( m_pRootGroup
->GetGroupLine() == pLine
)
1293 m_pRootGroup
->SetLine(m_linesHead
);
1295 wxLogTrace( FILECONF_TRACE_MASK
,
1297 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1298 wxLogTrace( FILECONF_TRACE_MASK
,
1300 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1305 bool wxFileConfig::LineListIsEmpty()
1307 return m_linesHead
== NULL
;
1310 // ============================================================================
1311 // wxFileConfig::wxFileConfigGroup
1312 // ============================================================================
1314 // ----------------------------------------------------------------------------
1316 // ----------------------------------------------------------------------------
1319 wxFileConfigGroup::wxFileConfigGroup(wxFileConfigGroup
*pParent
,
1320 const wxString
& strName
,
1321 wxFileConfig
*pConfig
)
1322 : m_aEntries(CompareEntries
),
1323 m_aSubgroups(CompareGroups
),
1326 m_pConfig
= pConfig
;
1327 m_pParent
= pParent
;
1330 m_pLastEntry
= NULL
;
1331 m_pLastGroup
= NULL
;
1334 // dtor deletes all children
1335 wxFileConfigGroup::~wxFileConfigGroup()
1338 size_t n
, nCount
= m_aEntries
.Count();
1339 for ( n
= 0; n
< nCount
; n
++ )
1340 delete m_aEntries
[n
];
1343 nCount
= m_aSubgroups
.Count();
1344 for ( n
= 0; n
< nCount
; n
++ )
1345 delete m_aSubgroups
[n
];
1348 // ----------------------------------------------------------------------------
1350 // ----------------------------------------------------------------------------
1352 void wxFileConfigGroup::SetLine(wxFileConfigLineList
*pLine
)
1354 // for a normal (i.e. not root) group this method shouldn't be called twice
1355 // unless we are resetting the line
1356 wxASSERT_MSG( !m_pParent
|| !m_pLine
|| !pLine
,
1357 _T("changing line for a non-root group?") );
1363 This is a bit complicated, so let me explain it in details. All lines that
1364 were read from the local file (the only one we will ever modify) are stored
1365 in a (doubly) linked list. Our problem is to know at which position in this
1366 list should we insert the new entries/subgroups. To solve it we keep three
1367 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1369 m_pLine points to the line containing "[group_name]"
1370 m_pLastEntry points to the last entry of this group in the local file.
1371 m_pLastGroup subgroup
1373 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1374 from the local file, the corresponding variable is set. However, if the group
1375 was read from the global file and then modified or created by the application
1376 these variables are still NULL and we need to create the corresponding lines.
1377 See the following functions (and comments preceding them) for the details of
1380 Also, when our last entry/group are deleted we need to find the new last
1381 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1382 of lines until it either founds an entry/subgroup (and this is the new last
1383 element) or the m_pLine of the group, in which case there are no more entries
1384 (or subgroups) left and m_pLast<element> becomes NULL.
1386 NB: This last problem could be avoided for entries if we added new entries
1387 immediately after m_pLine, but in this case the entries would appear
1388 backwards in the config file (OTOH, it's not that important) and as we
1389 would still need to do it for the subgroups the code wouldn't have been
1390 significantly less complicated.
1393 // Return the line which contains "[our name]". If we're still not in the list,
1394 // add our line to it immediately after the last line of our parent group if we
1395 // have it or in the very beginning if we're the root group.
1396 wxFileConfigLineList
*wxFileConfigGroup::GetGroupLine()
1398 wxLogTrace( FILECONF_TRACE_MASK
,
1399 _T(" GetGroupLine() for Group '%s'"),
1404 wxLogTrace( FILECONF_TRACE_MASK
,
1405 _T(" Getting Line item pointer") );
1407 wxFileConfigGroup
*pParent
= Parent();
1409 // this group wasn't present in local config file, add it now
1412 wxLogTrace( FILECONF_TRACE_MASK
,
1413 _T(" checking parent '%s'"),
1414 pParent
->Name().c_str() );
1416 wxString strFullName
;
1418 // add 1 to the name because we don't want to start with '/'
1419 strFullName
<< wxT("[")
1420 << FilterOutEntryName(GetFullName().c_str() + 1)
1422 m_pLine
= m_pConfig
->LineListInsert(strFullName
,
1423 pParent
->GetLastGroupLine());
1424 pParent
->SetLastGroup(this); // we're surely after all the others
1426 //else: this is the root group and so we return NULL because we don't
1427 // have any group line
1433 // Return the last line belonging to the subgroups of this group (after which
1434 // we can add a new subgroup), if we don't have any subgroups or entries our
1435 // last line is the group line (m_pLine) itself.
1436 wxFileConfigLineList
*wxFileConfigGroup::GetLastGroupLine()
1438 // if we have any subgroups, our last line is the last line of the last
1442 wxFileConfigLineList
*pLine
= m_pLastGroup
->GetLastGroupLine();
1444 wxASSERT_MSG( pLine
, _T("last group must have !NULL associated line") );
1449 // no subgroups, so the last line is the line of thelast entry (if any)
1450 return GetLastEntryLine();
1453 // return the last line belonging to the entries of this group (after which
1454 // we can add a new entry), if we don't have any entries we will add the new
1455 // one immediately after the group line itself.
1456 wxFileConfigLineList
*wxFileConfigGroup::GetLastEntryLine()
1458 wxLogTrace( FILECONF_TRACE_MASK
,
1459 _T(" GetLastEntryLine() for Group '%s'"),
1464 wxFileConfigLineList
*pLine
= m_pLastEntry
->GetLine();
1466 wxASSERT_MSG( pLine
, _T("last entry must have !NULL associated line") );
1471 // no entries: insert after the group header, if any
1472 return GetGroupLine();
1475 void wxFileConfigGroup::SetLastEntry(wxFileConfigEntry
*pEntry
)
1477 m_pLastEntry
= pEntry
;
1481 // the only situation in which a group without its own line can have
1482 // an entry is when the first entry is added to the initially empty
1483 // root pseudo-group
1484 wxASSERT_MSG( !m_pParent
, _T("unexpected for non root group") );
1486 // let the group know that it does have a line in the file now
1487 m_pLine
= pEntry
->GetLine();
1491 // ----------------------------------------------------------------------------
1493 // ----------------------------------------------------------------------------
1495 void wxFileConfigGroup::UpdateGroupAndSubgroupsLines()
1497 // update the line of this group
1498 wxFileConfigLineList
*line
= GetGroupLine();
1499 wxCHECK_RET( line
, _T("a non root group must have a corresponding line!") );
1501 // +1: skip the leading '/'
1502 line
->SetText(wxString::Format(_T("[%s]"), GetFullName().c_str() + 1));
1505 // also update all subgroups as they have this groups name in their lines
1506 const size_t nCount
= m_aSubgroups
.Count();
1507 for ( size_t n
= 0; n
< nCount
; n
++ )
1509 m_aSubgroups
[n
]->UpdateGroupAndSubgroupsLines();
1513 void wxFileConfigGroup::Rename(const wxString
& newName
)
1515 wxCHECK_RET( m_pParent
, _T("the root group can't be renamed") );
1517 m_strName
= newName
;
1519 // update the group lines recursively
1520 UpdateGroupAndSubgroupsLines();
1523 wxString
wxFileConfigGroup::GetFullName() const
1527 fullname
= Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR
+ Name();
1532 // ----------------------------------------------------------------------------
1534 // ----------------------------------------------------------------------------
1536 // use binary search because the array is sorted
1538 wxFileConfigGroup::FindEntry(const wxChar
*szName
) const
1542 hi
= m_aEntries
.Count();
1544 wxFileConfigEntry
*pEntry
;
1548 pEntry
= m_aEntries
[i
];
1550 #if wxCONFIG_CASE_SENSITIVE
1551 res
= wxStrcmp(pEntry
->Name(), szName
);
1553 res
= wxStricmp(pEntry
->Name(), szName
);
1568 wxFileConfigGroup::FindSubgroup(const wxChar
*szName
) const
1572 hi
= m_aSubgroups
.Count();
1574 wxFileConfigGroup
*pGroup
;
1578 pGroup
= m_aSubgroups
[i
];
1580 #if wxCONFIG_CASE_SENSITIVE
1581 res
= wxStrcmp(pGroup
->Name(), szName
);
1583 res
= wxStricmp(pGroup
->Name(), szName
);
1597 // ----------------------------------------------------------------------------
1598 // create a new item
1599 // ----------------------------------------------------------------------------
1601 // create a new entry and add it to the current group
1602 wxFileConfigEntry
*wxFileConfigGroup::AddEntry(const wxString
& strName
, int nLine
)
1604 wxASSERT( FindEntry(strName
) == 0 );
1606 wxFileConfigEntry
*pEntry
= new wxFileConfigEntry(this, strName
, nLine
);
1608 m_aEntries
.Add(pEntry
);
1612 // create a new group and add it to the current group
1613 wxFileConfigGroup
*wxFileConfigGroup::AddSubgroup(const wxString
& strName
)
1615 wxASSERT( FindSubgroup(strName
) == 0 );
1617 wxFileConfigGroup
*pGroup
= new wxFileConfigGroup(this, strName
, m_pConfig
);
1619 m_aSubgroups
.Add(pGroup
);
1623 // ----------------------------------------------------------------------------
1625 // ----------------------------------------------------------------------------
1628 The delete operations are _very_ slow if we delete the last item of this
1629 group (see comments before GetXXXLineXXX functions for more details),
1630 so it's much better to start with the first entry/group if we want to
1631 delete several of them.
1634 bool wxFileConfigGroup::DeleteSubgroupByName(const wxChar
*szName
)
1636 wxFileConfigGroup
* const pGroup
= FindSubgroup(szName
);
1638 return pGroup
? DeleteSubgroup(pGroup
) : false;
1641 // Delete the subgroup and remove all references to it from
1642 // other data structures.
1643 bool wxFileConfigGroup::DeleteSubgroup(wxFileConfigGroup
*pGroup
)
1645 wxCHECK_MSG( pGroup
, false, _T("deleting non existing group?") );
1647 wxLogTrace( FILECONF_TRACE_MASK
,
1648 _T("Deleting group '%s' from '%s'"),
1649 pGroup
->Name().c_str(),
1652 wxLogTrace( FILECONF_TRACE_MASK
,
1653 _T(" (m_pLine) = prev: %p, this %p, next %p"),
1654 ((m_pLine
) ? m_pLine
->Prev() : 0),
1656 ((m_pLine
) ? m_pLine
->Next() : 0) );
1657 wxLogTrace( FILECONF_TRACE_MASK
,
1659 ((m_pLine
) ? m_pLine
->Text().c_str() : wxEmptyString
) );
1661 // delete all entries...
1662 size_t nCount
= pGroup
->m_aEntries
.Count();
1664 wxLogTrace(FILECONF_TRACE_MASK
,
1665 _T("Removing %lu entries"), (unsigned long)nCount
);
1667 for ( size_t nEntry
= 0; nEntry
< nCount
; nEntry
++ )
1669 wxFileConfigLineList
*pLine
= pGroup
->m_aEntries
[nEntry
]->GetLine();
1673 wxLogTrace( FILECONF_TRACE_MASK
,
1675 pLine
->Text().c_str() );
1676 m_pConfig
->LineListRemove(pLine
);
1680 // ...and subgroups of this subgroup
1681 nCount
= pGroup
->m_aSubgroups
.Count();
1683 wxLogTrace( FILECONF_TRACE_MASK
,
1684 _T("Removing %lu subgroups"), (unsigned long)nCount
);
1686 for ( size_t nGroup
= 0; nGroup
< nCount
; nGroup
++ )
1688 pGroup
->DeleteSubgroup(pGroup
->m_aSubgroups
[0]);
1691 // and then finally the group itself
1692 wxFileConfigLineList
*pLine
= pGroup
->m_pLine
;
1695 wxLogTrace( FILECONF_TRACE_MASK
,
1696 _T(" Removing line for group '%s' : '%s'"),
1697 pGroup
->Name().c_str(),
1698 pLine
->Text().c_str() );
1699 wxLogTrace( FILECONF_TRACE_MASK
,
1700 _T(" Removing from group '%s' : '%s'"),
1702 ((m_pLine
) ? m_pLine
->Text().c_str() : wxEmptyString
) );
1704 // notice that we may do this test inside the previous "if"
1705 // because the last entry's line is surely !NULL
1706 if ( pGroup
== m_pLastGroup
)
1708 wxLogTrace( FILECONF_TRACE_MASK
,
1709 _T(" Removing last group") );
1711 // our last entry is being deleted, so find the last one which
1712 // stays by going back until we find a subgroup or reach the
1714 const size_t nSubgroups
= m_aSubgroups
.Count();
1716 m_pLastGroup
= NULL
;
1717 for ( wxFileConfigLineList
*pl
= pLine
->Prev();
1718 pl
&& pl
!= m_pLine
&& !m_pLastGroup
;
1721 // does this line belong to our subgroup?
1722 for ( size_t n
= 0; n
< nSubgroups
; n
++ )
1724 // do _not_ call GetGroupLine! we don't want to add it to
1725 // the local file if it's not already there
1726 if ( m_aSubgroups
[n
]->m_pLine
== pl
)
1728 m_pLastGroup
= m_aSubgroups
[n
];
1735 m_pConfig
->LineListRemove(pLine
);
1739 wxLogTrace( FILECONF_TRACE_MASK
,
1740 _T(" No line entry for Group '%s'?"),
1741 pGroup
->Name().c_str() );
1744 m_aSubgroups
.Remove(pGroup
);
1750 bool wxFileConfigGroup::DeleteEntry(const wxChar
*szName
)
1752 wxFileConfigEntry
*pEntry
= FindEntry(szName
);
1755 // entry doesn't exist, nothing to do
1759 wxFileConfigLineList
*pLine
= pEntry
->GetLine();
1760 if ( pLine
!= NULL
) {
1761 // notice that we may do this test inside the previous "if" because the
1762 // last entry's line is surely !NULL
1763 if ( pEntry
== m_pLastEntry
) {
1764 // our last entry is being deleted - find the last one which stays
1765 wxASSERT( m_pLine
!= NULL
); // if we have an entry with !NULL pLine...
1767 // go back until we find another entry or reach the group's line
1768 wxFileConfigEntry
*pNewLast
= NULL
;
1769 size_t n
, nEntries
= m_aEntries
.Count();
1770 wxFileConfigLineList
*pl
;
1771 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1772 // is it our subgroup?
1773 for ( n
= 0; (pNewLast
== NULL
) && (n
< nEntries
); n
++ ) {
1774 if ( m_aEntries
[n
]->GetLine() == m_pLine
)
1775 pNewLast
= m_aEntries
[n
];
1778 if ( pNewLast
!= NULL
) // found?
1782 if ( pl
== m_pLine
) {
1783 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1785 // we've reached the group line without finding any subgroups
1786 m_pLastEntry
= NULL
;
1789 m_pLastEntry
= pNewLast
;
1792 m_pConfig
->LineListRemove(pLine
);
1795 m_aEntries
.Remove(pEntry
);
1801 // ============================================================================
1802 // wxFileConfig::wxFileConfigEntry
1803 // ============================================================================
1805 // ----------------------------------------------------------------------------
1807 // ----------------------------------------------------------------------------
1808 wxFileConfigEntry::wxFileConfigEntry(wxFileConfigGroup
*pParent
,
1809 const wxString
& strName
,
1811 : m_strName(strName
)
1813 wxASSERT( !strName
.empty() );
1815 m_pParent
= pParent
;
1819 m_bHasValue
= false;
1821 m_bImmutable
= strName
[0] == wxCONFIG_IMMUTABLE_PREFIX
;
1823 m_strName
.erase(0, 1); // remove first character
1826 // ----------------------------------------------------------------------------
1828 // ----------------------------------------------------------------------------
1830 void wxFileConfigEntry::SetLine(wxFileConfigLineList
*pLine
)
1832 if ( m_pLine
!= NULL
) {
1833 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1834 Name().c_str(), m_pParent
->GetFullName().c_str());
1838 Group()->SetLastEntry(this);
1841 // second parameter is false if we read the value from file and prevents the
1842 // entry from being marked as 'dirty'
1843 void wxFileConfigEntry::SetValue(const wxString
& strValue
, bool bUser
)
1845 if ( bUser
&& IsImmutable() )
1847 wxLogWarning( _("attempt to change immutable key '%s' ignored."),
1852 // do nothing if it's the same value: but don't test for it if m_bHasValue
1853 // hadn't been set yet or we'd never write empty values to the file
1854 if ( m_bHasValue
&& strValue
== m_strValue
)
1858 m_strValue
= strValue
;
1862 wxString strValFiltered
;
1864 if ( Group()->Config()->GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS
)
1866 strValFiltered
= strValue
;
1869 strValFiltered
= FilterOutValue(strValue
);
1873 strLine
<< FilterOutEntryName(m_strName
) << wxT('=') << strValFiltered
;
1877 // entry was read from the local config file, just modify the line
1878 m_pLine
->SetText(strLine
);
1880 else // this entry didn't exist in the local file
1882 // add a new line to the file: note that line returned by
1883 // GetLastEntryLine() may be NULL if we're in the root group and it
1884 // doesn't have any entries yet, but this is ok as passing NULL
1885 // line to LineListInsert() means to prepend new line to the list
1886 wxFileConfigLineList
*line
= Group()->GetLastEntryLine();
1887 m_pLine
= Group()->Config()->LineListInsert(strLine
, line
);
1889 Group()->SetLastEntry(this);
1894 // ============================================================================
1896 // ============================================================================
1898 // ----------------------------------------------------------------------------
1899 // compare functions for array sorting
1900 // ----------------------------------------------------------------------------
1902 int CompareEntries(wxFileConfigEntry
*p1
, wxFileConfigEntry
*p2
)
1904 #if wxCONFIG_CASE_SENSITIVE
1905 return wxStrcmp(p1
->Name(), p2
->Name());
1907 return wxStricmp(p1
->Name(), p2
->Name());
1911 int CompareGroups(wxFileConfigGroup
*p1
, wxFileConfigGroup
*p2
)
1913 #if wxCONFIG_CASE_SENSITIVE
1914 return wxStrcmp(p1
->Name(), p2
->Name());
1916 return wxStricmp(p1
->Name(), p2
->Name());
1920 // ----------------------------------------------------------------------------
1922 // ----------------------------------------------------------------------------
1924 // undo FilterOutValue
1925 static wxString
FilterInValue(const wxString
& str
)
1928 strResult
.Alloc(str
.Len());
1930 bool bQuoted
= !str
.empty() && str
[0] == '"';
1932 for ( size_t n
= bQuoted
? 1 : 0; n
< str
.Len(); n
++ ) {
1933 if ( str
[n
] == wxT('\\') ) {
1934 switch ( str
[++n
] ) {
1936 strResult
+= wxT('\n');
1940 strResult
+= wxT('\r');
1944 strResult
+= wxT('\t');
1948 strResult
+= wxT('\\');
1952 strResult
+= wxT('"');
1957 if ( str
[n
] != wxT('"') || !bQuoted
)
1958 strResult
+= str
[n
];
1959 else if ( n
!= str
.Len() - 1 ) {
1960 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1963 //else: it's the last quote of a quoted string, ok
1970 // quote the string before writing it to file
1971 static wxString
FilterOutValue(const wxString
& str
)
1977 strResult
.Alloc(str
.Len());
1979 // quoting is necessary to preserve spaces in the beginning of the string
1980 bool bQuote
= wxIsspace(str
[0]) || str
[0] == wxT('"');
1983 strResult
+= wxT('"');
1986 for ( size_t n
= 0; n
< str
.Len(); n
++ ) {
2009 //else: fall through
2012 strResult
+= str
[n
];
2013 continue; // nothing special to do
2016 // we get here only for special characters
2017 strResult
<< wxT('\\') << c
;
2021 strResult
+= wxT('"');
2026 // undo FilterOutEntryName
2027 static wxString
FilterInEntryName(const wxString
& str
)
2030 strResult
.Alloc(str
.Len());
2032 for ( const wxChar
*pc
= str
.c_str(); *pc
!= '\0'; pc
++ ) {
2033 if ( *pc
== wxT('\\') ) {
2034 // we need to test it here or we'd skip past the NUL in the loop line
2035 if ( *++pc
== _T('\0') )
2045 // sanitize entry or group name: insert '\\' before any special characters
2046 static wxString
FilterOutEntryName(const wxString
& str
)
2049 strResult
.Alloc(str
.Len());
2051 for ( const wxChar
*pc
= str
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
2052 const wxChar c
= *pc
;
2054 // we explicitly allow some of "safe" chars and 8bit ASCII characters
2055 // which will probably never have special meaning and with which we can't
2056 // use isalnum() anyhow (in ASCII built, in Unicode it's just fine)
2058 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
2059 // should *not* be quoted
2062 ((unsigned char)c
< 127) &&
2064 !wxIsalnum(c
) && !wxStrchr(wxT("@_/-!.*%"), c
) )
2066 strResult
+= wxT('\\');
2075 // we can't put ?: in the ctor initializer list because it confuses some
2076 // broken compilers (Borland C++)
2077 static wxString
GetAppName(const wxString
& appName
)
2079 if ( !appName
&& wxTheApp
)
2080 return wxTheApp
->GetAppName();
2085 #endif // wxUSE_CONFIG