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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
14 #pragma implementation "fileconf.h"
17 // ----------------------------------------------------------------------------
19 // ----------------------------------------------------------------------------
21 #include "wx/wxprec.h"
27 #if wxUSE_CONFIG && wxUSE_FILECONFIG
30 #include "wx/string.h"
35 #include "wx/dynarray.h"
38 #include "wx/textfile.h"
39 #include "wx/memtext.h"
40 #include "wx/config.h"
41 #include "wx/fileconf.h"
42 #include "wx/filefn.h"
45 #include "wx/stream.h"
46 #endif // wxUSE_STREAMS
48 #include "wx/utils.h" // for wxGetHomeDir
50 #if defined(__WXMAC__)
51 #include "wx/mac/private.h" // includes mac headers
54 #if defined(__WXMSW__)
55 #include "wx/msw/private.h"
65 // ----------------------------------------------------------------------------
67 // ----------------------------------------------------------------------------
68 #define CONST_CAST ((wxFileConfig *)this)->
70 // ----------------------------------------------------------------------------
72 // ----------------------------------------------------------------------------
78 // ----------------------------------------------------------------------------
79 // global functions declarations
80 // ----------------------------------------------------------------------------
82 // compare functions for sorting the arrays
83 static int LINKAGEMODE
CompareEntries(wxFileConfigEntry
*p1
, wxFileConfigEntry
*p2
);
84 static int LINKAGEMODE
CompareGroups(wxFileConfigGroup
*p1
, wxFileConfigGroup
*p2
);
87 static wxString
FilterInValue(const wxString
& str
);
88 static wxString
FilterOutValue(const wxString
& str
);
90 static wxString
FilterInEntryName(const wxString
& str
);
91 static wxString
FilterOutEntryName(const wxString
& str
);
93 // get the name to use in wxFileConfig ctor
94 static wxString
GetAppName(const wxString
& appname
);
96 // ============================================================================
98 // ============================================================================
100 // ----------------------------------------------------------------------------
101 // "template" array types
102 // ----------------------------------------------------------------------------
104 #ifdef WXMAKINGDLL_BASE
105 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(wxFileConfigEntry
*, ArrayEntries
,
107 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(wxFileConfigGroup
*, ArrayGroups
,
110 WX_DEFINE_SORTED_ARRAY(wxFileConfigEntry
*, ArrayEntries
);
111 WX_DEFINE_SORTED_ARRAY(wxFileConfigGroup
*, ArrayGroups
);
114 // ----------------------------------------------------------------------------
115 // wxFileConfigLineList
116 // ----------------------------------------------------------------------------
118 // we store all lines of the local config file as a linked list in memory
119 class wxFileConfigLineList
122 void SetNext(wxFileConfigLineList
*pNext
) { m_pNext
= pNext
; }
123 void SetPrev(wxFileConfigLineList
*pPrev
) { m_pPrev
= pPrev
; }
126 wxFileConfigLineList(const wxString
& str
,
127 wxFileConfigLineList
*pNext
= NULL
) : m_strLine(str
)
128 { SetNext(pNext
); SetPrev(NULL
); }
130 // next/prev nodes in the linked list
131 wxFileConfigLineList
*Next() const { return m_pNext
; }
132 wxFileConfigLineList
*Prev() const { return m_pPrev
; }
134 // get/change lines text
135 void SetText(const wxString
& str
) { m_strLine
= str
; }
136 const wxString
& Text() const { return m_strLine
; }
139 wxString m_strLine
; // line contents
140 wxFileConfigLineList
*m_pNext
, // next node
141 *m_pPrev
; // previous one
143 DECLARE_NO_COPY_CLASS(wxFileConfigLineList
)
146 // ----------------------------------------------------------------------------
147 // wxFileConfigEntry: a name/value pair
148 // ----------------------------------------------------------------------------
150 class wxFileConfigEntry
153 wxFileConfigGroup
*m_pParent
; // group that contains us
155 wxString m_strName
, // entry name
157 bool m_bDirty
:1, // changed since last read?
158 m_bImmutable
:1, // can be overriden locally?
159 m_bHasValue
:1; // set after first call to SetValue()
161 int m_nLine
; // used if m_pLine == NULL only
163 // pointer to our line in the linked list or NULL if it was found in global
164 // file (which we don't modify)
165 wxFileConfigLineList
*m_pLine
;
168 wxFileConfigEntry(wxFileConfigGroup
*pParent
,
169 const wxString
& strName
, int nLine
);
172 const wxString
& Name() const { return m_strName
; }
173 const wxString
& Value() const { return m_strValue
; }
174 wxFileConfigGroup
*Group() const { return m_pParent
; }
175 bool IsDirty() const { return m_bDirty
; }
176 bool IsImmutable() const { return m_bImmutable
; }
177 bool IsLocal() const { return m_pLine
!= 0; }
178 int Line() const { return m_nLine
; }
179 wxFileConfigLineList
*
180 GetLine() const { return m_pLine
; }
182 // modify entry attributes
183 void SetValue(const wxString
& strValue
, bool bUser
= true);
185 void SetLine(wxFileConfigLineList
*pLine
);
187 DECLARE_NO_COPY_CLASS(wxFileConfigEntry
)
190 // ----------------------------------------------------------------------------
191 // wxFileConfigGroup: container of entries and other groups
192 // ----------------------------------------------------------------------------
194 class wxFileConfigGroup
197 wxFileConfig
*m_pConfig
; // config object we belong to
198 wxFileConfigGroup
*m_pParent
; // parent group (NULL for root group)
199 ArrayEntries m_aEntries
; // entries in this group
200 ArrayGroups m_aSubgroups
; // subgroups
201 wxString m_strName
; // group's name
202 bool m_bDirty
; // if false => all subgroups are not dirty
203 wxFileConfigLineList
*m_pLine
; // pointer to our line in the linked list
204 wxFileConfigEntry
*m_pLastEntry
; // last entry/subgroup of this group in the
205 wxFileConfigGroup
*m_pLastGroup
; // local file (we insert new ones after it)
207 // DeleteSubgroupByName helper
208 bool DeleteSubgroup(wxFileConfigGroup
*pGroup
);
212 wxFileConfigGroup(wxFileConfigGroup
*pParent
, const wxString
& strName
, wxFileConfig
*);
214 // dtor deletes all entries and subgroups also
215 ~wxFileConfigGroup();
218 const wxString
& Name() const { return m_strName
; }
219 wxFileConfigGroup
*Parent() const { return m_pParent
; }
220 wxFileConfig
*Config() const { return m_pConfig
; }
221 bool IsDirty() const { return m_bDirty
; }
223 const ArrayEntries
& Entries() const { return m_aEntries
; }
224 const ArrayGroups
& Groups() const { return m_aSubgroups
; }
225 bool IsEmpty() const { return Entries().IsEmpty() && Groups().IsEmpty(); }
227 // find entry/subgroup (NULL if not found)
228 wxFileConfigGroup
*FindSubgroup(const wxChar
*szName
) const;
229 wxFileConfigEntry
*FindEntry (const wxChar
*szName
) const;
231 // delete entry/subgroup, return false if doesn't exist
232 bool DeleteSubgroupByName(const wxChar
*szName
);
233 bool DeleteEntry(const wxChar
*szName
);
235 // create new entry/subgroup returning pointer to newly created element
236 wxFileConfigGroup
*AddSubgroup(const wxString
& strName
);
237 wxFileConfigEntry
*AddEntry (const wxString
& strName
, int nLine
= wxNOT_FOUND
);
239 // will also recursively set parent's dirty flag
241 void SetLine(wxFileConfigLineList
*pLine
);
243 // rename: no checks are done to ensure that the name is unique!
244 void Rename(const wxString
& newName
);
247 wxString
GetFullName() const;
249 // get the last line belonging to an entry/subgroup of this group
250 wxFileConfigLineList
*GetGroupLine(); // line which contains [group]
251 wxFileConfigLineList
*GetLastEntryLine(); // after which our subgroups start
252 wxFileConfigLineList
*GetLastGroupLine(); // after which the next group starts
254 // called by entries/subgroups when they're created/deleted
255 void SetLastEntry(wxFileConfigEntry
*pEntry
);
256 void SetLastGroup(wxFileConfigGroup
*pGroup
)
257 { m_pLastGroup
= pGroup
; }
259 DECLARE_NO_COPY_CLASS(wxFileConfigGroup
)
262 // ============================================================================
264 // ============================================================================
266 // ----------------------------------------------------------------------------
268 // ----------------------------------------------------------------------------
269 wxString wxFileConfig
::GetGlobalDir()
273 #ifdef __VMS__ // Note if __VMS is defined __UNIX is also defined
274 strDir
= wxT("sys$manager:");
275 #elif defined(__WXMAC__)
276 strDir
= wxMacFindFolder( (short) kOnSystemDisk
, kPreferencesFolderType
, kDontCreateFolder
) ;
277 #elif defined( __UNIX__ )
278 strDir
= wxT("/etc/");
279 #elif defined(__WXPM__)
280 ULONG aulSysInfo
[QSV_MAX
] = {0};
284 rc
= DosQuerySysInfo( 1L, QSV_MAX
, (PVOID
)aulSysInfo
, sizeof(ULONG
)*QSV_MAX
);
287 drive
= aulSysInfo
[QSV_BOOT_DRIVE
- 1];
288 strDir
.Printf(wxT("%c:\\OS2\\"), 'A'+drive
-1);
290 #elif defined(__WXSTUBS__)
291 wxASSERT_MSG( false, wxT("TODO") ) ;
292 #elif defined(__DOS__)
293 // There's no such thing as global cfg dir in MS-DOS, let's return
294 // current directory (FIXME_MGL?)
297 wxChar szWinDir
[MAX_PATH
];
298 ::GetWindowsDirectory(szWinDir
, MAX_PATH
);
302 #endif // Unix/Windows
307 wxString wxFileConfig
::GetLocalDir()
311 #if defined(__WXMAC__) || defined(__DOS__)
312 // no local dir concept on Mac OS 9 or MS-DOS
313 return GetGlobalDir() ;
315 wxGetHomeDir(&strDir
);
319 if (strDir
.Last() != wxT(']'))
321 if (strDir
.Last() != wxT('/')) strDir
<< wxT('/');
323 if (strDir
.Last() != wxT('\\')) strDir
<< wxT('\\');
330 wxString wxFileConfig
::GetGlobalFileName(const wxChar
*szFile
)
332 wxString str
= GetGlobalDir();
335 if ( wxStrchr(szFile
, wxT('.')) == NULL
)
336 #if defined( __WXMAC__ )
337 str
<< wxT(" Preferences") ;
338 #elif defined( __UNIX__ )
347 wxString wxFileConfig
::GetLocalFileName(const wxChar
*szFile
)
350 // On VMS I saw the problem that the home directory was appended
351 // twice for the configuration file. Does that also happen for
353 wxString str
= wxT( '.' );
355 wxString str
= GetLocalDir();
358 #if defined( __UNIX__ ) && !defined( __VMS ) && !defined( __WXMAC__ )
364 #if defined(__WINDOWS__) || defined(__DOS__)
365 if ( wxStrchr(szFile
, wxT('.')) == NULL
)
370 str
<< wxT(" Preferences") ;
376 // ----------------------------------------------------------------------------
378 // ----------------------------------------------------------------------------
380 void wxFileConfig
::Init()
383 m_pRootGroup
= new wxFileConfigGroup(NULL
, wxT(""), this);
388 // It's not an error if (one of the) file(s) doesn't exist.
390 // parse the global file
391 if ( !m_strGlobalFile
.IsEmpty() && wxFile
::Exists(m_strGlobalFile
) )
393 wxTextFile
fileGlobal(m_strGlobalFile
);
395 if ( fileGlobal
.Open(m_conv
/*ignored in ANSI build*/) )
397 Parse(fileGlobal
, false /* global */);
402 wxLogWarning(_("can't open global configuration file '%s'."), m_strGlobalFile
.c_str());
406 // parse the local file
407 if ( !m_strLocalFile
.IsEmpty() && wxFile
::Exists(m_strLocalFile
) )
409 wxTextFile
fileLocal(m_strLocalFile
);
410 if ( fileLocal
.Open(m_conv
/*ignored in ANSI build*/) )
412 Parse(fileLocal
, true /* local */);
417 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
.IsEmpty() && (style
& wxCONFIG_USE_LOCAL_FILE
) )
434 m_strLocalFile
= GetLocalFileName(GetAppName());
436 if ( m_strGlobalFile
.IsEmpty() && (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
.IsEmpty() )
442 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE
);
444 if ( !m_strGlobalFile
.IsEmpty() )
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
.IsEmpty() && !wxIsAbsolutePath(m_strLocalFile
) )
453 wxString strLocal
= m_strLocalFile
;
454 m_strLocalFile
= GetLocalDir();
455 m_strLocalFile
<< strLocal
;
458 if ( !m_strGlobalFile
.IsEmpty() && !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
, wxT(""), this);
485 // translate everything to the current (platform-dependent) line
486 // termination character
494 inStream
.Read(buf
, WXSIZEOF(buf
));
496 const wxStreamError err
= inStream
.GetLastError();
498 if ( err
!= wxSTREAM_NO_ERROR
&& err
!= wxSTREAM_EOF
)
500 wxLogError(_("Error reading config options."));
504 strTmp
.append(wxConvertMB2WX(buf
), inStream
.LastRead());
506 while ( !inStream
.Eof() );
508 strTrans
= wxTextBuffer
::Translate(strTmp
);
511 wxMemoryText memText
;
513 // Now we can add the text to the memory text. To do this we extract line
514 // by line from the translated string, until we've reached the end.
516 // VZ: all this is horribly inefficient, we should do the translation on
517 // the fly in one pass saving both memory and time (TODO)
519 const wxChar
*pEOL
= wxTextBuffer
::GetEOL(wxTextBuffer
::typeDefault
);
520 const size_t EOLLen
= wxStrlen(pEOL
);
522 int posLineStart
= strTrans
.Find(pEOL
);
523 while ( posLineStart
!= -1 )
525 wxString
line(strTrans
.Left(posLineStart
));
527 memText
.AddLine(line
);
529 strTrans
= strTrans
.Mid(posLineStart
+ EOLLen
);
531 posLineStart
= strTrans
.Find(pEOL
);
534 // also add whatever we have left in the translated string.
535 memText
.AddLine(strTrans
);
537 // Finally we can parse it all.
538 Parse(memText
, true /* local */);
543 #endif // wxUSE_STREAMS
545 void wxFileConfig
::CleanUp()
549 wxFileConfigLineList
*pCur
= m_linesHead
;
550 while ( pCur
!= NULL
) {
551 wxFileConfigLineList
*pNext
= pCur
->Next();
557 wxFileConfig
::~wxFileConfig()
564 // ----------------------------------------------------------------------------
565 // parse a config file
566 // ----------------------------------------------------------------------------
568 void wxFileConfig
::Parse(wxTextBuffer
& buffer
, bool bLocal
)
570 const wxChar
*pStart
;
574 size_t nLineCount
= buffer
.GetLineCount();
576 for ( size_t n
= 0; n
< nLineCount
; n
++ )
580 // add the line to linked list
583 LineListAppend(strLine
);
585 // let the root group have it start line as well
588 m_pCurrentGroup
->SetLine(m_linesTail
);
593 // skip leading spaces
594 for ( pStart
= strLine
; wxIsspace(*pStart
); pStart
++ )
597 // skip blank/comment lines
598 if ( *pStart
== wxT('\0')|| *pStart
== wxT(';') || *pStart
== wxT('#') )
601 if ( *pStart
== wxT('[') ) { // a new group
604 while ( *++pEnd
!= wxT(']') ) {
605 if ( *pEnd
== wxT('\\') ) {
606 // the next char is escaped, so skip it even if it is ']'
610 if ( *pEnd
== wxT('\n') || *pEnd
== wxT('\0') ) {
611 // we reached the end of line, break out of the loop
616 if ( *pEnd
!= wxT(']') ) {
617 wxLogError(_("file '%s': unexpected character %c at line %d."),
618 buffer
.GetName(), *pEnd
, n
+ 1);
619 continue; // skip this line
622 // group name here is always considered as abs path
625 strGroup
<< wxCONFIG_PATH_SEPARATOR
626 << FilterInEntryName(wxString(pStart
, pEnd
- pStart
));
628 // will create it if doesn't yet exist
633 if ( m_pCurrentGroup
->Parent() )
634 m_pCurrentGroup
->Parent()->SetLastGroup(m_pCurrentGroup
);
635 m_pCurrentGroup
->SetLine(m_linesTail
);
638 // check that there is nothing except comments left on this line
640 while ( *++pEnd
!= wxT('\0') && bCont
) {
649 // ignore whitespace ('\n' impossible here)
653 wxLogWarning(_("file '%s', line %d: '%s' ignored after group header."),
654 buffer
.GetName(), n
+ 1, pEnd
);
660 const wxChar
*pEnd
= pStart
;
661 while ( *pEnd
&& *pEnd
!= wxT('=') /* && !wxIsspace(*pEnd)*/ ) {
662 if ( *pEnd
== wxT('\\') ) {
663 // next character may be space or not - still take it because it's
664 // quoted (unless there is nothing)
667 // the error message will be given below anyhow
675 wxString
strKey(FilterInEntryName(wxString(pStart
, pEnd
).Trim()));
678 while ( wxIsspace(*pEnd
) )
681 if ( *pEnd
++ != wxT('=') ) {
682 wxLogError(_("file '%s', line %d: '=' expected."),
683 buffer
.GetName(), n
+ 1);
686 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strKey
);
688 if ( pEntry
== NULL
) {
690 pEntry
= m_pCurrentGroup
->AddEntry(strKey
, n
);
693 if ( bLocal
&& pEntry
->IsImmutable() ) {
694 // immutable keys can't be changed by user
695 wxLogWarning(_("file '%s', line %d: value for immutable key '%s' ignored."),
696 buffer
.GetName(), n
+ 1, strKey
.c_str());
699 // the condition below catches the cases (a) and (b) but not (c):
700 // (a) global key found second time in global file
701 // (b) key found second (or more) time in local file
702 // (c) key from global file now found in local one
703 // which is exactly what we want.
704 else if ( !bLocal
|| pEntry
->IsLocal() ) {
705 wxLogWarning(_("file '%s', line %d: key '%s' was first found at line %d."),
706 buffer
.GetName(), n
+ 1, strKey
.c_str(), pEntry
->Line());
712 pEntry
->SetLine(m_linesTail
);
715 while ( wxIsspace(*pEnd
) )
718 wxString value
= pEnd
;
719 if ( !(GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS
) )
720 value
= FilterInValue(value
);
722 pEntry
->SetValue(value
, false);
728 // ----------------------------------------------------------------------------
730 // ----------------------------------------------------------------------------
732 void wxFileConfig
::SetRootPath()
735 m_pCurrentGroup
= m_pRootGroup
;
738 void wxFileConfig
::SetPath(const wxString
& strPath
)
740 wxArrayString aParts
;
742 if ( strPath
.IsEmpty() ) {
747 if ( strPath
[0] == wxCONFIG_PATH_SEPARATOR
) {
749 wxSplitPath(aParts
, strPath
);
752 // relative path, combine with current one
753 wxString strFullPath
= m_strPath
;
754 strFullPath
<< wxCONFIG_PATH_SEPARATOR
<< strPath
;
755 wxSplitPath(aParts
, strFullPath
);
758 // change current group
760 m_pCurrentGroup
= m_pRootGroup
;
761 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
762 wxFileConfigGroup
*pNextGroup
= m_pCurrentGroup
->FindSubgroup(aParts
[n
]);
763 if ( pNextGroup
== NULL
)
764 pNextGroup
= m_pCurrentGroup
->AddSubgroup(aParts
[n
]);
765 m_pCurrentGroup
= pNextGroup
;
768 // recombine path parts in one variable
770 for ( n
= 0; n
< aParts
.Count(); n
++ ) {
771 m_strPath
<< wxCONFIG_PATH_SEPARATOR
<< aParts
[n
];
775 // ----------------------------------------------------------------------------
777 // ----------------------------------------------------------------------------
779 bool wxFileConfig
::GetFirstGroup(wxString
& str
, long& lIndex
) const
782 return GetNextGroup(str
, lIndex
);
785 bool wxFileConfig
::GetNextGroup (wxString
& str
, long& lIndex
) const
787 if ( size_t(lIndex
) < m_pCurrentGroup
->Groups().Count() ) {
788 str
= m_pCurrentGroup
->Groups()[(size_t)lIndex
++]->Name();
795 bool wxFileConfig
::GetFirstEntry(wxString
& str
, long& lIndex
) const
798 return GetNextEntry(str
, lIndex
);
801 bool wxFileConfig
::GetNextEntry (wxString
& str
, long& lIndex
) const
803 if ( size_t(lIndex
) < m_pCurrentGroup
->Entries().Count() ) {
804 str
= m_pCurrentGroup
->Entries()[(size_t)lIndex
++]->Name();
811 size_t wxFileConfig
::GetNumberOfEntries(bool bRecursive
) const
813 size_t n
= m_pCurrentGroup
->Entries().Count();
815 wxFileConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
816 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
817 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
818 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
819 n
+= GetNumberOfEntries(true);
820 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
827 size_t wxFileConfig
::GetNumberOfGroups(bool bRecursive
) const
829 size_t n
= m_pCurrentGroup
->Groups().Count();
831 wxFileConfigGroup
*pOldCurrentGroup
= m_pCurrentGroup
;
832 size_t nSubgroups
= m_pCurrentGroup
->Groups().Count();
833 for ( size_t nGroup
= 0; nGroup
< nSubgroups
; nGroup
++ ) {
834 CONST_CAST m_pCurrentGroup
= m_pCurrentGroup
->Groups()[nGroup
];
835 n
+= GetNumberOfGroups(true);
836 CONST_CAST m_pCurrentGroup
= pOldCurrentGroup
;
843 // ----------------------------------------------------------------------------
844 // tests for existence
845 // ----------------------------------------------------------------------------
847 bool wxFileConfig
::HasGroup(const wxString
& strName
) const
849 wxConfigPathChanger
path(this, strName
);
851 wxFileConfigGroup
*pGroup
= m_pCurrentGroup
->FindSubgroup(path
.Name());
852 return pGroup
!= NULL
;
855 bool wxFileConfig
::HasEntry(const wxString
& strName
) const
857 wxConfigPathChanger
path(this, strName
);
859 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
860 return pEntry
!= NULL
;
863 // ----------------------------------------------------------------------------
865 // ----------------------------------------------------------------------------
867 bool wxFileConfig
::DoReadString(const wxString
& key
, wxString
* pStr
) const
869 wxConfigPathChanger
path(this, key
);
871 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(path
.Name());
872 if (pEntry
== NULL
) {
876 *pStr
= pEntry
->Value();
881 bool wxFileConfig
::DoReadLong(const wxString
& key
, long *pl
) const
884 if ( !Read(key
, &str
) )
887 // extra spaces shouldn't prevent us from reading numeric values
890 return str
.ToLong(pl
);
893 bool wxFileConfig
::DoWriteString(const wxString
& key
, const wxString
& szValue
)
895 wxConfigPathChanger
path(this, key
);
896 wxString strName
= path
.Name();
898 wxLogTrace( _T("wxFileConfig"),
899 _T(" Writing String '%s' = '%s' to Group '%s'"),
904 if ( strName
.IsEmpty() )
906 // setting the value of a group is an error
908 wxASSERT_MSG( wxIsEmpty(szValue
), wxT("can't set value of a group!") );
910 // ... except if it's empty in which case it's a way to force it's creation
912 wxLogTrace( _T("wxFileConfig"),
913 _T(" Creating group %s"),
914 m_pCurrentGroup
->Name().c_str() );
916 m_pCurrentGroup
->SetDirty();
918 // this will add a line for this group if it didn't have it before
920 (void)m_pCurrentGroup
->GetGroupLine();
925 // check that the name is reasonable
927 if ( strName
[0u] == wxCONFIG_IMMUTABLE_PREFIX
)
929 wxLogError( _("Config entry name cannot start with '%c'."),
930 wxCONFIG_IMMUTABLE_PREFIX
);
934 wxFileConfigEntry
*pEntry
= m_pCurrentGroup
->FindEntry(strName
);
938 wxLogTrace( _T("wxFileConfig"),
939 _T(" Adding Entry %s"),
941 pEntry
= m_pCurrentGroup
->AddEntry(strName
);
944 wxLogTrace( _T("wxFileConfig"),
945 _T(" Setting value %s"),
947 pEntry
->SetValue(szValue
);
953 bool wxFileConfig
::DoWriteLong(const wxString
& key
, long lValue
)
955 return Write(key
, wxString
::Format(_T("%ld"), lValue
));
958 bool wxFileConfig
::Flush(bool /* bCurrentOnly */)
960 if ( LineListIsEmpty() || !m_pRootGroup
->IsDirty() || !m_strLocalFile
)
963 // set the umask if needed
964 wxCHANGE_UMASK(m_umask
);
966 wxTempFile
file(m_strLocalFile
);
968 if ( !file
.IsOpened() )
970 wxLogError(_("can't open user configuration file."));
974 // write all strings to file
975 for ( wxFileConfigLineList
*p
= m_linesHead
; p
!= NULL
; p
= p
->Next() )
977 wxString line
= p
->Text();
978 line
+= wxTextFile
::GetEOL();
979 if ( !file
.Write(line
, m_conv
) )
981 wxLogError(_("can't write user configuration file."));
986 bool ret
= file
.Commit();
988 #if defined(__WXMAC__)
992 FSCatalogInfo catInfo
;
995 if ( wxMacPathToFSRef( m_strLocalFile
, &fsRef
) == noErr
)
997 if ( FSGetCatalogInfo (&fsRef
, kFSCatInfoFinderInfo
, &catInfo
, NULL
, NULL
, NULL
) == noErr
)
999 finfo
= (FileInfo
*)&catInfo
.finderInfo
;
1000 finfo
->fileType
= 'TEXT' ;
1001 finfo
->fileCreator
= 'ttxt' ;
1002 FSSetCatalogInfo( &fsRef
, kFSCatInfoFinderInfo
, &catInfo
) ;
1011 // ----------------------------------------------------------------------------
1012 // renaming groups/entries
1013 // ----------------------------------------------------------------------------
1015 bool wxFileConfig
::RenameEntry(const wxString
& oldName
,
1016 const wxString
& newName
)
1018 // check that the entry exists
1019 wxFileConfigEntry
*oldEntry
= m_pCurrentGroup
->FindEntry(oldName
);
1023 // check that the new entry doesn't already exist
1024 if ( m_pCurrentGroup
->FindEntry(newName
) )
1027 // delete the old entry, create the new one
1028 wxString value
= oldEntry
->Value();
1029 if ( !m_pCurrentGroup
->DeleteEntry(oldName
) )
1032 wxFileConfigEntry
*newEntry
= m_pCurrentGroup
->AddEntry(newName
);
1033 newEntry
->SetValue(value
);
1038 bool wxFileConfig
::RenameGroup(const wxString
& oldName
,
1039 const wxString
& newName
)
1041 // check that the group exists
1042 wxFileConfigGroup
*group
= m_pCurrentGroup
->FindSubgroup(oldName
);
1046 // check that the new group doesn't already exist
1047 if ( m_pCurrentGroup
->FindSubgroup(newName
) )
1050 group
->Rename(newName
);
1055 // ----------------------------------------------------------------------------
1056 // delete groups/entries
1057 // ----------------------------------------------------------------------------
1059 bool wxFileConfig
::DeleteEntry(const wxString
& key
, bool bGroupIfEmptyAlso
)
1061 wxConfigPathChanger
path(this, key
);
1063 if ( !m_pCurrentGroup
->DeleteEntry(path
.Name()) )
1066 if ( bGroupIfEmptyAlso
&& m_pCurrentGroup
->IsEmpty() ) {
1067 if ( m_pCurrentGroup
!= m_pRootGroup
) {
1068 wxFileConfigGroup
*pGroup
= m_pCurrentGroup
;
1069 SetPath(wxT("..")); // changes m_pCurrentGroup!
1070 m_pCurrentGroup
->DeleteSubgroupByName(pGroup
->Name());
1072 //else: never delete the root group
1078 bool wxFileConfig
::DeleteGroup(const wxString
& key
)
1080 wxConfigPathChanger
path(this, key
);
1082 return m_pCurrentGroup
->DeleteSubgroupByName(path
.Name());
1085 bool wxFileConfig
::DeleteAll()
1089 if ( wxFile
::Exists(m_strLocalFile
) && wxRemove(m_strLocalFile
) == -1 )
1091 wxLogSysError(_("can't delete user configuration file '%s'"), m_strLocalFile
.c_str());
1095 m_strLocalFile
= m_strGlobalFile
= wxT("");
1101 // ----------------------------------------------------------------------------
1102 // linked list functions
1103 // ----------------------------------------------------------------------------
1105 // append a new line to the end of the list
1107 wxFileConfigLineList
*wxFileConfig
::LineListAppend(const wxString
& str
)
1109 wxLogTrace( _T("wxFileConfig"),
1110 _T(" ** Adding Line '%s'"),
1112 wxLogTrace( _T("wxFileConfig"),
1114 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1115 wxLogTrace( _T("wxFileConfig"),
1117 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1119 wxFileConfigLineList
*pLine
= new wxFileConfigLineList(str
);
1121 if ( m_linesTail
== NULL
)
1124 m_linesHead
= pLine
;
1129 m_linesTail
->SetNext(pLine
);
1130 pLine
->SetPrev(m_linesTail
);
1133 m_linesTail
= pLine
;
1135 wxLogTrace( _T("wxFileConfig"),
1137 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1138 wxLogTrace( _T("wxFileConfig"),
1140 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1145 // insert a new line after the given one or in the very beginning if !pLine
1146 wxFileConfigLineList
*wxFileConfig
::LineListInsert(const wxString
& str
,
1147 wxFileConfigLineList
*pLine
)
1149 wxLogTrace( _T("wxFileConfig"),
1150 _T(" ** Inserting Line '%s' after '%s'"),
1152 ((pLine
) ? pLine
->Text().c_str() : wxEmptyString
) );
1153 wxLogTrace( _T("wxFileConfig"),
1155 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1156 wxLogTrace( _T("wxFileConfig"),
1158 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1160 if ( pLine
== m_linesTail
)
1161 return LineListAppend(str
);
1163 wxFileConfigLineList
*pNewLine
= new wxFileConfigLineList(str
);
1164 if ( pLine
== NULL
)
1166 // prepend to the list
1167 pNewLine
->SetNext(m_linesHead
);
1168 m_linesHead
->SetPrev(pNewLine
);
1169 m_linesHead
= pNewLine
;
1173 // insert before pLine
1174 wxFileConfigLineList
*pNext
= pLine
->Next();
1175 pNewLine
->SetNext(pNext
);
1176 pNewLine
->SetPrev(pLine
);
1177 pNext
->SetPrev(pNewLine
);
1178 pLine
->SetNext(pNewLine
);
1181 wxLogTrace( _T("wxFileConfig"),
1183 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1184 wxLogTrace( _T("wxFileConfig"),
1186 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1191 void wxFileConfig
::LineListRemove(wxFileConfigLineList
*pLine
)
1193 wxLogTrace( _T("wxFileConfig"),
1194 _T(" ** Removing Line '%s'"),
1195 pLine
->Text().c_str() );
1196 wxLogTrace( _T("wxFileConfig"),
1198 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1199 wxLogTrace( _T("wxFileConfig"),
1201 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1203 wxFileConfigLineList
*pPrev
= pLine
->Prev(),
1204 *pNext
= pLine
->Next();
1208 if ( pPrev
== NULL
)
1209 m_linesHead
= pNext
;
1211 pPrev
->SetNext(pNext
);
1215 if ( pNext
== NULL
)
1216 m_linesTail
= pPrev
;
1218 pNext
->SetPrev(pPrev
);
1220 wxLogTrace( _T("wxFileConfig"),
1222 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1223 wxLogTrace( _T("wxFileConfig"),
1225 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1230 bool wxFileConfig
::LineListIsEmpty()
1232 return m_linesHead
== NULL
;
1235 // ============================================================================
1236 // wxFileConfig::wxFileConfigGroup
1237 // ============================================================================
1239 // ----------------------------------------------------------------------------
1241 // ----------------------------------------------------------------------------
1244 wxFileConfigGroup
::wxFileConfigGroup(wxFileConfigGroup
*pParent
,
1245 const wxString
& strName
,
1246 wxFileConfig
*pConfig
)
1247 : m_aEntries(CompareEntries
),
1248 m_aSubgroups(CompareGroups
),
1251 m_pConfig
= pConfig
;
1252 m_pParent
= pParent
;
1256 m_pLastEntry
= NULL
;
1257 m_pLastGroup
= NULL
;
1260 // dtor deletes all children
1261 wxFileConfigGroup
::~wxFileConfigGroup()
1264 size_t n
, nCount
= m_aEntries
.Count();
1265 for ( n
= 0; n
< nCount
; n
++ )
1266 delete m_aEntries
[n
];
1269 nCount
= m_aSubgroups
.Count();
1270 for ( n
= 0; n
< nCount
; n
++ )
1271 delete m_aSubgroups
[n
];
1274 // ----------------------------------------------------------------------------
1276 // ----------------------------------------------------------------------------
1278 void wxFileConfigGroup
::SetLine(wxFileConfigLineList
*pLine
)
1280 wxASSERT( m_pLine
== 0 ); // shouldn't be called twice
1285 This is a bit complicated, so let me explain it in details. All lines that
1286 were read from the local file (the only one we will ever modify) are stored
1287 in a (doubly) linked list. Our problem is to know at which position in this
1288 list should we insert the new entries/subgroups. To solve it we keep three
1289 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1291 m_pLine points to the line containing "[group_name]"
1292 m_pLastEntry points to the last entry of this group in the local file.
1293 m_pLastGroup subgroup
1295 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1296 from the local file, the corresponding variable is set. However, if the group
1297 was read from the global file and then modified or created by the application
1298 these variables are still NULL and we need to create the corresponding lines.
1299 See the following functions (and comments preceding them) for the details of
1302 Also, when our last entry/group are deleted we need to find the new last
1303 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1304 of lines until it either founds an entry/subgroup (and this is the new last
1305 element) or the m_pLine of the group, in which case there are no more entries
1306 (or subgroups) left and m_pLast<element> becomes NULL.
1308 NB: This last problem could be avoided for entries if we added new entries
1309 immediately after m_pLine, but in this case the entries would appear
1310 backwards in the config file (OTOH, it's not that important) and as we
1311 would still need to do it for the subgroups the code wouldn't have been
1312 significantly less complicated.
1315 // Return the line which contains "[our name]". If we're still not in the list,
1316 // add our line to it immediately after the last line of our parent group if we
1317 // have it or in the very beginning if we're the root group.
1318 wxFileConfigLineList
*wxFileConfigGroup
::GetGroupLine()
1320 wxLogTrace( _T("wxFileConfig"),
1321 _T(" GetGroupLine() for Group '%s'"),
1326 wxLogTrace( _T("wxFileConfig"),
1327 _T(" Getting Line item pointer") );
1329 wxFileConfigGroup
*pParent
= Parent();
1331 // this group wasn't present in local config file, add it now
1334 wxLogTrace( _T("wxFileConfig"),
1335 _T(" checking parent '%s'"),
1336 pParent
->Name().c_str() );
1338 wxString strFullName
;
1340 // add 1 to the name because we don't want to start with '/'
1341 strFullName
<< wxT("[")
1342 << FilterOutEntryName(GetFullName().c_str() + 1)
1344 m_pLine
= m_pConfig
->LineListInsert(strFullName
,
1345 pParent
->GetLastGroupLine());
1346 pParent
->SetLastGroup(this); // we're surely after all the others
1348 //else: this is the root group and so we return NULL because we don't
1349 // have any group line
1355 // Return the last line belonging to the subgroups of this group (after which
1356 // we can add a new subgroup), if we don't have any subgroups or entries our
1357 // last line is the group line (m_pLine) itself.
1358 wxFileConfigLineList
*wxFileConfigGroup
::GetLastGroupLine()
1360 // if we have any subgroups, our last line is the last line of the last
1364 wxFileConfigLineList
*pLine
= m_pLastGroup
->GetLastGroupLine();
1366 wxASSERT_MSG( pLine
, _T("last group must have !NULL associated line") );
1371 // no subgroups, so the last line is the line of thelast entry (if any)
1372 return GetLastEntryLine();
1375 // return the last line belonging to the entries of this group (after which
1376 // we can add a new entry), if we don't have any entries we will add the new
1377 // one immediately after the group line itself.
1378 wxFileConfigLineList
*wxFileConfigGroup
::GetLastEntryLine()
1380 wxLogTrace( _T("wxFileConfig"),
1381 _T(" GetLastEntryLine() for Group '%s'"),
1386 wxFileConfigLineList
*pLine
= m_pLastEntry
->GetLine();
1388 wxASSERT_MSG( pLine
, _T("last entry must have !NULL associated line") );
1393 // no entries: insert after the group header, if any
1394 return GetGroupLine();
1397 void wxFileConfigGroup
::SetLastEntry(wxFileConfigEntry
*pEntry
)
1399 m_pLastEntry
= pEntry
;
1403 // the only situation in which a group without its own line can have
1404 // an entry is when the first entry is added to the initially empty
1405 // root pseudo-group
1406 wxASSERT_MSG( !m_pParent
, _T("unexpected for non root group") );
1408 // let the group know that it does have a line in the file now
1409 m_pLine
= pEntry
->GetLine();
1413 // ----------------------------------------------------------------------------
1415 // ----------------------------------------------------------------------------
1417 void wxFileConfigGroup
::Rename(const wxString
& newName
)
1419 wxCHECK_RET( m_pParent
, _T("the root group can't be renamed") );
1421 m_strName
= newName
;
1423 // +1: no leading '/'
1424 wxString strFullName
;
1425 strFullName
<< wxT("[") << (GetFullName().c_str() + 1) << wxT("]");
1427 wxFileConfigLineList
*line
= GetGroupLine();
1428 wxCHECK_RET( line
, _T("a non root group must have a corresponding line!") );
1430 line
->SetText(strFullName
);
1435 wxString wxFileConfigGroup
::GetFullName() const
1438 return Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR
+ Name();
1443 // ----------------------------------------------------------------------------
1445 // ----------------------------------------------------------------------------
1447 // use binary search because the array is sorted
1449 wxFileConfigGroup
::FindEntry(const wxChar
*szName
) const
1453 hi
= m_aEntries
.Count();
1455 wxFileConfigEntry
*pEntry
;
1459 pEntry
= m_aEntries
[i
];
1461 #if wxCONFIG_CASE_SENSITIVE
1462 res
= wxStrcmp(pEntry
->Name(), szName
);
1464 res
= wxStricmp(pEntry
->Name(), szName
);
1479 wxFileConfigGroup
::FindSubgroup(const wxChar
*szName
) const
1483 hi
= m_aSubgroups
.Count();
1485 wxFileConfigGroup
*pGroup
;
1489 pGroup
= m_aSubgroups
[i
];
1491 #if wxCONFIG_CASE_SENSITIVE
1492 res
= wxStrcmp(pGroup
->Name(), szName
);
1494 res
= wxStricmp(pGroup
->Name(), szName
);
1508 // ----------------------------------------------------------------------------
1509 // create a new item
1510 // ----------------------------------------------------------------------------
1512 // create a new entry and add it to the current group
1513 wxFileConfigEntry
*wxFileConfigGroup
::AddEntry(const wxString
& strName
, int nLine
)
1515 wxASSERT( FindEntry(strName
) == 0 );
1517 wxFileConfigEntry
*pEntry
= new wxFileConfigEntry(this, strName
, nLine
);
1519 m_aEntries
.Add(pEntry
);
1523 // create a new group and add it to the current group
1524 wxFileConfigGroup
*wxFileConfigGroup
::AddSubgroup(const wxString
& strName
)
1526 wxASSERT( FindSubgroup(strName
) == 0 );
1528 wxFileConfigGroup
*pGroup
= new wxFileConfigGroup(this, strName
, m_pConfig
);
1530 m_aSubgroups
.Add(pGroup
);
1534 // ----------------------------------------------------------------------------
1536 // ----------------------------------------------------------------------------
1539 The delete operations are _very_ slow if we delete the last item of this
1540 group (see comments before GetXXXLineXXX functions for more details),
1541 so it's much better to start with the first entry/group if we want to
1542 delete several of them.
1545 bool wxFileConfigGroup
::DeleteSubgroupByName(const wxChar
*szName
)
1547 wxFileConfigGroup
* const pGroup
= FindSubgroup(szName
);
1549 return pGroup ?
DeleteSubgroup(pGroup
) : false;
1552 // Delete the subgroup and remove all references to it from
1553 // other data structures.
1554 bool wxFileConfigGroup
::DeleteSubgroup(wxFileConfigGroup
*pGroup
)
1556 wxCHECK_MSG( pGroup
, false, _T("deleting non existing group?") );
1558 wxLogTrace( _T("wxFileConfig"),
1559 _T("Deleting group '%s' from '%s'"),
1560 pGroup
->Name().c_str(),
1563 wxLogTrace( _T("wxFileConfig"),
1564 _T(" (m_pLine) = prev: %p, this %p, next %p"),
1565 ((m_pLine
) ? m_pLine
->Prev() : 0),
1567 ((m_pLine
) ? m_pLine
->Next() : 0) );
1568 wxLogTrace( _T("wxFileConfig"),
1570 ((m_pLine
) ? m_pLine
->Text().c_str() : wxEmptyString
) );
1572 // delete all entries
1573 size_t nCount
= pGroup
->m_aEntries
.Count();
1575 wxLogTrace(_T("wxFileConfig"),
1576 _T("Removing %lu Entries"),
1577 (unsigned long)nCount
);
1579 for ( size_t nEntry
= 0; nEntry
< nCount
; nEntry
++ )
1581 wxFileConfigLineList
*pLine
= pGroup
->m_aEntries
[nEntry
]->GetLine();
1585 wxLogTrace( _T("wxFileConfig"),
1587 pLine
->Text().c_str() );
1588 m_pConfig
->LineListRemove(pLine
);
1592 // and subgroups of this subgroup
1594 nCount
= pGroup
->m_aSubgroups
.Count();
1596 wxLogTrace( _T("wxFileConfig"),
1597 _T("Removing %lu SubGroups"),
1598 (unsigned long)nCount
);
1600 for ( size_t nGroup
= 0; nGroup
< nCount
; nGroup
++ )
1602 pGroup
->DeleteSubgroup(pGroup
->m_aSubgroups
[0]);
1605 // finally the group itself
1607 wxFileConfigLineList
*pLine
= pGroup
->m_pLine
;
1611 wxLogTrace( _T("wxFileConfig"),
1612 _T(" Removing line entry for Group '%s' : '%s'"),
1613 pGroup
->Name().c_str(),
1614 pLine
->Text().c_str() );
1615 wxLogTrace( _T("wxFileConfig"),
1616 _T(" Removing from Group '%s' : '%s'"),
1618 ((m_pLine
) ? m_pLine
->Text().c_str() : wxEmptyString
) );
1620 // notice that we may do this test inside the previous "if"
1621 // because the last entry's line is surely !NULL
1623 if ( pGroup
== m_pLastGroup
)
1625 wxLogTrace( _T("wxFileConfig"),
1626 _T(" ------- Removing last group -------") );
1628 // our last entry is being deleted, so find the last one which stays.
1629 // go back until we find a subgroup or reach the group's line, unless
1630 // we are the root group, which we'll notice shortly.
1632 wxFileConfigGroup
*pNewLast
= 0;
1633 size_t nSubgroups
= m_aSubgroups
.Count();
1634 wxFileConfigLineList
*pl
;
1636 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() )
1638 // is it our subgroup?
1640 for ( size_t n
= 0; (pNewLast
== 0) && (n
< nSubgroups
); n
++ )
1642 // do _not_ call GetGroupLine! we don't want to add it to the local
1643 // file if it's not already there
1645 if ( m_aSubgroups
[n
]->m_pLine
== m_pLine
)
1646 pNewLast
= m_aSubgroups
[n
];
1649 if ( pNewLast
!= 0 ) // found?
1653 if ( pl
== m_pLine
|| m_pParent
== 0 )
1655 wxLogTrace( _T("wxFileConfig"),
1656 _T(" ------- No previous group found -------") );
1658 wxASSERT_MSG( !pNewLast
|| m_pLine
== 0,
1659 _T("how comes it has the same line as we?") );
1661 // we've reached the group line without finding any subgroups,
1662 // or realised we removed the last group from the root.
1668 wxLogTrace( _T("wxFileConfig"),
1669 _T(" ------- Last Group set to '%s' -------"),
1670 pNewLast
->Name().c_str() );
1672 m_pLastGroup
= pNewLast
;
1676 m_pConfig
->LineListRemove(pLine
);
1680 wxLogTrace( _T("wxFileConfig"),
1681 _T(" No line entry for Group '%s'?"),
1682 pGroup
->Name().c_str() );
1687 m_aSubgroups
.Remove(pGroup
);
1693 bool wxFileConfigGroup
::DeleteEntry(const wxChar
*szName
)
1695 wxFileConfigEntry
*pEntry
= FindEntry(szName
);
1696 wxCHECK( pEntry
!= NULL
, false ); // deleting non existing item?
1698 wxFileConfigLineList
*pLine
= pEntry
->GetLine();
1699 if ( pLine
!= NULL
) {
1700 // notice that we may do this test inside the previous "if" because the
1701 // last entry's line is surely !NULL
1702 if ( pEntry
== m_pLastEntry
) {
1703 // our last entry is being deleted - find the last one which stays
1704 wxASSERT( m_pLine
!= NULL
); // if we have an entry with !NULL pLine...
1706 // go back until we find another entry or reach the group's line
1707 wxFileConfigEntry
*pNewLast
= NULL
;
1708 size_t n
, nEntries
= m_aEntries
.Count();
1709 wxFileConfigLineList
*pl
;
1710 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1711 // is it our subgroup?
1712 for ( n
= 0; (pNewLast
== NULL
) && (n
< nEntries
); n
++ ) {
1713 if ( m_aEntries
[n
]->GetLine() == m_pLine
)
1714 pNewLast
= m_aEntries
[n
];
1717 if ( pNewLast
!= NULL
) // found?
1721 if ( pl
== m_pLine
) {
1722 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1724 // we've reached the group line without finding any subgroups
1725 m_pLastEntry
= NULL
;
1728 m_pLastEntry
= pNewLast
;
1731 m_pConfig
->LineListRemove(pLine
);
1734 // we must be written back for the changes to be saved
1737 m_aEntries
.Remove(pEntry
);
1743 // ----------------------------------------------------------------------------
1745 // ----------------------------------------------------------------------------
1746 void wxFileConfigGroup
::SetDirty()
1749 if ( Parent() != NULL
) // propagate upwards
1750 Parent()->SetDirty();
1753 // ============================================================================
1754 // wxFileConfig::wxFileConfigEntry
1755 // ============================================================================
1757 // ----------------------------------------------------------------------------
1759 // ----------------------------------------------------------------------------
1760 wxFileConfigEntry
::wxFileConfigEntry(wxFileConfigGroup
*pParent
,
1761 const wxString
& strName
,
1763 : m_strName(strName
)
1765 wxASSERT( !strName
.IsEmpty() );
1767 m_pParent
= pParent
;
1772 m_bHasValue
= false;
1774 m_bImmutable
= strName
[0] == wxCONFIG_IMMUTABLE_PREFIX
;
1776 m_strName
.erase(0, 1); // remove first character
1779 // ----------------------------------------------------------------------------
1781 // ----------------------------------------------------------------------------
1783 void wxFileConfigEntry
::SetLine(wxFileConfigLineList
*pLine
)
1785 if ( m_pLine
!= NULL
) {
1786 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1787 Name().c_str(), m_pParent
->GetFullName().c_str());
1791 Group()->SetLastEntry(this);
1794 // second parameter is false if we read the value from file and prevents the
1795 // entry from being marked as 'dirty'
1796 void wxFileConfigEntry
::SetValue(const wxString
& strValue
, bool bUser
)
1798 if ( bUser
&& IsImmutable() )
1800 wxLogWarning( _("attempt to change immutable key '%s' ignored."),
1805 // do nothing if it's the same value: but don't test for it
1806 // if m_bHasValue hadn't been set yet or we'd never write
1807 // empty values to the file
1809 if ( m_bHasValue
&& strValue
== m_strValue
)
1813 m_strValue
= strValue
;
1817 wxString strValFiltered
;
1819 if ( Group()->Config()->GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS
)
1821 strValFiltered
= strValue
;
1824 strValFiltered
= FilterOutValue(strValue
);
1828 strLine
<< FilterOutEntryName(m_strName
) << wxT('=') << strValFiltered
;
1832 // entry was read from the local config file, just modify the line
1833 m_pLine
->SetText(strLine
);
1835 else // this entry didn't exist in the local file
1837 // add a new line to the file
1838 wxFileConfigLineList
*line
= Group()->GetLastEntryLine();
1839 m_pLine
= Group()->Config()->LineListInsert(strLine
, line
);
1841 Group()->SetLastEntry(this);
1848 void wxFileConfigEntry
::SetDirty()
1851 Group()->SetDirty();
1854 // ============================================================================
1856 // ============================================================================
1858 // ----------------------------------------------------------------------------
1859 // compare functions for array sorting
1860 // ----------------------------------------------------------------------------
1862 int CompareEntries(wxFileConfigEntry
*p1
, wxFileConfigEntry
*p2
)
1864 #if wxCONFIG_CASE_SENSITIVE
1865 return wxStrcmp(p1
->Name(), p2
->Name());
1867 return wxStricmp(p1
->Name(), p2
->Name());
1871 int CompareGroups(wxFileConfigGroup
*p1
, wxFileConfigGroup
*p2
)
1873 #if wxCONFIG_CASE_SENSITIVE
1874 return wxStrcmp(p1
->Name(), p2
->Name());
1876 return wxStricmp(p1
->Name(), p2
->Name());
1880 // ----------------------------------------------------------------------------
1882 // ----------------------------------------------------------------------------
1884 // undo FilterOutValue
1885 static wxString
FilterInValue(const wxString
& str
)
1888 strResult
.Alloc(str
.Len());
1890 bool bQuoted
= !str
.IsEmpty() && str
[0] == '"';
1892 for ( size_t n
= bQuoted ?
1 : 0; n
< str
.Len(); n
++ ) {
1893 if ( str
[n
] == wxT('\\') ) {
1894 switch ( str
[++n
] ) {
1896 strResult
+= wxT('\n');
1900 strResult
+= wxT('\r');
1904 strResult
+= wxT('\t');
1908 strResult
+= wxT('\\');
1912 strResult
+= wxT('"');
1917 if ( str
[n
] != wxT('"') || !bQuoted
)
1918 strResult
+= str
[n
];
1919 else if ( n
!= str
.Len() - 1 ) {
1920 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1923 //else: it's the last quote of a quoted string, ok
1930 // quote the string before writing it to file
1931 static wxString
FilterOutValue(const wxString
& str
)
1937 strResult
.Alloc(str
.Len());
1939 // quoting is necessary to preserve spaces in the beginning of the string
1940 bool bQuote
= wxIsspace(str
[0]) || str
[0] == wxT('"');
1943 strResult
+= wxT('"');
1946 for ( size_t n
= 0; n
< str
.Len(); n
++ ) {
1969 //else: fall through
1972 strResult
+= str
[n
];
1973 continue; // nothing special to do
1976 // we get here only for special characters
1977 strResult
<< wxT('\\') << c
;
1981 strResult
+= wxT('"');
1986 // undo FilterOutEntryName
1987 static wxString
FilterInEntryName(const wxString
& str
)
1990 strResult
.Alloc(str
.Len());
1992 for ( const wxChar
*pc
= str
.c_str(); *pc
!= '\0'; pc
++ ) {
1993 if ( *pc
== wxT('\\') )
2002 // sanitize entry or group name: insert '\\' before any special characters
2003 static wxString
FilterOutEntryName(const wxString
& str
)
2006 strResult
.Alloc(str
.Len());
2008 for ( const wxChar
*pc
= str
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
2009 const wxChar c
= *pc
;
2011 // we explicitly allow some of "safe" chars and 8bit ASCII characters
2012 // which will probably never have special meaning and with which we can't
2013 // use isalnum() anyhow (in ASCII built, in Unicode it's just fine)
2015 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
2016 // should *not* be quoted
2019 ((unsigned char)c
< 127) &&
2021 !wxIsalnum(c
) && !wxStrchr(wxT("@_/-!.*%"), c
) )
2023 strResult
+= wxT('\\');
2032 // we can't put ?: in the ctor initializer list because it confuses some
2033 // broken compilers (Borland C++)
2034 static wxString
GetAppName(const wxString
& appName
)
2036 if ( !appName
&& wxTheApp
)
2037 return wxTheApp
->GetAppName();
2042 #endif // wxUSE_CONFIG