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 if ( !file
.Commit() )
988 wxLogError(_("Failed to update user configuration file."));
993 #if defined(__WXMAC__)
994 wxFileName(m_strLocalFile
).MacSetTypeAndCreator('TEXT', 'ttxt');
1000 // ----------------------------------------------------------------------------
1001 // renaming groups/entries
1002 // ----------------------------------------------------------------------------
1004 bool wxFileConfig::RenameEntry(const wxString
& oldName
,
1005 const wxString
& newName
)
1007 // check that the entry exists
1008 wxFileConfigEntry
*oldEntry
= m_pCurrentGroup
->FindEntry(oldName
);
1012 // check that the new entry doesn't already exist
1013 if ( m_pCurrentGroup
->FindEntry(newName
) )
1016 // delete the old entry, create the new one
1017 wxString value
= oldEntry
->Value();
1018 if ( !m_pCurrentGroup
->DeleteEntry(oldName
) )
1021 wxFileConfigEntry
*newEntry
= m_pCurrentGroup
->AddEntry(newName
);
1022 newEntry
->SetValue(value
);
1027 bool wxFileConfig::RenameGroup(const wxString
& oldName
,
1028 const wxString
& newName
)
1030 // check that the group exists
1031 wxFileConfigGroup
*group
= m_pCurrentGroup
->FindSubgroup(oldName
);
1035 // check that the new group doesn't already exist
1036 if ( m_pCurrentGroup
->FindSubgroup(newName
) )
1039 group
->Rename(newName
);
1044 // ----------------------------------------------------------------------------
1045 // delete groups/entries
1046 // ----------------------------------------------------------------------------
1048 bool wxFileConfig::DeleteEntry(const wxString
& key
, bool bGroupIfEmptyAlso
)
1050 wxConfigPathChanger
path(this, key
);
1052 if ( !m_pCurrentGroup
->DeleteEntry(path
.Name()) )
1055 if ( bGroupIfEmptyAlso
&& m_pCurrentGroup
->IsEmpty() ) {
1056 if ( m_pCurrentGroup
!= m_pRootGroup
) {
1057 wxFileConfigGroup
*pGroup
= m_pCurrentGroup
;
1058 SetPath(wxT("..")); // changes m_pCurrentGroup!
1059 m_pCurrentGroup
->DeleteSubgroupByName(pGroup
->Name());
1061 //else: never delete the root group
1067 bool wxFileConfig::DeleteGroup(const wxString
& key
)
1069 wxConfigPathChanger
path(this, key
);
1071 return m_pCurrentGroup
->DeleteSubgroupByName(path
.Name());
1074 bool wxFileConfig::DeleteAll()
1078 if ( wxFile::Exists(m_strLocalFile
) && wxRemove(m_strLocalFile
) == -1 )
1080 wxLogSysError(_("can't delete user configuration file '%s'"), m_strLocalFile
.c_str());
1084 m_strLocalFile
= m_strGlobalFile
= wxT("");
1090 // ----------------------------------------------------------------------------
1091 // linked list functions
1092 // ----------------------------------------------------------------------------
1094 // append a new line to the end of the list
1096 wxFileConfigLineList
*wxFileConfig::LineListAppend(const wxString
& str
)
1098 wxLogTrace( _T("wxFileConfig"),
1099 _T(" ** Adding Line '%s'"),
1101 wxLogTrace( _T("wxFileConfig"),
1103 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1104 wxLogTrace( _T("wxFileConfig"),
1106 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1108 wxFileConfigLineList
*pLine
= new wxFileConfigLineList(str
);
1110 if ( m_linesTail
== NULL
)
1113 m_linesHead
= pLine
;
1118 m_linesTail
->SetNext(pLine
);
1119 pLine
->SetPrev(m_linesTail
);
1122 m_linesTail
= pLine
;
1124 wxLogTrace( _T("wxFileConfig"),
1126 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1127 wxLogTrace( _T("wxFileConfig"),
1129 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1134 // insert a new line after the given one or in the very beginning if !pLine
1135 wxFileConfigLineList
*wxFileConfig::LineListInsert(const wxString
& str
,
1136 wxFileConfigLineList
*pLine
)
1138 wxLogTrace( _T("wxFileConfig"),
1139 _T(" ** Inserting Line '%s' after '%s'"),
1141 ((pLine
) ? pLine
->Text().c_str() : wxEmptyString
) );
1142 wxLogTrace( _T("wxFileConfig"),
1144 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1145 wxLogTrace( _T("wxFileConfig"),
1147 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1149 if ( pLine
== m_linesTail
)
1150 return LineListAppend(str
);
1152 wxFileConfigLineList
*pNewLine
= new wxFileConfigLineList(str
);
1153 if ( pLine
== NULL
)
1155 // prepend to the list
1156 pNewLine
->SetNext(m_linesHead
);
1157 m_linesHead
->SetPrev(pNewLine
);
1158 m_linesHead
= pNewLine
;
1162 // insert before pLine
1163 wxFileConfigLineList
*pNext
= pLine
->Next();
1164 pNewLine
->SetNext(pNext
);
1165 pNewLine
->SetPrev(pLine
);
1166 pNext
->SetPrev(pNewLine
);
1167 pLine
->SetNext(pNewLine
);
1170 wxLogTrace( _T("wxFileConfig"),
1172 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1173 wxLogTrace( _T("wxFileConfig"),
1175 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1180 void wxFileConfig::LineListRemove(wxFileConfigLineList
*pLine
)
1182 wxLogTrace( _T("wxFileConfig"),
1183 _T(" ** Removing Line '%s'"),
1184 pLine
->Text().c_str() );
1185 wxLogTrace( _T("wxFileConfig"),
1187 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1188 wxLogTrace( _T("wxFileConfig"),
1190 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1192 wxFileConfigLineList
*pPrev
= pLine
->Prev(),
1193 *pNext
= pLine
->Next();
1197 if ( pPrev
== NULL
)
1198 m_linesHead
= pNext
;
1200 pPrev
->SetNext(pNext
);
1204 if ( pNext
== NULL
)
1205 m_linesTail
= pPrev
;
1207 pNext
->SetPrev(pPrev
);
1209 wxLogTrace( _T("wxFileConfig"),
1211 ((m_linesHead
) ? m_linesHead
->Text().c_str() : wxEmptyString
) );
1212 wxLogTrace( _T("wxFileConfig"),
1214 ((m_linesTail
) ? m_linesTail
->Text().c_str() : wxEmptyString
) );
1219 bool wxFileConfig::LineListIsEmpty()
1221 return m_linesHead
== NULL
;
1224 // ============================================================================
1225 // wxFileConfig::wxFileConfigGroup
1226 // ============================================================================
1228 // ----------------------------------------------------------------------------
1230 // ----------------------------------------------------------------------------
1233 wxFileConfigGroup::wxFileConfigGroup(wxFileConfigGroup
*pParent
,
1234 const wxString
& strName
,
1235 wxFileConfig
*pConfig
)
1236 : m_aEntries(CompareEntries
),
1237 m_aSubgroups(CompareGroups
),
1240 m_pConfig
= pConfig
;
1241 m_pParent
= pParent
;
1245 m_pLastEntry
= NULL
;
1246 m_pLastGroup
= NULL
;
1249 // dtor deletes all children
1250 wxFileConfigGroup::~wxFileConfigGroup()
1253 size_t n
, nCount
= m_aEntries
.Count();
1254 for ( n
= 0; n
< nCount
; n
++ )
1255 delete m_aEntries
[n
];
1258 nCount
= m_aSubgroups
.Count();
1259 for ( n
= 0; n
< nCount
; n
++ )
1260 delete m_aSubgroups
[n
];
1263 // ----------------------------------------------------------------------------
1265 // ----------------------------------------------------------------------------
1267 void wxFileConfigGroup::SetLine(wxFileConfigLineList
*pLine
)
1269 wxASSERT( m_pLine
== 0 ); // shouldn't be called twice
1274 This is a bit complicated, so let me explain it in details. All lines that
1275 were read from the local file (the only one we will ever modify) are stored
1276 in a (doubly) linked list. Our problem is to know at which position in this
1277 list should we insert the new entries/subgroups. To solve it we keep three
1278 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1280 m_pLine points to the line containing "[group_name]"
1281 m_pLastEntry points to the last entry of this group in the local file.
1282 m_pLastGroup subgroup
1284 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1285 from the local file, the corresponding variable is set. However, if the group
1286 was read from the global file and then modified or created by the application
1287 these variables are still NULL and we need to create the corresponding lines.
1288 See the following functions (and comments preceding them) for the details of
1291 Also, when our last entry/group are deleted we need to find the new last
1292 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1293 of lines until it either founds an entry/subgroup (and this is the new last
1294 element) or the m_pLine of the group, in which case there are no more entries
1295 (or subgroups) left and m_pLast<element> becomes NULL.
1297 NB: This last problem could be avoided for entries if we added new entries
1298 immediately after m_pLine, but in this case the entries would appear
1299 backwards in the config file (OTOH, it's not that important) and as we
1300 would still need to do it for the subgroups the code wouldn't have been
1301 significantly less complicated.
1304 // Return the line which contains "[our name]". If we're still not in the list,
1305 // add our line to it immediately after the last line of our parent group if we
1306 // have it or in the very beginning if we're the root group.
1307 wxFileConfigLineList
*wxFileConfigGroup::GetGroupLine()
1309 wxLogTrace( _T("wxFileConfig"),
1310 _T(" GetGroupLine() for Group '%s'"),
1315 wxLogTrace( _T("wxFileConfig"),
1316 _T(" Getting Line item pointer") );
1318 wxFileConfigGroup
*pParent
= Parent();
1320 // this group wasn't present in local config file, add it now
1323 wxLogTrace( _T("wxFileConfig"),
1324 _T(" checking parent '%s'"),
1325 pParent
->Name().c_str() );
1327 wxString strFullName
;
1329 // add 1 to the name because we don't want to start with '/'
1330 strFullName
<< wxT("[")
1331 << FilterOutEntryName(GetFullName().c_str() + 1)
1333 m_pLine
= m_pConfig
->LineListInsert(strFullName
,
1334 pParent
->GetLastGroupLine());
1335 pParent
->SetLastGroup(this); // we're surely after all the others
1337 //else: this is the root group and so we return NULL because we don't
1338 // have any group line
1344 // Return the last line belonging to the subgroups of this group (after which
1345 // we can add a new subgroup), if we don't have any subgroups or entries our
1346 // last line is the group line (m_pLine) itself.
1347 wxFileConfigLineList
*wxFileConfigGroup::GetLastGroupLine()
1349 // if we have any subgroups, our last line is the last line of the last
1353 wxFileConfigLineList
*pLine
= m_pLastGroup
->GetLastGroupLine();
1355 wxASSERT_MSG( pLine
, _T("last group must have !NULL associated line") );
1360 // no subgroups, so the last line is the line of thelast entry (if any)
1361 return GetLastEntryLine();
1364 // return the last line belonging to the entries of this group (after which
1365 // we can add a new entry), if we don't have any entries we will add the new
1366 // one immediately after the group line itself.
1367 wxFileConfigLineList
*wxFileConfigGroup::GetLastEntryLine()
1369 wxLogTrace( _T("wxFileConfig"),
1370 _T(" GetLastEntryLine() for Group '%s'"),
1375 wxFileConfigLineList
*pLine
= m_pLastEntry
->GetLine();
1377 wxASSERT_MSG( pLine
, _T("last entry must have !NULL associated line") );
1382 // no entries: insert after the group header, if any
1383 return GetGroupLine();
1386 void wxFileConfigGroup::SetLastEntry(wxFileConfigEntry
*pEntry
)
1388 m_pLastEntry
= pEntry
;
1392 // the only situation in which a group without its own line can have
1393 // an entry is when the first entry is added to the initially empty
1394 // root pseudo-group
1395 wxASSERT_MSG( !m_pParent
, _T("unexpected for non root group") );
1397 // let the group know that it does have a line in the file now
1398 m_pLine
= pEntry
->GetLine();
1402 // ----------------------------------------------------------------------------
1404 // ----------------------------------------------------------------------------
1406 void wxFileConfigGroup::Rename(const wxString
& newName
)
1408 wxCHECK_RET( m_pParent
, _T("the root group can't be renamed") );
1410 m_strName
= newName
;
1412 // +1: no leading '/'
1413 wxString strFullName
;
1414 strFullName
<< wxT("[") << (GetFullName().c_str() + 1) << wxT("]");
1416 wxFileConfigLineList
*line
= GetGroupLine();
1417 wxCHECK_RET( line
, _T("a non root group must have a corresponding line!") );
1419 line
->SetText(strFullName
);
1424 wxString
wxFileConfigGroup::GetFullName() const
1427 return Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR
+ Name();
1432 // ----------------------------------------------------------------------------
1434 // ----------------------------------------------------------------------------
1436 // use binary search because the array is sorted
1438 wxFileConfigGroup::FindEntry(const wxChar
*szName
) const
1442 hi
= m_aEntries
.Count();
1444 wxFileConfigEntry
*pEntry
;
1448 pEntry
= m_aEntries
[i
];
1450 #if wxCONFIG_CASE_SENSITIVE
1451 res
= wxStrcmp(pEntry
->Name(), szName
);
1453 res
= wxStricmp(pEntry
->Name(), szName
);
1468 wxFileConfigGroup::FindSubgroup(const wxChar
*szName
) const
1472 hi
= m_aSubgroups
.Count();
1474 wxFileConfigGroup
*pGroup
;
1478 pGroup
= m_aSubgroups
[i
];
1480 #if wxCONFIG_CASE_SENSITIVE
1481 res
= wxStrcmp(pGroup
->Name(), szName
);
1483 res
= wxStricmp(pGroup
->Name(), szName
);
1497 // ----------------------------------------------------------------------------
1498 // create a new item
1499 // ----------------------------------------------------------------------------
1501 // create a new entry and add it to the current group
1502 wxFileConfigEntry
*wxFileConfigGroup::AddEntry(const wxString
& strName
, int nLine
)
1504 wxASSERT( FindEntry(strName
) == 0 );
1506 wxFileConfigEntry
*pEntry
= new wxFileConfigEntry(this, strName
, nLine
);
1508 m_aEntries
.Add(pEntry
);
1512 // create a new group and add it to the current group
1513 wxFileConfigGroup
*wxFileConfigGroup::AddSubgroup(const wxString
& strName
)
1515 wxASSERT( FindSubgroup(strName
) == 0 );
1517 wxFileConfigGroup
*pGroup
= new wxFileConfigGroup(this, strName
, m_pConfig
);
1519 m_aSubgroups
.Add(pGroup
);
1523 // ----------------------------------------------------------------------------
1525 // ----------------------------------------------------------------------------
1528 The delete operations are _very_ slow if we delete the last item of this
1529 group (see comments before GetXXXLineXXX functions for more details),
1530 so it's much better to start with the first entry/group if we want to
1531 delete several of them.
1534 bool wxFileConfigGroup::DeleteSubgroupByName(const wxChar
*szName
)
1536 wxFileConfigGroup
* const pGroup
= FindSubgroup(szName
);
1538 return pGroup
? DeleteSubgroup(pGroup
) : false;
1541 // Delete the subgroup and remove all references to it from
1542 // other data structures.
1543 bool wxFileConfigGroup::DeleteSubgroup(wxFileConfigGroup
*pGroup
)
1545 wxCHECK_MSG( pGroup
, false, _T("deleting non existing group?") );
1547 wxLogTrace( _T("wxFileConfig"),
1548 _T("Deleting group '%s' from '%s'"),
1549 pGroup
->Name().c_str(),
1552 wxLogTrace( _T("wxFileConfig"),
1553 _T(" (m_pLine) = prev: %p, this %p, next %p"),
1554 ((m_pLine
) ? m_pLine
->Prev() : 0),
1556 ((m_pLine
) ? m_pLine
->Next() : 0) );
1557 wxLogTrace( _T("wxFileConfig"),
1559 ((m_pLine
) ? m_pLine
->Text().c_str() : wxEmptyString
) );
1561 // delete all entries
1562 size_t nCount
= pGroup
->m_aEntries
.Count();
1564 wxLogTrace(_T("wxFileConfig"),
1565 _T("Removing %lu Entries"),
1566 (unsigned long)nCount
);
1568 for ( size_t nEntry
= 0; nEntry
< nCount
; nEntry
++ )
1570 wxFileConfigLineList
*pLine
= pGroup
->m_aEntries
[nEntry
]->GetLine();
1574 wxLogTrace( _T("wxFileConfig"),
1576 pLine
->Text().c_str() );
1577 m_pConfig
->LineListRemove(pLine
);
1581 // and subgroups of this subgroup
1583 nCount
= pGroup
->m_aSubgroups
.Count();
1585 wxLogTrace( _T("wxFileConfig"),
1586 _T("Removing %lu SubGroups"),
1587 (unsigned long)nCount
);
1589 for ( size_t nGroup
= 0; nGroup
< nCount
; nGroup
++ )
1591 pGroup
->DeleteSubgroup(pGroup
->m_aSubgroups
[0]);
1594 // finally the group itself
1596 wxFileConfigLineList
*pLine
= pGroup
->m_pLine
;
1600 wxLogTrace( _T("wxFileConfig"),
1601 _T(" Removing line entry for Group '%s' : '%s'"),
1602 pGroup
->Name().c_str(),
1603 pLine
->Text().c_str() );
1604 wxLogTrace( _T("wxFileConfig"),
1605 _T(" Removing from Group '%s' : '%s'"),
1607 ((m_pLine
) ? m_pLine
->Text().c_str() : wxEmptyString
) );
1609 // notice that we may do this test inside the previous "if"
1610 // because the last entry's line is surely !NULL
1612 if ( pGroup
== m_pLastGroup
)
1614 wxLogTrace( _T("wxFileConfig"),
1615 _T(" ------- Removing last group -------") );
1617 // our last entry is being deleted, so find the last one which stays.
1618 // go back until we find a subgroup or reach the group's line, unless
1619 // we are the root group, which we'll notice shortly.
1621 wxFileConfigGroup
*pNewLast
= 0;
1622 size_t nSubgroups
= m_aSubgroups
.Count();
1623 wxFileConfigLineList
*pl
;
1625 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() )
1627 // is it our subgroup?
1629 for ( size_t n
= 0; (pNewLast
== 0) && (n
< nSubgroups
); n
++ )
1631 // do _not_ call GetGroupLine! we don't want to add it to the local
1632 // file if it's not already there
1634 if ( m_aSubgroups
[n
]->m_pLine
== m_pLine
)
1635 pNewLast
= m_aSubgroups
[n
];
1638 if ( pNewLast
!= 0 ) // found?
1642 if ( pl
== m_pLine
|| m_pParent
== 0 )
1644 wxLogTrace( _T("wxFileConfig"),
1645 _T(" ------- No previous group found -------") );
1647 wxASSERT_MSG( !pNewLast
|| m_pLine
== 0,
1648 _T("how comes it has the same line as we?") );
1650 // we've reached the group line without finding any subgroups,
1651 // or realised we removed the last group from the root.
1657 wxLogTrace( _T("wxFileConfig"),
1658 _T(" ------- Last Group set to '%s' -------"),
1659 pNewLast
->Name().c_str() );
1661 m_pLastGroup
= pNewLast
;
1665 m_pConfig
->LineListRemove(pLine
);
1669 wxLogTrace( _T("wxFileConfig"),
1670 _T(" No line entry for Group '%s'?"),
1671 pGroup
->Name().c_str() );
1676 m_aSubgroups
.Remove(pGroup
);
1682 bool wxFileConfigGroup::DeleteEntry(const wxChar
*szName
)
1684 wxFileConfigEntry
*pEntry
= FindEntry(szName
);
1685 wxCHECK( pEntry
!= NULL
, false ); // deleting non existing item?
1687 wxFileConfigLineList
*pLine
= pEntry
->GetLine();
1688 if ( pLine
!= NULL
) {
1689 // notice that we may do this test inside the previous "if" because the
1690 // last entry's line is surely !NULL
1691 if ( pEntry
== m_pLastEntry
) {
1692 // our last entry is being deleted - find the last one which stays
1693 wxASSERT( m_pLine
!= NULL
); // if we have an entry with !NULL pLine...
1695 // go back until we find another entry or reach the group's line
1696 wxFileConfigEntry
*pNewLast
= NULL
;
1697 size_t n
, nEntries
= m_aEntries
.Count();
1698 wxFileConfigLineList
*pl
;
1699 for ( pl
= pLine
->Prev(); pl
!= m_pLine
; pl
= pl
->Prev() ) {
1700 // is it our subgroup?
1701 for ( n
= 0; (pNewLast
== NULL
) && (n
< nEntries
); n
++ ) {
1702 if ( m_aEntries
[n
]->GetLine() == m_pLine
)
1703 pNewLast
= m_aEntries
[n
];
1706 if ( pNewLast
!= NULL
) // found?
1710 if ( pl
== m_pLine
) {
1711 wxASSERT( !pNewLast
); // how comes it has the same line as we?
1713 // we've reached the group line without finding any subgroups
1714 m_pLastEntry
= NULL
;
1717 m_pLastEntry
= pNewLast
;
1720 m_pConfig
->LineListRemove(pLine
);
1723 // we must be written back for the changes to be saved
1726 m_aEntries
.Remove(pEntry
);
1732 // ----------------------------------------------------------------------------
1734 // ----------------------------------------------------------------------------
1735 void wxFileConfigGroup::SetDirty()
1738 if ( Parent() != NULL
) // propagate upwards
1739 Parent()->SetDirty();
1742 // ============================================================================
1743 // wxFileConfig::wxFileConfigEntry
1744 // ============================================================================
1746 // ----------------------------------------------------------------------------
1748 // ----------------------------------------------------------------------------
1749 wxFileConfigEntry::wxFileConfigEntry(wxFileConfigGroup
*pParent
,
1750 const wxString
& strName
,
1752 : m_strName(strName
)
1754 wxASSERT( !strName
.IsEmpty() );
1756 m_pParent
= pParent
;
1761 m_bHasValue
= false;
1763 m_bImmutable
= strName
[0] == wxCONFIG_IMMUTABLE_PREFIX
;
1765 m_strName
.erase(0, 1); // remove first character
1768 // ----------------------------------------------------------------------------
1770 // ----------------------------------------------------------------------------
1772 void wxFileConfigEntry::SetLine(wxFileConfigLineList
*pLine
)
1774 if ( m_pLine
!= NULL
) {
1775 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1776 Name().c_str(), m_pParent
->GetFullName().c_str());
1780 Group()->SetLastEntry(this);
1783 // second parameter is false if we read the value from file and prevents the
1784 // entry from being marked as 'dirty'
1785 void wxFileConfigEntry::SetValue(const wxString
& strValue
, bool bUser
)
1787 if ( bUser
&& IsImmutable() )
1789 wxLogWarning( _("attempt to change immutable key '%s' ignored."),
1794 // do nothing if it's the same value: but don't test for it
1795 // if m_bHasValue hadn't been set yet or we'd never write
1796 // empty values to the file
1798 if ( m_bHasValue
&& strValue
== m_strValue
)
1802 m_strValue
= strValue
;
1806 wxString strValFiltered
;
1808 if ( Group()->Config()->GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS
)
1810 strValFiltered
= strValue
;
1813 strValFiltered
= FilterOutValue(strValue
);
1817 strLine
<< FilterOutEntryName(m_strName
) << wxT('=') << strValFiltered
;
1821 // entry was read from the local config file, just modify the line
1822 m_pLine
->SetText(strLine
);
1824 else // this entry didn't exist in the local file
1826 // add a new line to the file
1827 wxFileConfigLineList
*line
= Group()->GetLastEntryLine();
1828 m_pLine
= Group()->Config()->LineListInsert(strLine
, line
);
1830 Group()->SetLastEntry(this);
1837 void wxFileConfigEntry::SetDirty()
1840 Group()->SetDirty();
1843 // ============================================================================
1845 // ============================================================================
1847 // ----------------------------------------------------------------------------
1848 // compare functions for array sorting
1849 // ----------------------------------------------------------------------------
1851 int CompareEntries(wxFileConfigEntry
*p1
, wxFileConfigEntry
*p2
)
1853 #if wxCONFIG_CASE_SENSITIVE
1854 return wxStrcmp(p1
->Name(), p2
->Name());
1856 return wxStricmp(p1
->Name(), p2
->Name());
1860 int CompareGroups(wxFileConfigGroup
*p1
, wxFileConfigGroup
*p2
)
1862 #if wxCONFIG_CASE_SENSITIVE
1863 return wxStrcmp(p1
->Name(), p2
->Name());
1865 return wxStricmp(p1
->Name(), p2
->Name());
1869 // ----------------------------------------------------------------------------
1871 // ----------------------------------------------------------------------------
1873 // undo FilterOutValue
1874 static wxString
FilterInValue(const wxString
& str
)
1877 strResult
.Alloc(str
.Len());
1879 bool bQuoted
= !str
.IsEmpty() && str
[0] == '"';
1881 for ( size_t n
= bQuoted
? 1 : 0; n
< str
.Len(); n
++ ) {
1882 if ( str
[n
] == wxT('\\') ) {
1883 switch ( str
[++n
] ) {
1885 strResult
+= wxT('\n');
1889 strResult
+= wxT('\r');
1893 strResult
+= wxT('\t');
1897 strResult
+= wxT('\\');
1901 strResult
+= wxT('"');
1906 if ( str
[n
] != wxT('"') || !bQuoted
)
1907 strResult
+= str
[n
];
1908 else if ( n
!= str
.Len() - 1 ) {
1909 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1912 //else: it's the last quote of a quoted string, ok
1919 // quote the string before writing it to file
1920 static wxString
FilterOutValue(const wxString
& str
)
1926 strResult
.Alloc(str
.Len());
1928 // quoting is necessary to preserve spaces in the beginning of the string
1929 bool bQuote
= wxIsspace(str
[0]) || str
[0] == wxT('"');
1932 strResult
+= wxT('"');
1935 for ( size_t n
= 0; n
< str
.Len(); n
++ ) {
1958 //else: fall through
1961 strResult
+= str
[n
];
1962 continue; // nothing special to do
1965 // we get here only for special characters
1966 strResult
<< wxT('\\') << c
;
1970 strResult
+= wxT('"');
1975 // undo FilterOutEntryName
1976 static wxString
FilterInEntryName(const wxString
& str
)
1979 strResult
.Alloc(str
.Len());
1981 for ( const wxChar
*pc
= str
.c_str(); *pc
!= '\0'; pc
++ ) {
1982 if ( *pc
== wxT('\\') )
1991 // sanitize entry or group name: insert '\\' before any special characters
1992 static wxString
FilterOutEntryName(const wxString
& str
)
1995 strResult
.Alloc(str
.Len());
1997 for ( const wxChar
*pc
= str
.c_str(); *pc
!= wxT('\0'); pc
++ ) {
1998 const wxChar c
= *pc
;
2000 // we explicitly allow some of "safe" chars and 8bit ASCII characters
2001 // which will probably never have special meaning and with which we can't
2002 // use isalnum() anyhow (in ASCII built, in Unicode it's just fine)
2004 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
2005 // should *not* be quoted
2008 ((unsigned char)c
< 127) &&
2010 !wxIsalnum(c
) && !wxStrchr(wxT("@_/-!.*%"), c
) )
2012 strResult
+= wxT('\\');
2021 // we can't put ?: in the ctor initializer list because it confuses some
2022 // broken compilers (Borland C++)
2023 static wxString
GetAppName(const wxString
& appName
)
2025 if ( !appName
&& wxTheApp
)
2026 return wxTheApp
->GetAppName();
2031 #endif // wxUSE_CONFIG