1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: implementation of wxFileConfig derivation of wxConfig
4 // Author: Vadim Zeitlin
6 // Created: 07.04.98 (adapted from appconf.cpp)
8 // Copyright: (c) 1997 Karsten Ballüder & Vadim Zeitlin
9 // Ballueder@usa.net <zeitlin@dptmaths.ens-cachan.fr>
10 // Licence: wxWindows 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(__WXPM__)
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 return GetGlobalDir() ;
313 wxGetHomeDir(&strDir
);
317 if (strDir
.Last() != wxT(']'))
319 if (strDir
.Last() != wxT('/')) strDir
<< wxT('/');
321 if (strDir
.Last() != wxT('\\')) strDir
<< wxT('\\');
328 wxString
wxFileConfig::GetGlobalFileName(const wxChar
*szFile
)
330 wxString str
= GetGlobalDir();
333 if ( wxStrchr(szFile
, wxT('.')) == NULL
)
334 #if defined( __WXMAC__ )
335 str
<< wxT(" Preferences") ;
336 #elif defined( __UNIX__ )
345 wxString
wxFileConfig::GetLocalFileName(const wxChar
*szFile
)
348 // On VMS I saw the problem that the home directory was appended
349 // twice for the configuration file. Does that also happen for
351 wxString str
= wxT( '.' );
353 wxString str
= GetLocalDir();
356 #if defined( __UNIX__ ) && !defined( __VMS ) && !defined( __WXMAC__ )
362 #if defined(__WINDOWS__) || defined(__DOS__)
363 if ( wxStrchr(szFile
, wxT('.')) == NULL
)
368 str
<< wxT(" Preferences") ;
374 // ----------------------------------------------------------------------------
376 // ----------------------------------------------------------------------------
378 void wxFileConfig::Init()
381 m_pRootGroup
= new wxFileConfigGroup(NULL
, wxEmptyString
, this);
386 // It's not an error if (one of the) file(s) doesn't exist.
388 // parse the global file
389 if ( !m_strGlobalFile
.empty() && wxFile::Exists(m_strGlobalFile
) )
391 wxTextFile
fileGlobal(m_strGlobalFile
);
393 if ( fileGlobal
.Open(m_conv
/*ignored in ANSI build*/) )
395 Parse(fileGlobal
, false /* global */);
400 wxLogWarning(_("can't open global configuration file '%s'."), m_strGlobalFile
.c_str());
404 // parse the local file
405 if ( !m_strLocalFile
.empty() && wxFile::Exists(m_strLocalFile
) )
407 wxTextFile
fileLocal(m_strLocalFile
);
408 if ( fileLocal
.Open(m_conv
/*ignored in ANSI build*/) )
410 Parse(fileLocal
, true /* local */);
415 wxLogWarning(_("can't open user configuration file '%s'."), m_strLocalFile
.c_str() );
422 // constructor supports creation of wxFileConfig objects of any type
423 wxFileConfig::wxFileConfig(const wxString
& appName
, const wxString
& vendorName
,
424 const wxString
& strLocal
, const wxString
& strGlobal
,
425 long style
, wxMBConv
& conv
)
426 : wxConfigBase(::GetAppName(appName
), vendorName
,
429 m_strLocalFile(strLocal
), m_strGlobalFile(strGlobal
),
432 // Make up names for files if empty
433 if ( m_strLocalFile
.empty() && (style
& wxCONFIG_USE_LOCAL_FILE
) )
434 m_strLocalFile
= GetLocalFileName(GetAppName());
436 if ( m_strGlobalFile
.empty() && (style
& wxCONFIG_USE_GLOBAL_FILE
) )
437 m_strGlobalFile
= GetGlobalFileName(GetAppName());
439 // Check if styles are not supplied, but filenames are, in which case
440 // add the correct styles.
441 if ( !m_strLocalFile
.empty() )
442 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
444 if ( !m_strGlobalFile
.empty() )
445 SetStyle(GetStyle() | wxCONFIG_USE_GLOBAL_FILE
);
447 // if the path is not absolute, prepend the standard directory to it
448 // UNLESS wxCONFIG_USE_RELATIVE_PATH style is set
449 if ( !(style
& wxCONFIG_USE_RELATIVE_PATH
) )
451 if ( !m_strLocalFile
.empty() && !wxIsAbsolutePath(m_strLocalFile
) )
453 wxString strLocal
= m_strLocalFile
;
454 m_strLocalFile
= GetLocalDir();
455 m_strLocalFile
<< strLocal
;
458 if ( !m_strGlobalFile
.empty() && !wxIsAbsolutePath(m_strGlobalFile
) )
460 wxString strGlobal
= m_strGlobalFile
;
461 m_strGlobalFile
= GetGlobalDir();
462 m_strGlobalFile
<< strGlobal
;
473 wxFileConfig::wxFileConfig(wxInputStream
&inStream
, wxMBConv
& conv
)
476 // always local_file when this constructor is called (?)
477 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
480 m_pRootGroup
= new wxFileConfigGroup(NULL
, wxEmptyString
, this);
485 // translate everything to the current (platform-dependent) line
486 // termination character
494 inStream
.Read(buf
, WXSIZEOF(buf
)-1); // leave room for the NULL
496 const wxStreamError err
= inStream
.GetLastError();
498 if ( err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
)
500 wxLogError(_("Error reading config options."));
504 // FIXME: this is broken because if we have part of multibyte
505 // character in the buffer (and another part hasn't been
506 // read yet) we're going to lose data because of conversion
508 buf
[inStream
.LastRead()] = '\0';
509 strTmp
+= conv
.cMB2WX(buf
);
511 while ( !inStream
.Eof() );
513 strTrans
= wxTextBuffer::Translate(strTmp
);
516 wxMemoryText memText
;
518 // Now we can add the text to the memory text. To do this we extract line
519 // by line from the translated string, until we've reached the end.
521 // VZ: all this is horribly inefficient, we should do the translation on
522 // the fly in one pass saving both memory and time (TODO)
524 const wxChar
*pEOL
= wxTextBuffer::GetEOL(wxTextBuffer::typeDefault
);
525 const size_t EOLLen
= wxStrlen(pEOL
);
527 int posLineStart
= strTrans
.Find(pEOL
);
528 while ( posLineStart
!= -1 )
530 wxString
line(strTrans
.Left(posLineStart
));
532 memText
.AddLine(line
);
534 strTrans
= strTrans
.Mid(posLineStart
+ EOLLen
);
536 posLineStart
= strTrans
.Find(pEOL
);
539 // also add whatever we have left in the translated string.
540 if ( !strTrans
.empty() )
541 memText
.AddLine(strTrans
);
543 // Finally we can parse it all.
544 Parse(memText
, true /* local */);
550 #endif // wxUSE_STREAMS
552 void wxFileConfig::CleanUp()
556 wxFileConfigLineList
*pCur
= m_linesHead
;
557 while ( pCur
!= NULL
) {
558 wxFileConfigLineList
*pNext
= pCur
->Next();
564 wxFileConfig::~wxFileConfig()
571 // ----------------------------------------------------------------------------
572 // parse a config file
573 // ----------------------------------------------------------------------------
575 void wxFileConfig::Parse(const wxTextBuffer
& buffer
, bool bLocal
)
577 const wxChar
*pStart
;
581 size_t nLineCount
= buffer
.GetLineCount();
583 for ( size_t n
= 0; n
< nLineCount
; n
++ )
587 // add the line to linked list
590 LineListAppend(strLine
);
592 // let the root group have its start line as well
595 m_pCurrentGroup
->SetLine(m_linesTail
);
600 // skip leading spaces
601 for ( pStart
= strLine
; wxIsspace(*pStart
); pStart
++ )
604 // skip blank/comment lines
605 if ( *pStart
== wxT('\0')|| *pStart
== wxT(';') || *pStart
== wxT('#') )
608 if ( *pStart
== wxT('[') ) { // a new group
611 while ( *++pEnd
!= wxT(']') ) {
612 if ( *pEnd
== wxT('\\') ) {
613 // the next char is escaped, so skip it even if it is ']'
617 if ( *pEnd
== wxT('\n') || *pEnd
== wxT('\0') ) {
618 // we reached the end of line, break out of the loop
623 if ( *pEnd
!= wxT(']') ) {
624 wxLogError(_("file '%s': unexpected character %c at line %d."),
625 buffer
.GetName(), *pEnd
, n
+ 1);
626 continue; // skip this line
629 // group name here is always considered as abs path
632 strGroup
<< wxCONFIG_PATH_SEPARATOR
633 << FilterInEntryName(wxString(pStart
, pEnd
- pStart
));
635 // will create it if doesn't yet exist
640 if ( m_pCurrentGroup
->Parent() )
641 m_pCurrentGroup
->Parent()->SetLastGroup(m_pCurrentGroup
);
642 m_pCurrentGroup
->SetLine(m_linesTail
);
645 // check that there is nothing except comments left on this line
647 while ( *++pEnd
!= wxT('\0') && bCont
) {
656 // ignore whitespace ('\n' impossible here)
660 wxLogWarning(_("file '%s', line %d: '%s' ignored after group header."),
661 buffer
.GetName(), n
+ 1, pEnd
);
667 const wxChar
*pEnd
= pStart
;
668 while ( *pEnd
&& *pEnd
!= wxT('=') /* && !wxIsspace(*pEnd)*/ ) {
669 if ( *pEnd
== wxT('\\') ) {
670 // next character may be space or not - still take it because it's
671 // quoted (unless there is nothing)
674 // the error message will be given below anyhow
682 wxString
strKey(FilterInEntryName(wxString(pStart
, pEnd
).Trim()));
685 while ( wxIsspace(*pEnd
) )
688 if ( *pEnd
++ != wxT('=') ) {
689 wxLogError(_("file '%s', line %d: '=' expected."),
690 buffer
.GetName(), n
+ 1);
693 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strKey
);
695 if ( pEntry
== NULL
) {
697 pEntry
= m_pCurrentGroup
->AddEntry(strKey
, n
);
700 if ( bLocal
&& pEntry
->IsImmutable() ) {
701 // immutable keys can't be changed by user
702 wxLogWarning(_("file '%s', line %d: value for immutable key '%s' ignored."),
703 buffer
.GetName(), n
+ 1, strKey
.c_str());
706 // the condition below catches the cases (a) and (b) but not (c):
707 // (a) global key found second time in global file
708 // (b) key found second (or more) time in local file
709 // (c) key from global file now found in local one
710 // which is exactly what we want.
711 else if ( !bLocal
|| pEntry
->IsLocal() ) {
712 wxLogWarning(_("file '%s', line %d: key '%s' was first found at line %d."),
713 buffer
.GetName(), n
+ 1, strKey
.c_str(), pEntry
->Line());
719 pEntry
->SetLine(m_linesTail
);
722 while ( wxIsspace(*pEnd
) )
725 wxString value
= pEnd
;
726 if ( !(GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS
) )
727 value
= FilterInValue(value
);
729 pEntry
->SetValue(value
, false);
735 // ----------------------------------------------------------------------------
737 // ----------------------------------------------------------------------------
739 void wxFileConfig::SetRootPath()
742 m_pCurrentGroup
= m_pRootGroup
;
746 wxFileConfig::DoSetPath(const wxString
& strPath
, bool createMissingComponents
)
748 wxArrayString aParts
;
750 if ( strPath
.empty() ) {
755 if ( strPath
[0] == wxCONFIG_PATH_SEPARATOR
) {
757 wxSplitPath(aParts
, strPath
);
760 // relative path, combine with current one
761 wxString strFullPath
= m_strPath
;
762 strFullPath
<< wxCONFIG_PATH_SEPARATOR
<< strPath
;
763 wxSplitPath(aParts
, strFullPath
);
766 // change current group
768 m_pCurrentGroup
= m_pRootGroup
;
769 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
770 wxFileConfigGroup
*pNextGroup
= m_pCurrentGroup
->FindSubgroup(aParts
[n
]);
771 if ( pNextGroup
== NULL
)
773 if ( !createMissingComponents
)
776 pNextGroup
= m_pCurrentGroup
->AddSubgroup(aParts
[n
]);
779 m_pCurrentGroup
= pNextGroup
;
782 // recombine path parts in one variable
784 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
785 m_strPath
<< wxCONFIG_PATH_SEPARATOR
<< aParts
[n
];
791 void wxFileConfig::SetPath(const wxString
& strPath
)
793 DoSetPath(strPath
, true /* create missing path components */);
796 // ----------------------------------------------------------------------------
798 // ----------------------------------------------------------------------------
800 bool wxFileConfig::GetFirstGroup(wxString
& str
, long& lIndex
) const
803 return GetNextGroup(str
, lIndex
);
806 bool wxFileConfig::GetNextGroup (wxString
& str
, long& lIndex
) const
808 if ( size_t(lIndex
) < m_pCurrentGroup
->Groups().Count() ) {
809 str
= m_pCurrentGroup
->Groups()[(size_t)lIndex
++]->Name();
816 bool wxFileConfig::GetFirstEntry(wxString
& str
, long& lIndex
) const
819 return GetNextEntry(str
, lIndex
);
822 bool wxFileConfig::GetNextEntry (wxString
& str
, long& lIndex
) const
824 if ( size_t(lIndex
) < m_pCurrentGroup
->Entries().Count() ) {
825 str
= m_pCurrentGroup
->Entries()[(size_t)lIndex
++]->Name();
832 size_t wxFileConfig::GetNumberOfEntries(bool bRecursive
) const
834 size_t n
= m_pCurrentGroup
->Entries().Count();
836 wxFileConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
837 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
838 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
839 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
840 n
+= GetNumberOfEntries(true);
841 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
848 size_t wxFileConfig::GetNumberOfGroups(bool bRecursive
) const
850 size_t n
= m_pCurrentGroup
->Groups().Count();
852 wxFileConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
853 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
854 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
855 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
856 n
+= GetNumberOfGroups(true);
857 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
864 // ----------------------------------------------------------------------------
865 // tests for existence
866 // ----------------------------------------------------------------------------
868 bool wxFileConfig::HasGroup(const wxString
& strName
) const
870 // special case: DoSetPath("") does work as it's equivalent to DoSetPath("/")
871 // but there is no group with empty name so treat this separately
872 if ( strName
.empty() )
875 const wxString pathOld
= GetPath();
877 wxFileConfig
*self
= wx_const_cast(wxFileConfig
*, this);
879 rc
= self
->DoSetPath(strName
, false /* don't create missing components */);
881 self
->SetPath(pathOld
);
886 bool wxFileConfig::HasEntry(const wxString
& strName
) const
888 wxConfigPathChanger
path(this, strName
);
890 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
891 return pEntry
!= NULL
;
894 // ----------------------------------------------------------------------------
896 // ----------------------------------------------------------------------------
898 bool wxFileConfig::DoReadString(const wxString
& key
, wxString
* pStr
) const
900 wxConfigPathChanger
path(this, key
);
902 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
903 if (pEntry
== NULL
) {
907 *pStr
= pEntry
->Value();
912 bool wxFileConfig::DoReadLong(const wxString
& key
, long *pl
) const
915 if ( !Read(key
, &str
) )
918 // extra spaces shouldn't prevent us from reading numeric values
921 return str
.ToLong(pl
);
924 bool wxFileConfig::DoWriteString(const wxString
& key
, const wxString
& szValue
)
926 wxConfigPathChanger
path(this, key
);
927 wxString strName
= path
.Name();
929 wxLogTrace( FILECONF_TRACE_MASK
,
930 _T(" Writing String '%s' = '%s' to Group '%s'"),
935 if ( strName
.empty() )
937 // setting the value of a group is an error
939 wxASSERT_MSG( szValue
.empty(), wxT("can't set value of a group!") );
941 // ... except if it's empty in which case it's a way to force it's creation
943 wxLogTrace( FILECONF_TRACE_MASK
,
944 _T(" Creating group %s"),
945 m_pCurrentGroup
->Name().c_str() );
949 // this will add a line for this group if it didn't have it before
951 (void)m_pCurrentGroup
->GetGroupLine();
955 // writing an entry check that the name is reasonable
956 if ( strName
[0u] == wxCONFIG_IMMUTABLE_PREFIX
)
958 wxLogError( _("Config entry name cannot start with '%c'."),
959 wxCONFIG_IMMUTABLE_PREFIX
);
963 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strName
);
967 wxLogTrace( FILECONF_TRACE_MASK
,
968 _T(" Adding Entry %s"),
970 pEntry
= m_pCurrentGroup
->AddEntry(strName
);
973 wxLogTrace( FILECONF_TRACE_MASK
,
974 _T(" Setting value %s"),
976 pEntry
->SetValue(szValue
);
984 bool wxFileConfig::DoWriteLong(const wxString
& key
, long lValue
)
986 return Write(key
, wxString::Format(_T("%ld"), lValue
));
989 bool wxFileConfig::Flush(bool /* bCurrentOnly */)
991 if ( !IsDirty() || !m_strLocalFile
)
994 // set the umask if needed
995 wxCHANGE_UMASK(m_umask
);
997 wxTempFile
file(m_strLocalFile
);
999 if ( !file
.IsOpened() )
1001 wxLogError(_("can't open user configuration file."));
1005 // write all strings to file
1006 for ( wxFileConfigLineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() )
1008 wxString line
= p
->Text();
1009 line
+= wxTextFile::GetEOL();
1010 if ( !file
.Write(line
, m_conv
) )
1012 wxLogError(_("can't write user configuration file."));
1017 if ( !file
.Commit() )
1019 wxLogError(_("Failed to update user configuration file."));
1026 #if defined(__WXMAC__)
1027 wxFileName(m_strLocalFile
).MacSetTypeAndCreator('TEXT', 'ttxt');
1035 bool wxFileConfig::Save(wxOutputStream
& os
, wxMBConv
& conv
)
1037 // save unconditionally, even if not dirty
1038 for ( wxFileConfigLineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() )
1040 wxString line
= p
->Text();
1041 line
+= wxTextFile::GetEOL();
1043 wxCharBuffer
buf(line
.mb_str(conv
));
1044 if ( !os
.Write(buf
, strlen(buf
)) )
1046 wxLogError(_("Error saving user configuration data."));
1057 #endif // wxUSE_STREAMS
1059 // ----------------------------------------------------------------------------
1060 // renaming groups/entries
1061 // ----------------------------------------------------------------------------
1063 bool wxFileConfig::RenameEntry(const wxString
& oldName
,
1064 const wxString
& newName
)
1066 wxASSERT_MSG( !wxStrchr(oldName
, wxCONFIG_PATH_SEPARATOR
),
1067 _T("RenameEntry(): paths are not supported") );
1069 // check that the entry exists
1070 wxFileConfigEntry
*oldEntry
= m_pCurrentGroup
->FindEntry(oldName
);
1074 // check that the new entry doesn't already exist
1075 if ( m_pCurrentGroup
->FindEntry(newName
) )
1078 // delete the old entry, create the new one
1079 wxString value
= oldEntry
->Value();
1080 if ( !m_pCurrentGroup
->DeleteEntry(oldName
) )
1085 wxFileConfigEntry
*newEntry
= m_pCurrentGroup
->AddEntry(newName
);
1086 newEntry
->SetValue(value
);
1091 bool wxFileConfig::RenameGroup(const wxString
& oldName
,
1092 const wxString
& newName
)
1094 // check that the group exists
1095 wxFileConfigGroup
*group
= m_pCurrentGroup
->FindSubgroup(oldName
);
1099 // check that the new group doesn't already exist
1100 if ( m_pCurrentGroup
->FindSubgroup(newName
) )
1103 group
->Rename(newName
);
1110 // ----------------------------------------------------------------------------
1111 // delete groups/entries
1112 // ----------------------------------------------------------------------------
1114 bool wxFileConfig::DeleteEntry(const wxString
& key
, bool bGroupIfEmptyAlso
)
1116 wxConfigPathChanger
path(this, key
);
1118 if ( !m_pCurrentGroup
->DeleteEntry(path
.Name()) )
1123 if ( bGroupIfEmptyAlso
&& m_pCurrentGroup
->IsEmpty() ) {
1124 if ( m_pCurrentGroup
!= m_pRootGroup
) {
1125 wxFileConfigGroup
*pGroup
= m_pCurrentGroup
;
1126 SetPath(wxT("..")); // changes m_pCurrentGroup!
1127 m_pCurrentGroup
->DeleteSubgroupByName(pGroup
->Name());
1129 //else: never delete the root group
1135 bool wxFileConfig::DeleteGroup(const wxString
& key
)
1137 wxConfigPathChanger
path(this, key
);
1139 if ( !m_pCurrentGroup
->DeleteSubgroupByName(path
.Name()) )
1147 bool wxFileConfig::DeleteAll()
1151 if ( !m_strLocalFile
.empty() )
1153 if ( wxFile::Exists(m_strLocalFile
) && wxRemove(m_strLocalFile
) == -1 )
1155 wxLogSysError(_("can't delete user configuration file '%s'"),
1156 m_strLocalFile
.c_str());
1161 m_strGlobalFile
= wxEmptyString
;
1169 // ----------------------------------------------------------------------------
1170 // linked list functions
1171 // ----------------------------------------------------------------------------
1173 // append a new line to the end of the list
1175 wxFileConfigLineList
*wxFileConfig::LineListAppend(const wxString
& str
)
1177 wxLogTrace( FILECONF_TRACE_MASK
,
1178 _T(" ** Adding Line '%s'"),
1180 wxLogTrace( FILECONF_TRACE_MASK
,
1182 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1183 wxLogTrace( FILECONF_TRACE_MASK
,
1185 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1187 wxFileConfigLineList
*pLine
= new wxFileConfigLineList(str
);
1189 if ( m_linesTail
== NULL
)
1192 m_linesHead
= pLine
;
1197 m_linesTail
->SetNext(pLine
);
1198 pLine
->SetPrev(m_linesTail
);
1201 m_linesTail
= pLine
;
1203 wxLogTrace( FILECONF_TRACE_MASK
,
1205 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1206 wxLogTrace( FILECONF_TRACE_MASK
,
1208 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1213 // insert a new line after the given one or in the very beginning if !pLine
1214 wxFileConfigLineList
*wxFileConfig::LineListInsert(const wxString
& str
,
1215 wxFileConfigLineList
*pLine
)
1217 wxLogTrace( FILECONF_TRACE_MASK
,
1218 _T(" ** Inserting Line '%s' after '%s'"),
1220 ((pLine
) ? pLine
->Text().c_str() : wxEmptyString
) );
1221 wxLogTrace( FILECONF_TRACE_MASK
,
1223 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1224 wxLogTrace( FILECONF_TRACE_MASK
,
1226 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1228 if ( pLine
== m_linesTail
)
1229 return LineListAppend(str
);
1231 wxFileConfigLineList
*pNewLine
= new wxFileConfigLineList(str
);
1232 if ( pLine
== NULL
)
1234 // prepend to the list
1235 pNewLine
->SetNext(m_linesHead
);
1236 m_linesHead
->SetPrev(pNewLine
);
1237 m_linesHead
= pNewLine
;
1241 // insert before pLine
1242 wxFileConfigLineList
*pNext
= pLine
->Next();
1243 pNewLine
->SetNext(pNext
);
1244 pNewLine
->SetPrev(pLine
);
1245 pNext
->SetPrev(pNewLine
);
1246 pLine
->SetNext(pNewLine
);
1249 wxLogTrace( FILECONF_TRACE_MASK
,
1251 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1252 wxLogTrace( FILECONF_TRACE_MASK
,
1254 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1259 void wxFileConfig::LineListRemove(wxFileConfigLineList
*pLine
)
1261 wxLogTrace( FILECONF_TRACE_MASK
,
1262 _T(" ** Removing Line '%s'"),
1263 pLine
->Text().c_str() );
1264 wxLogTrace( FILECONF_TRACE_MASK
,
1266 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1267 wxLogTrace( FILECONF_TRACE_MASK
,
1269 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1271 wxFileConfigLineList
*pPrev
= pLine
->Prev(),
1272 *pNext
= pLine
->Next();
1276 if ( pPrev
== NULL
)
1277 m_linesHead
= pNext
;
1279 pPrev
->SetNext(pNext
);
1283 if ( pNext
== NULL
)
1284 m_linesTail
= pPrev
;
1286 pNext
->SetPrev(pPrev
);
1288 if ( m_pRootGroup
->GetGroupLine() == pLine
)
1289 m_pRootGroup
->SetLine(m_linesHead
);
1291 wxLogTrace( FILECONF_TRACE_MASK
,
1293 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1294 wxLogTrace( FILECONF_TRACE_MASK
,
1296 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1301 bool wxFileConfig::LineListIsEmpty()
1303 return m_linesHead
== NULL
;
1306 // ============================================================================
1307 // wxFileConfig::wxFileConfigGroup
1308 // ============================================================================
1310 // ----------------------------------------------------------------------------
1312 // ----------------------------------------------------------------------------
1315 wxFileConfigGroup::wxFileConfigGroup(wxFileConfigGroup
*pParent
,
1316 const wxString
& strName
,
1317 wxFileConfig
*pConfig
)
1318 : m_aEntries(CompareEntries
),
1319 m_aSubgroups(CompareGroups
),
1322 m_pConfig
= pConfig
;
1323 m_pParent
= pParent
;
1326 m_pLastEntry
= NULL
;
1327 m_pLastGroup
= NULL
;
1330 // dtor deletes all children
1331 wxFileConfigGroup::~wxFileConfigGroup()
1334 size_t n
, nCount
= m_aEntries
.Count();
1335 for ( n
= 0; n
< nCount
; n
++ )
1336 delete m_aEntries
[n
];
1339 nCount
= m_aSubgroups
.Count();
1340 for ( n
= 0; n
< nCount
; n
++ )
1341 delete m_aSubgroups
[n
];
1344 // ----------------------------------------------------------------------------
1346 // ----------------------------------------------------------------------------
1348 void wxFileConfigGroup::SetLine(wxFileConfigLineList
*pLine
)
1350 // for a normal (i.e. not root) group this method shouldn't be called twice
1351 // unless we are resetting the line
1352 wxASSERT_MSG( !m_pParent
|| !m_pLine
|| !pLine
,
1353 _T("changing line for a non-root group?") );
1359 This is a bit complicated, so let me explain it in details. All lines that
1360 were read from the local file (the only one we will ever modify) are stored
1361 in a (doubly) linked list. Our problem is to know at which position in this
1362 list should we insert the new entries/subgroups. To solve it we keep three
1363 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1365 m_pLine points to the line containing "[group_name]"
1366 m_pLastEntry points to the last entry of this group in the local file.
1367 m_pLastGroup subgroup
1369 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1370 from the local file, the corresponding variable is set. However, if the group
1371 was read from the global file and then modified or created by the application
1372 these variables are still NULL and we need to create the corresponding lines.
1373 See the following functions (and comments preceding them) for the details of
1376 Also, when our last entry/group are deleted we need to find the new last
1377 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1378 of lines until it either founds an entry/subgroup (and this is the new last
1379 element) or the m_pLine of the group, in which case there are no more entries
1380 (or subgroups) left and m_pLast<element> becomes NULL.
1382 NB: This last problem could be avoided for entries if we added new entries
1383 immediately after m_pLine, but in this case the entries would appear
1384 backwards in the config file (OTOH, it's not that important) and as we
1385 would still need to do it for the subgroups the code wouldn't have been
1386 significantly less complicated.
1389 // Return the line which contains "[our name]". If we're still not in the list,
1390 // add our line to it immediately after the last line of our parent group if we
1391 // have it or in the very beginning if we're the root group.
1392 wxFileConfigLineList
*wxFileConfigGroup::GetGroupLine()
1394 wxLogTrace( FILECONF_TRACE_MASK
,
1395 _T(" GetGroupLine() for Group '%s'"),
1400 wxLogTrace( FILECONF_TRACE_MASK
,
1401 _T(" Getting Line item pointer") );
1403 wxFileConfigGroup
*pParent
= Parent();
1405 // this group wasn't present in local config file, add it now
1408 wxLogTrace( FILECONF_TRACE_MASK
,
1409 _T(" checking parent '%s'"),
1410 pParent
->Name().c_str() );
1412 wxString strFullName
;
1414 // add 1 to the name because we don't want to start with '/'
1415 strFullName
<< wxT("[")
1416 << FilterOutEntryName(GetFullName().c_str() + 1)
1418 m_pLine
= m_pConfig
->LineListInsert(strFullName
,
1419 pParent
->GetLastGroupLine());
1420 pParent
->SetLastGroup(this); // we're surely after all the others
1422 //else: this is the root group and so we return NULL because we don't
1423 // have any group line
1429 // Return the last line belonging to the subgroups of this group (after which
1430 // we can add a new subgroup), if we don't have any subgroups or entries our
1431 // last line is the group line (m_pLine) itself.
1432 wxFileConfigLineList
*wxFileConfigGroup::GetLastGroupLine()
1434 // if we have any subgroups, our last line is the last line of the last
1438 wxFileConfigLineList
*pLine
= m_pLastGroup
->GetLastGroupLine();
1440 wxASSERT_MSG( pLine
, _T("last group must have !NULL associated line") );
1445 // no subgroups, so the last line is the line of thelast entry (if any)
1446 return GetLastEntryLine();
1449 // return the last line belonging to the entries of this group (after which
1450 // we can add a new entry), if we don't have any entries we will add the new
1451 // one immediately after the group line itself.
1452 wxFileConfigLineList
*wxFileConfigGroup::GetLastEntryLine()
1454 wxLogTrace( FILECONF_TRACE_MASK
,
1455 _T(" GetLastEntryLine() for Group '%s'"),
1460 wxFileConfigLineList
*pLine
= m_pLastEntry
->GetLine();
1462 wxASSERT_MSG( pLine
, _T("last entry must have !NULL associated line") );
1467 // no entries: insert after the group header, if any
1468 return GetGroupLine();
1471 void wxFileConfigGroup::SetLastEntry(wxFileConfigEntry
*pEntry
)
1473 m_pLastEntry
= pEntry
;
1477 // the only situation in which a group without its own line can have
1478 // an entry is when the first entry is added to the initially empty
1479 // root pseudo-group
1480 wxASSERT_MSG( !m_pParent
, _T("unexpected for non root group") );
1482 // let the group know that it does have a line in the file now
1483 m_pLine
= pEntry
->GetLine();
1487 // ----------------------------------------------------------------------------
1489 // ----------------------------------------------------------------------------
1491 void wxFileConfigGroup::UpdateGroupAndSubgroupsLines()
1493 // update the line of this group
1494 wxFileConfigLineList
*line
= GetGroupLine();
1495 wxCHECK_RET( line
, _T("a non root group must have a corresponding line!") );
1497 // +1: skip the leading '/'
1498 line
->SetText(wxString::Format(_T("[%s]"), GetFullName().c_str() + 1));
1501 // also update all subgroups as they have this groups name in their lines
1502 const size_t nCount
= m_aSubgroups
.Count();
1503 for ( size_t n
= 0; n
< nCount
; n
++ )
1505 m_aSubgroups
[n
]->UpdateGroupAndSubgroupsLines();
1509 void wxFileConfigGroup::Rename(const wxString
& newName
)
1511 wxCHECK_RET( m_pParent
, _T("the root group can't be renamed") );
1513 m_strName
= newName
;
1515 // update the group lines recursively
1516 UpdateGroupAndSubgroupsLines();
1519 wxString
wxFileConfigGroup::GetFullName() const
1523 fullname
= Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR
+ Name();
1528 // ----------------------------------------------------------------------------
1530 // ----------------------------------------------------------------------------
1532 // use binary search because the array is sorted
1534 wxFileConfigGroup::FindEntry(const wxChar
*szName
) const
1538 hi
= m_aEntries
.Count();
1540 wxFileConfigEntry
*pEntry
;
1544 pEntry
= m_aEntries
[i
];
1546 #if wxCONFIG_CASE_SENSITIVE
1547 res
= wxStrcmp(pEntry
->Name(), szName
);
1549 res
= wxStricmp(pEntry
->Name(), szName
);
1564 wxFileConfigGroup::FindSubgroup(const wxChar
*szName
) const
1568 hi
= m_aSubgroups
.Count();
1570 wxFileConfigGroup
*pGroup
;
1574 pGroup
= m_aSubgroups
[i
];
1576 #if wxCONFIG_CASE_SENSITIVE
1577 res
= wxStrcmp(pGroup
->Name(), szName
);
1579 res
= wxStricmp(pGroup
->Name(), szName
);
1593 // ----------------------------------------------------------------------------
1594 // create a new item
1595 // ----------------------------------------------------------------------------
1597 // create a new entry and add it to the current group
1598 wxFileConfigEntry
*wxFileConfigGroup::AddEntry(const wxString
& strName
, int nLine
)
1600 wxASSERT( FindEntry(strName
) == 0 );
1602 wxFileConfigEntry
*pEntry
= new wxFileConfigEntry(this, strName
, nLine
);
1604 m_aEntries
.Add(pEntry
);
1608 // create a new group and add it to the current group
1609 wxFileConfigGroup
*wxFileConfigGroup::AddSubgroup(const wxString
& strName
)
1611 wxASSERT( FindSubgroup(strName
) == 0 );
1613 wxFileConfigGroup
*pGroup
= new wxFileConfigGroup(this, strName
, m_pConfig
);
1615 m_aSubgroups
.Add(pGroup
);
1619 // ----------------------------------------------------------------------------
1621 // ----------------------------------------------------------------------------
1624 The delete operations are _very_ slow if we delete the last item of this
1625 group (see comments before GetXXXLineXXX functions for more details),
1626 so it's much better to start with the first entry/group if we want to
1627 delete several of them.
1630 bool wxFileConfigGroup::DeleteSubgroupByName(const wxChar
*szName
)
1632 wxFileConfigGroup
* const pGroup
= FindSubgroup(szName
);
1634 return pGroup
? DeleteSubgroup(pGroup
) : false;
1637 // Delete the subgroup and remove all references to it from
1638 // other data structures.
1639 bool wxFileConfigGroup::DeleteSubgroup(wxFileConfigGroup
*pGroup
)
1641 wxCHECK_MSG( pGroup
, false, _T("deleting non existing group?") );
1643 wxLogTrace( FILECONF_TRACE_MASK
,
1644 _T("Deleting group '%s' from '%s'"),
1645 pGroup
->Name().c_str(),
1648 wxLogTrace( FILECONF_TRACE_MASK
,
1649 _T(" (m_pLine) = prev: %p, this %p, next %p"),
1650 ((m_pLine
) ? m_pLine
->Prev() : 0),
1652 ((m_pLine
) ? m_pLine
->Next() : 0) );
1653 wxLogTrace( FILECONF_TRACE_MASK
,
1655 ((m_pLine
) ? m_pLine
->Text().c_str() : wxEmptyString
) );
1657 // delete all entries...
1658 size_t nCount
= pGroup
->m_aEntries
.Count();
1660 wxLogTrace(FILECONF_TRACE_MASK
,
1661 _T("Removing %lu entries"), (unsigned long)nCount
);
1663 for ( size_t nEntry
= 0; nEntry
< nCount
; nEntry
++ )
1665 wxFileConfigLineList
*pLine
= pGroup
->m_aEntries
[nEntry
]->GetLine();
1669 wxLogTrace( FILECONF_TRACE_MASK
,
1671 pLine
->Text().c_str() );
1672 m_pConfig
->LineListRemove(pLine
);
1676 // ...and subgroups of this subgroup
1677 nCount
= pGroup
->m_aSubgroups
.Count();
1679 wxLogTrace( FILECONF_TRACE_MASK
,
1680 _T("Removing %lu subgroups"), (unsigned long)nCount
);
1682 for ( size_t nGroup
= 0; nGroup
< nCount
; nGroup
++ )
1684 pGroup
->DeleteSubgroup(pGroup
->m_aSubgroups
[0]);
1687 // and then finally the group itself
1688 wxFileConfigLineList
*pLine
= pGroup
->m_pLine
;
1691 wxLogTrace( FILECONF_TRACE_MASK
,
1692 _T(" Removing line for group '%s' : '%s'"),
1693 pGroup
->Name().c_str(),
1694 pLine
->Text().c_str() );
1695 wxLogTrace( FILECONF_TRACE_MASK
,
1696 _T(" Removing from group '%s' : '%s'"),
1698 ((m_pLine
) ? m_pLine
->Text().c_str() : wxEmptyString
) );
1700 // notice that we may do this test inside the previous "if"
1701 // because the last entry's line is surely !NULL
1702 if ( pGroup
== m_pLastGroup
)
1704 wxLogTrace( FILECONF_TRACE_MASK
,
1705 _T(" Removing last group") );
1707 // our last entry is being deleted, so find the last one which
1708 // stays by going back until we find a subgroup or reach the
1710 const size_t nSubgroups
= m_aSubgroups
.Count();
1712 m_pLastGroup
= NULL
;
1713 for ( wxFileConfigLineList
*pl
= pLine
->Prev();
1714 pl
&& pl
!= m_pLine
&& !m_pLastGroup
;
1717 // does this line belong to our subgroup?
1718 for ( size_t n
= 0; n
< nSubgroups
; n
++ )
1720 // do _not_ call GetGroupLine! we don't want to add it to
1721 // the local file if it's not already there
1722 if ( m_aSubgroups
[n
]->m_pLine
== pl
)
1724 m_pLastGroup
= m_aSubgroups
[n
];
1731 m_pConfig
->LineListRemove(pLine
);
1735 wxLogTrace( FILECONF_TRACE_MASK
,
1736 _T(" No line entry for Group '%s'?"),
1737 pGroup
->Name().c_str() );
1740 m_aSubgroups
.Remove(pGroup
);
1746 bool wxFileConfigGroup::DeleteEntry(const wxChar
*szName
)
1748 wxFileConfigEntry
*pEntry
= FindEntry(szName
);
1751 // entry doesn't exist, nothing to do
1755 wxFileConfigLineList
*pLine
= pEntry
->GetLine();
1756 if ( pLine
!= NULL
) {
1757 // notice that we may do this test inside the previous "if" because the
1758 // last entry's line is surely !NULL
1759 if ( pEntry
== m_pLastEntry
) {
1760 // our last entry is being deleted - find the last one which stays
1761 wxASSERT( m_pLine
!= NULL
); // if we have an entry with !NULL pLine...
1763 // go back until we find another entry or reach the group's line
1764 wxFileConfigEntry
*pNewLast
= NULL
;
1765 size_t n
, nEntries
= m_aEntries
.Count();
1766 wxFileConfigLineList
*pl
;
1767 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1768 // is it our subgroup?
1769 for ( n
= 0; (pNewLast
== NULL
) && (n
< nEntries
); n
++ ) {
1770 if ( m_aEntries
[n
]->GetLine() == m_pLine
)
1771 pNewLast
= m_aEntries
[n
];
1774 if ( pNewLast
!= NULL
) // found?
1778 if ( pl
== m_pLine
) {
1779 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1781 // we've reached the group line without finding any subgroups
1782 m_pLastEntry
= NULL
;
1785 m_pLastEntry
= pNewLast
;
1788 m_pConfig
->LineListRemove(pLine
);
1791 m_aEntries
.Remove(pEntry
);
1797 // ============================================================================
1798 // wxFileConfig::wxFileConfigEntry
1799 // ============================================================================
1801 // ----------------------------------------------------------------------------
1803 // ----------------------------------------------------------------------------
1804 wxFileConfigEntry::wxFileConfigEntry(wxFileConfigGroup
*pParent
,
1805 const wxString
& strName
,
1807 : m_strName(strName
)
1809 wxASSERT( !strName
.empty() );
1811 m_pParent
= pParent
;
1815 m_bHasValue
= false;
1817 m_bImmutable
= strName
[0] == wxCONFIG_IMMUTABLE_PREFIX
;
1819 m_strName
.erase(0, 1); // remove first character
1822 // ----------------------------------------------------------------------------
1824 // ----------------------------------------------------------------------------
1826 void wxFileConfigEntry::SetLine(wxFileConfigLineList
*pLine
)
1828 if ( m_pLine
!= NULL
) {
1829 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1830 Name().c_str(), m_pParent
->GetFullName().c_str());
1834 Group()->SetLastEntry(this);
1837 // second parameter is false if we read the value from file and prevents the
1838 // entry from being marked as 'dirty'
1839 void wxFileConfigEntry::SetValue(const wxString
& strValue
, bool bUser
)
1841 if ( bUser
&& IsImmutable() )
1843 wxLogWarning( _("attempt to change immutable key '%s' ignored."),
1848 // do nothing if it's the same value: but don't test for it if m_bHasValue
1849 // hadn't been set yet or we'd never write empty values to the file
1850 if ( m_bHasValue
&& strValue
== m_strValue
)
1854 m_strValue
= strValue
;
1858 wxString strValFiltered
;
1860 if ( Group()->Config()->GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS
)
1862 strValFiltered
= strValue
;
1865 strValFiltered
= FilterOutValue(strValue
);
1869 strLine
<< FilterOutEntryName(m_strName
) << wxT('=') << strValFiltered
;
1873 // entry was read from the local config file, just modify the line
1874 m_pLine
->SetText(strLine
);
1876 else // this entry didn't exist in the local file
1878 // add a new line to the file: note that line returned by
1879 // GetLastEntryLine() may be NULL if we're in the root group and it
1880 // doesn't have any entries yet, but this is ok as passing NULL
1881 // line to LineListInsert() means to prepend new line to the list
1882 wxFileConfigLineList
*line
= Group()->GetLastEntryLine();
1883 m_pLine
= Group()->Config()->LineListInsert(strLine
, line
);
1885 Group()->SetLastEntry(this);
1890 // ============================================================================
1892 // ============================================================================
1894 // ----------------------------------------------------------------------------
1895 // compare functions for array sorting
1896 // ----------------------------------------------------------------------------
1898 int CompareEntries(wxFileConfigEntry
*p1
, wxFileConfigEntry
*p2
)
1900 #if wxCONFIG_CASE_SENSITIVE
1901 return wxStrcmp(p1
->Name(), p2
->Name());
1903 return wxStricmp(p1
->Name(), p2
->Name());
1907 int CompareGroups(wxFileConfigGroup
*p1
, wxFileConfigGroup
*p2
)
1909 #if wxCONFIG_CASE_SENSITIVE
1910 return wxStrcmp(p1
->Name(), p2
->Name());
1912 return wxStricmp(p1
->Name(), p2
->Name());
1916 // ----------------------------------------------------------------------------
1918 // ----------------------------------------------------------------------------
1920 // undo FilterOutValue
1921 static wxString
FilterInValue(const wxString
& str
)
1924 strResult
.Alloc(str
.Len());
1926 bool bQuoted
= !str
.empty() && str
[0] == '"';
1928 for ( size_t n
= bQuoted
? 1 : 0; n
< str
.Len(); n
++ ) {
1929 if ( str
[n
] == wxT('\\') ) {
1930 switch ( str
[++n
] ) {
1932 strResult
+= wxT('\n');
1936 strResult
+= wxT('\r');
1940 strResult
+= wxT('\t');
1944 strResult
+= wxT('\\');
1948 strResult
+= wxT('"');
1953 if ( str
[n
] != wxT('"') || !bQuoted
)
1954 strResult
+= str
[n
];
1955 else if ( n
!= str
.Len() - 1 ) {
1956 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1959 //else: it's the last quote of a quoted string, ok
1966 // quote the string before writing it to file
1967 static wxString
FilterOutValue(const wxString
& str
)
1973 strResult
.Alloc(str
.Len());
1975 // quoting is necessary to preserve spaces in the beginning of the string
1976 bool bQuote
= wxIsspace(str
[0]) || str
[0] == wxT('"');
1979 strResult
+= wxT('"');
1982 for ( size_t n
= 0; n
< str
.Len(); n
++ ) {
2005 //else: fall through
2008 strResult
+= str
[n
];
2009 continue; // nothing special to do
2012 // we get here only for special characters
2013 strResult
<< wxT('\\') << c
;
2017 strResult
+= wxT('"');
2022 // undo FilterOutEntryName
2023 static wxString
FilterInEntryName(const wxString
& str
)
2026 strResult
.Alloc(str
.Len());
2028 for ( const wxChar
*pc
= str
.c_str(); *pc
!= '\0'; pc
++ ) {
2029 if ( *pc
== wxT('\\') )
2038 // sanitize entry or group name: insert '\\' before any special characters
2039 static wxString
FilterOutEntryName(const wxString
& str
)
2042 strResult
.Alloc(str
.Len());
2044 for ( const wxChar
*pc
= str
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
2045 const wxChar c
= *pc
;
2047 // we explicitly allow some of "safe" chars and 8bit ASCII characters
2048 // which will probably never have special meaning and with which we can't
2049 // use isalnum() anyhow (in ASCII built, in Unicode it's just fine)
2051 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
2052 // should *not* be quoted
2055 ((unsigned char)c
< 127) &&
2057 !wxIsalnum(c
) && !wxStrchr(wxT("@_/-!.*%"), c
) )
2059 strResult
+= wxT('\\');
2068 // we can't put ?: in the ctor initializer list because it confuses some
2069 // broken compilers (Borland C++)
2070 static wxString
GetAppName(const wxString
& appName
)
2072 if ( !appName
&& wxTheApp
)
2073 return wxTheApp
->GetAppName();
2078 #endif // wxUSE_CONFIG