]> git.saurik.com Git - wxWidgets.git/blame - src/common/fileconf.cpp
fixing overrelease and out-of-bounds write, fixes #13725
[wxWidgets.git] / src / common / fileconf.cpp
CommitLineData
c801d85f 1///////////////////////////////////////////////////////////////////////////////
55034339 2// Name: src/common/fileconf.cpp
c801d85f
KB
3// Purpose: implementation of wxFileConfig derivation of wxConfig
4// Author: Vadim Zeitlin
876419ce 5// Modified by:
c801d85f
KB
6// Created: 07.04.98 (adapted from appconf.cpp)
7// RCS-ID: $Id$
9d55bfef 8// Copyright: (c) 1997 Karsten Ballueder & Vadim Zeitlin
c801d85f 9// Ballueder@usa.net <zeitlin@dptmaths.ens-cachan.fr>
65571936 10// Licence: wxWindows licence
c801d85f
KB
11///////////////////////////////////////////////////////////////////////////////
12
c801d85f
KB
13// ----------------------------------------------------------------------------
14// headers
15// ----------------------------------------------------------------------------
d427503c 16
ad9835c9 17// For compilers that support precompilation, includes "wx.h".
c801d85f
KB
18#include "wx/wxprec.h"
19
20#ifdef __BORLANDC__
ad9835c9 21 #pragma hdrstop
c801d85f
KB
22#endif //__BORLANDC__
23
1c193821 24#if wxUSE_CONFIG && wxUSE_FILECONFIG
d427503c 25
c801d85f 26#ifndef WX_PRECOMP
ad9835c9
WS
27 #include "wx/dynarray.h"
28 #include "wx/string.h"
29 #include "wx/intl.h"
e4db172a 30 #include "wx/log.h"
670f9935 31 #include "wx/app.h"
de6185e2 32 #include "wx/utils.h" // for wxGetHomeDir
530ecef0
WS
33 #if wxUSE_STREAMS
34 #include "wx/stream.h"
35 #endif // wxUSE_STREAMS
c801d85f
KB
36#endif //WX_PRECOMP
37
47d67540 38#include "wx/file.h"
47d67540 39#include "wx/textfile.h"
a3a584a7 40#include "wx/memtext.h"
47d67540 41#include "wx/config.h"
a3ef5bf5 42#include "wx/fileconf.h"
8482e4bd 43#include "wx/filefn.h"
47d67540 44
5814e8ba
VZ
45#include "wx/base64.h"
46
466e87bd
VZ
47#include "wx/stdpaths.h"
48
d98a58c5 49#if defined(__WINDOWS__)
670f9935 50 #include "wx/msw/private.h"
1f905dc5 51#endif //windows.h
c2ff79b1 52#if defined(__WXPM__)
670f9935
WS
53 #define INCL_DOS
54 #include <os2.h>
c2ff79b1 55#endif
c801d85f 56
1f905dc5
VZ
57#include <stdlib.h>
58#include <ctype.h>
c801d85f 59
1c4a764c
VZ
60// ----------------------------------------------------------------------------
61// constants
62// ----------------------------------------------------------------------------
0516e0e8 63
1c4a764c 64#ifndef MAX_PATH
670f9935 65 #define MAX_PATH 512
1c4a764c
VZ
66#endif
67
9a83f860 68#define FILECONF_TRACE_MASK wxT("fileconf")
701fb11e 69
c801d85f
KB
70// ----------------------------------------------------------------------------
71// global functions declarations
72// ----------------------------------------------------------------------------
73
f5ae0449 74// compare functions for sorting the arrays
0516e0e8
VZ
75static int LINKAGEMODE CompareEntries(wxFileConfigEntry *p1, wxFileConfigEntry *p2);
76static int LINKAGEMODE CompareGroups(wxFileConfigGroup *p1, wxFileConfigGroup *p2);
f5ae0449 77
c801d85f 78// filter strings
b8e9dd43
VZ
79static wxString FilterInValue(const wxString& str);
80static wxString FilterOutValue(const wxString& str);
81
82static wxString FilterInEntryName(const wxString& str);
83static wxString FilterOutEntryName(const wxString& str);
c801d85f 84
004c69ab
VZ
85// get the name to use in wxFileConfig ctor
86static wxString GetAppName(const wxString& appname);
87
0516e0e8
VZ
88// ============================================================================
89// private classes
90// ============================================================================
91
92// ----------------------------------------------------------------------------
93// "template" array types
94// ----------------------------------------------------------------------------
95
34dceb47
VZ
96#ifdef WXMAKINGDLL_BASE
97 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(wxFileConfigEntry *, ArrayEntries,
e33f6503 98 WXDLLIMPEXP_BASE);
34dceb47 99 WX_DEFINE_SORTED_USER_EXPORTED_ARRAY(wxFileConfigGroup *, ArrayGroups,
e33f6503 100 WXDLLIMPEXP_BASE);
34dceb47
VZ
101#else
102 WX_DEFINE_SORTED_ARRAY(wxFileConfigEntry *, ArrayEntries);
103 WX_DEFINE_SORTED_ARRAY(wxFileConfigGroup *, ArrayGroups);
104#endif
0516e0e8
VZ
105
106// ----------------------------------------------------------------------------
107// wxFileConfigLineList
108// ----------------------------------------------------------------------------
109
110// we store all lines of the local config file as a linked list in memory
111class wxFileConfigLineList
112{
113public:
114 void SetNext(wxFileConfigLineList *pNext) { m_pNext = pNext; }
115 void SetPrev(wxFileConfigLineList *pPrev) { m_pPrev = pPrev; }
116
117 // ctor
118 wxFileConfigLineList(const wxString& str,
119 wxFileConfigLineList *pNext = NULL) : m_strLine(str)
120 { SetNext(pNext); SetPrev(NULL); }
121
122 // next/prev nodes in the linked list
123 wxFileConfigLineList *Next() const { return m_pNext; }
124 wxFileConfigLineList *Prev() const { return m_pPrev; }
125
126 // get/change lines text
127 void SetText(const wxString& str) { m_strLine = str; }
128 const wxString& Text() const { return m_strLine; }
129
130private:
131 wxString m_strLine; // line contents
132 wxFileConfigLineList *m_pNext, // next node
133 *m_pPrev; // previous one
22f3361e 134
c0c133e1 135 wxDECLARE_NO_COPY_CLASS(wxFileConfigLineList);
0516e0e8
VZ
136};
137
138// ----------------------------------------------------------------------------
139// wxFileConfigEntry: a name/value pair
140// ----------------------------------------------------------------------------
141
142class wxFileConfigEntry
143{
144private:
145 wxFileConfigGroup *m_pParent; // group that contains us
146
147 wxString m_strName, // entry name
148 m_strValue; // value
4c51a665 149 bool m_bImmutable:1, // can be overridden locally?
0516e0e8
VZ
150 m_bHasValue:1; // set after first call to SetValue()
151
152 int m_nLine; // used if m_pLine == NULL only
153
154 // pointer to our line in the linked list or NULL if it was found in global
155 // file (which we don't modify)
156 wxFileConfigLineList *m_pLine;
157
158public:
159 wxFileConfigEntry(wxFileConfigGroup *pParent,
160 const wxString& strName, int nLine);
161
162 // simple accessors
163 const wxString& Name() const { return m_strName; }
164 const wxString& Value() const { return m_strValue; }
165 wxFileConfigGroup *Group() const { return m_pParent; }
0516e0e8
VZ
166 bool IsImmutable() const { return m_bImmutable; }
167 bool IsLocal() const { return m_pLine != 0; }
168 int Line() const { return m_nLine; }
169 wxFileConfigLineList *
170 GetLine() const { return m_pLine; }
171
172 // modify entry attributes
a62848fd 173 void SetValue(const wxString& strValue, bool bUser = true);
0516e0e8 174 void SetLine(wxFileConfigLineList *pLine);
22f3361e 175
c0c133e1 176 wxDECLARE_NO_COPY_CLASS(wxFileConfigEntry);
0516e0e8
VZ
177};
178
179// ----------------------------------------------------------------------------
180// wxFileConfigGroup: container of entries and other groups
181// ----------------------------------------------------------------------------
182
183class wxFileConfigGroup
184{
185private:
186 wxFileConfig *m_pConfig; // config object we belong to
187 wxFileConfigGroup *m_pParent; // parent group (NULL for root group)
188 ArrayEntries m_aEntries; // entries in this group
189 ArrayGroups m_aSubgroups; // subgroups
190 wxString m_strName; // group's name
0516e0e8
VZ
191 wxFileConfigLineList *m_pLine; // pointer to our line in the linked list
192 wxFileConfigEntry *m_pLastEntry; // last entry/subgroup of this group in the
193 wxFileConfigGroup *m_pLastGroup; // local file (we insert new ones after it)
194
195 // DeleteSubgroupByName helper
196 bool DeleteSubgroup(wxFileConfigGroup *pGroup);
197
6dda7a75
VZ
198 // used by Rename()
199 void UpdateGroupAndSubgroupsLines();
200
0516e0e8
VZ
201public:
202 // ctor
203 wxFileConfigGroup(wxFileConfigGroup *pParent, const wxString& strName, wxFileConfig *);
204
205 // dtor deletes all entries and subgroups also
206 ~wxFileConfigGroup();
207
208 // simple accessors
209 const wxString& Name() const { return m_strName; }
210 wxFileConfigGroup *Parent() const { return m_pParent; }
211 wxFileConfig *Config() const { return m_pConfig; }
0516e0e8
VZ
212
213 const ArrayEntries& Entries() const { return m_aEntries; }
214 const ArrayGroups& Groups() const { return m_aSubgroups; }
215 bool IsEmpty() const { return Entries().IsEmpty() && Groups().IsEmpty(); }
216
217 // find entry/subgroup (NULL if not found)
86501081
VS
218 wxFileConfigGroup *FindSubgroup(const wxString& name) const;
219 wxFileConfigEntry *FindEntry (const wxString& name) const;
0516e0e8 220
a62848fd 221 // delete entry/subgroup, return false if doesn't exist
86501081
VS
222 bool DeleteSubgroupByName(const wxString& name);
223 bool DeleteEntry(const wxString& name);
0516e0e8
VZ
224
225 // create new entry/subgroup returning pointer to newly created element
226 wxFileConfigGroup *AddSubgroup(const wxString& strName);
227 wxFileConfigEntry *AddEntry (const wxString& strName, int nLine = wxNOT_FOUND);
228
0516e0e8
VZ
229 void SetLine(wxFileConfigLineList *pLine);
230
231 // rename: no checks are done to ensure that the name is unique!
232 void Rename(const wxString& newName);
233
234 //
235 wxString GetFullName() const;
236
237 // get the last line belonging to an entry/subgroup of this group
238 wxFileConfigLineList *GetGroupLine(); // line which contains [group]
9a7b7798 239 // may be NULL for "/" only
0516e0e8
VZ
240 wxFileConfigLineList *GetLastEntryLine(); // after which our subgroups start
241 wxFileConfigLineList *GetLastGroupLine(); // after which the next group starts
242
243 // called by entries/subgroups when they're created/deleted
128e0251
VZ
244 void SetLastEntry(wxFileConfigEntry *pEntry);
245 void SetLastGroup(wxFileConfigGroup *pGroup)
246 { m_pLastGroup = pGroup; }
22f3361e 247
c0c133e1 248 wxDECLARE_NO_COPY_CLASS(wxFileConfigGroup);
0516e0e8
VZ
249};
250
1f905dc5
VZ
251// ============================================================================
252// implementation
253// ============================================================================
254
c801d85f 255// ----------------------------------------------------------------------------
1f905dc5 256// static functions
c801d85f 257// ----------------------------------------------------------------------------
1f905dc5 258
466e87bd
VZ
259// this function modifies in place the given wxFileName object if it doesn't
260// already have an extension
261//
262// note that it's slightly misnamed under Mac as there it doesn't add an
263// extension but modifies the file name instead, so you shouldn't suppose that
264// fn.HasExt() is true after it returns
265static void AddConfFileExtIfNeeded(wxFileName& fn)
266{
267 if ( !fn.HasExt() )
c2ff79b1 268 {
466e87bd
VZ
269#if defined( __WXMAC__ )
270 fn.SetName(fn.GetName() + wxT(" Preferences"));
271#elif defined( __UNIX__ )
b0bcc787 272 fn.SetExt(wxT("conf"));
466e87bd 273#else // Windows
b0bcc787 274 fn.SetExt(wxT("ini"));
466e87bd 275#endif // UNIX/Win
c2ff79b1 276 }
1f905dc5
VZ
277}
278
466e87bd 279wxString wxFileConfig::GetGlobalDir()
c801d85f 280{
466e87bd 281 return wxStandardPaths::Get().GetConfigDir();
da468d38
VZ
282}
283
466e87bd 284wxString wxFileConfig::GetLocalDir(int style)
da468d38 285{
466e87bd 286 wxUnusedVar(style);
da468d38 287
466e87bd 288 wxStandardPathsBase& stdp = wxStandardPaths::Get();
2b5f62a0 289
466e87bd
VZ
290 // it so happens that user data directory is a subdirectory of user config
291 // directory on all supported platforms, which explains why we use it here
292 return style & wxCONFIG_USE_SUBDIR ? stdp.GetUserDataDir()
293 : stdp.GetUserConfigDir();
da468d38
VZ
294}
295
466e87bd 296wxFileName wxFileConfig::GetGlobalFile(const wxString& szFile)
da468d38 297{
466e87bd 298 wxFileName fn(GetGlobalDir(), szFile);
8dce54c9 299
466e87bd 300 AddConfFileExtIfNeeded(fn);
da468d38 301
466e87bd
VZ
302 return fn;
303}
da468d38 304
466e87bd
VZ
305wxFileName wxFileConfig::GetLocalFile(const wxString& szFile, int style)
306{
307 wxFileName fn(GetLocalDir(style), szFile);
8bbe427f 308
0cd1c6e3 309#if defined( __UNIX__ ) && !defined( __WXMAC__ )
466e87bd
VZ
310 if ( !(style & wxCONFIG_USE_SUBDIR) )
311 {
312 // dot-files under Unix start with, well, a dot (but OTOH they usually
313 // don't have any specific extension)
314 fn.SetName(wxT('.') + fn.GetName());
315 }
316 else // we do append ".conf" extension to config files in subdirectories
bba0174a 317#endif // defined( __UNIX__ ) && !defined( __WXMAC__ )
466e87bd
VZ
318 {
319 AddConfFileExtIfNeeded(fn);
320 }
2b5f62a0 321
466e87bd 322 return fn;
1f905dc5 323}
c801d85f
KB
324
325// ----------------------------------------------------------------------------
326// ctor
327// ----------------------------------------------------------------------------
c4ec0ce8 328IMPLEMENT_ABSTRACT_CLASS(wxFileConfig, wxConfigBase)
c801d85f
KB
329
330void wxFileConfig::Init()
331{
2b5f62a0 332 m_pCurrentGroup =
b494c48b 333 m_pRootGroup = new wxFileConfigGroup(NULL, wxEmptyString, this);
c801d85f 334
2b5f62a0
VZ
335 m_linesHead =
336 m_linesTail = NULL;
c801d85f 337
2b5f62a0 338 // It's not an error if (one of the) file(s) doesn't exist.
c801d85f 339
2b5f62a0 340 // parse the global file
d2ea08b9 341 if ( m_fnGlobalFile.IsOk() && m_fnGlobalFile.FileExists() )
2b5f62a0 342 {
466e87bd 343 wxTextFile fileGlobal(m_fnGlobalFile.GetFullPath());
c801d85f 344
e835ec01 345 if ( fileGlobal.Open(*m_conv/*ignored in ANSI build*/) )
2b5f62a0 346 {
a62848fd 347 Parse(fileGlobal, false /* global */);
2b5f62a0
VZ
348 SetRootPath();
349 }
350 else
351 {
466e87bd 352 wxLogWarning(_("can't open global configuration file '%s'."), m_fnGlobalFile.GetFullPath().c_str());
2b5f62a0 353 }
c801d85f 354 }
c801d85f 355
2b5f62a0 356 // parse the local file
d2ea08b9 357 if ( m_fnLocalFile.IsOk() && m_fnLocalFile.FileExists() )
2b5f62a0 358 {
466e87bd 359 wxTextFile fileLocal(m_fnLocalFile.GetFullPath());
e835ec01 360 if ( fileLocal.Open(*m_conv/*ignored in ANSI build*/) )
2b5f62a0 361 {
a62848fd 362 Parse(fileLocal, true /* local */);
2b5f62a0
VZ
363 SetRootPath();
364 }
365 else
366 {
bf6d45eb
VZ
367 const wxString path = m_fnLocalFile.GetFullPath();
368 wxLogWarning(_("can't open user configuration file '%s'."),
369 path.c_str());
370
371 if ( m_fnLocalFile.FileExists() )
372 {
373 wxLogWarning(_("Changes won't be saved to avoid overwriting the existing file \"%s\""),
374 path.c_str());
375 m_fnLocalFile.Clear();
376 }
2b5f62a0 377 }
c801d85f 378 }
e1cc6874
VZ
379
380 m_isDirty = false;
c801d85f
KB
381}
382
b3031762 383// constructor supports creation of wxFileConfig objects of any type
18244936 384wxFileConfig::wxFileConfig(const wxString& appName, const wxString& vendorName,
b3031762 385 const wxString& strLocal, const wxString& strGlobal,
830f8f11
VZ
386 long style,
387 const wxMBConv& conv)
004c69ab
VZ
388 : wxConfigBase(::GetAppName(appName), vendorName,
389 strLocal, strGlobal,
390 style),
466e87bd
VZ
391 m_fnLocalFile(strLocal),
392 m_fnGlobalFile(strGlobal),
e835ec01 393 m_conv(conv.Clone())
18244936 394{
2b5f62a0 395 // Make up names for files if empty
466e87bd
VZ
396 if ( !m_fnLocalFile.IsOk() && (style & wxCONFIG_USE_LOCAL_FILE) )
397 m_fnLocalFile = GetLocalFile(GetAppName(), style);
18244936 398
466e87bd
VZ
399 if ( !m_fnGlobalFile.IsOk() && (style & wxCONFIG_USE_GLOBAL_FILE) )
400 m_fnGlobalFile = GetGlobalFile(GetAppName());
18244936 401
2b5f62a0
VZ
402 // Check if styles are not supplied, but filenames are, in which case
403 // add the correct styles.
466e87bd 404 if ( m_fnLocalFile.IsOk() )
2b5f62a0 405 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE);
18244936 406
466e87bd 407 if ( m_fnGlobalFile.IsOk() )
2b5f62a0 408 SetStyle(GetStyle() | wxCONFIG_USE_GLOBAL_FILE);
7beba2fc 409
2b5f62a0 410 // if the path is not absolute, prepend the standard directory to it
466e87bd 411 // unless explicitly asked not to
2b5f62a0
VZ
412 if ( !(style & wxCONFIG_USE_RELATIVE_PATH) )
413 {
466e87bd
VZ
414 if ( m_fnLocalFile.IsOk() )
415 m_fnLocalFile.MakeAbsolute(GetLocalDir(style));
18244936 416
466e87bd
VZ
417 if ( m_fnGlobalFile.IsOk() )
418 m_fnGlobalFile.MakeAbsolute(GetGlobalDir());
2b5f62a0 419 }
f6bcfd97 420
2b5f62a0 421 SetUmask(-1);
bc33be3b 422
2b5f62a0 423 Init();
18244936 424}
da468d38 425
a3a584a7
VZ
426#if wxUSE_STREAMS
427
830f8f11 428wxFileConfig::wxFileConfig(wxInputStream &inStream, const wxMBConv& conv)
e835ec01 429 : m_conv(conv.Clone())
a3a584a7
VZ
430{
431 // always local_file when this constructor is called (?)
432 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE);
433
434 m_pCurrentGroup =
b494c48b 435 m_pRootGroup = new wxFileConfigGroup(NULL, wxEmptyString, this);
a3a584a7
VZ
436
437 m_linesHead =
438 m_linesTail = NULL;
439
8d7bfa66 440 // read the entire stream contents in memory
5ad2b5ce
VZ
441 wxWxCharBuffer cbuf;
442 static const size_t chunkLen = 1024;
a3a584a7 443
5ad2b5ce
VZ
444 wxMemoryBuffer buf(chunkLen);
445 do
446 {
447 inStream.Read(buf.GetAppendBuf(chunkLen), chunkLen);
448 buf.UngetAppendBuf(inStream.LastRead());
2825b3f5 449
5ad2b5ce 450 const wxStreamError err = inStream.GetLastError();
01b18927 451
5ad2b5ce
VZ
452 if ( err != wxSTREAM_NO_ERROR && err != wxSTREAM_EOF )
453 {
454 wxLogError(_("Error reading config options."));
455 break;
2825b3f5 456 }
5ad2b5ce
VZ
457 }
458 while ( !inStream.Eof() );
a3a584a7 459
8d7bfa66 460#if wxUSE_UNICODE
5ad2b5ce 461 size_t len;
8ca1a013 462 cbuf = conv.cMB2WC((char *)buf.GetData(), buf.GetDataLen() + 1, &len);
5ad2b5ce
VZ
463 if ( !len && buf.GetDataLen() )
464 {
465 wxLogError(_("Failed to read config options."));
466 }
8d7bfa66 467#else // !wxUSE_UNICODE
5ad2b5ce 468 // no need for conversion
6df09f32 469 cbuf = wxCharBuffer::CreateNonOwned((char *)buf.GetData(), buf.GetDataLen());
8d7bfa66 470#endif // wxUSE_UNICODE/!wxUSE_UNICODE
a3a584a7 471
975fb32b
VZ
472 // parse the input contents if there is anything to parse
473 if ( cbuf )
a3a584a7 474 {
975fb32b
VZ
475 // now break it into lines
476 wxMemoryText memText;
477 for ( const wxChar *s = cbuf; ; ++s )
478 {
479 const wxChar *e = s;
480 while ( *e != '\0' && *e != '\n' && *e != '\r' )
481 ++e;
a3a584a7 482
975fb32b
VZ
483 // notice that we throw away the original EOL kind here, maybe we
484 // should preserve it?
485 if ( e != s )
486 memText.AddLine(wxString(s, e));
a3a584a7 487
975fb32b
VZ
488 if ( *e == '\0' )
489 break;
a3a584a7 490
975fb32b
VZ
491 // skip the second EOL byte if it's a DOS one
492 if ( *e == '\r' && e[1] == '\n' )
493 ++e;
a3a584a7 494
975fb32b
VZ
495 s = e;
496 }
a3a584a7 497
975fb32b
VZ
498 // Finally we can parse it all.
499 Parse(memText, true /* local */);
500 }
a3a584a7
VZ
501
502 SetRootPath();
ca7dc59a 503 ResetDirty();
a3a584a7
VZ
504}
505
506#endif // wxUSE_STREAMS
507
da468d38 508void wxFileConfig::CleanUp()
c801d85f 509{
127eab18 510 delete m_pRootGroup;
128aec1d 511
127eab18
WS
512 wxFileConfigLineList *pCur = m_linesHead;
513 while ( pCur != NULL ) {
514 wxFileConfigLineList *pNext = pCur->Next();
515 delete pCur;
516 pCur = pNext;
517 }
c801d85f
KB
518}
519
da468d38
VZ
520wxFileConfig::~wxFileConfig()
521{
127eab18 522 Flush();
da468d38 523
127eab18 524 CleanUp();
2754877b
VZ
525
526 delete m_conv;
da468d38
VZ
527}
528
c801d85f
KB
529// ----------------------------------------------------------------------------
530// parse a config file
531// ----------------------------------------------------------------------------
532
fbfb8bcc 533void wxFileConfig::Parse(const wxTextBuffer& buffer, bool bLocal)
c801d85f 534{
9fbd8b8d 535
a3a584a7 536 size_t nLineCount = buffer.GetLineCount();
bc33be3b 537
2b5f62a0
VZ
538 for ( size_t n = 0; n < nLineCount; n++ )
539 {
86501081
VS
540 wxString strLine = buffer[n];
541 // FIXME-UTF8: rewrite using iterators, without this buffer
542 wxWxCharBuffer buf(strLine.c_str());
543 const wxChar *pStart;
544 const wxChar *pEnd;
876419ce 545
c801d85f
KB
546 // add the line to linked list
547 if ( bLocal )
9fbd8b8d 548 LineListAppend(strLine);
c801d85f 549
3362e80e 550
c801d85f 551 // skip leading spaces
86501081 552 for ( pStart = buf; wxIsspace(*pStart); pStart++ )
c801d85f
KB
553 ;
554
555 // skip blank/comment lines
223d09f6 556 if ( *pStart == wxT('\0')|| *pStart == wxT(';') || *pStart == wxT('#') )
c801d85f
KB
557 continue;
558
223d09f6 559 if ( *pStart == wxT('[') ) { // a new group
c801d85f
KB
560 pEnd = pStart;
561
223d09f6 562 while ( *++pEnd != wxT(']') ) {
1c68fb91
VZ
563 if ( *pEnd == wxT('\\') ) {
564 // the next char is escaped, so skip it even if it is ']'
565 pEnd++;
566 }
567
568 if ( *pEnd == wxT('\n') || *pEnd == wxT('\0') ) {
569 // we reached the end of line, break out of the loop
b8e9dd43 570 break;
1c68fb91 571 }
c801d85f
KB
572 }
573
223d09f6 574 if ( *pEnd != wxT(']') ) {
7502ba29 575 wxLogError(_("file '%s': unexpected character %c at line %d."),
a3a584a7 576 buffer.GetName(), *pEnd, n + 1);
c801d85f
KB
577 continue; // skip this line
578 }
579
580 // group name here is always considered as abs path
581 wxString strGroup;
582 pStart++;
b8e9dd43
VZ
583 strGroup << wxCONFIG_PATH_SEPARATOR
584 << FilterInEntryName(wxString(pStart, pEnd - pStart));
c801d85f
KB
585
586 // will create it if doesn't yet exist
587 SetPath(strGroup);
588
589 if ( bLocal )
80fdb8d6
VZ
590 {
591 if ( m_pCurrentGroup->Parent() )
592 m_pCurrentGroup->Parent()->SetLastGroup(m_pCurrentGroup);
c801d85f 593 m_pCurrentGroup->SetLine(m_linesTail);
80fdb8d6 594 }
c801d85f
KB
595
596 // check that there is nothing except comments left on this line
a62848fd 597 bool bCont = true;
223d09f6 598 while ( *++pEnd != wxT('\0') && bCont ) {
c801d85f 599 switch ( *pEnd ) {
223d09f6
KB
600 case wxT('#'):
601 case wxT(';'):
a62848fd 602 bCont = false;
c801d85f 603 break;
876419ce 604
223d09f6
KB
605 case wxT(' '):
606 case wxT('\t'):
c801d85f
KB
607 // ignore whitespace ('\n' impossible here)
608 break;
876419ce 609
c801d85f 610 default:
f6bcfd97 611 wxLogWarning(_("file '%s', line %d: '%s' ignored after group header."),
a3a584a7 612 buffer.GetName(), n + 1, pEnd);
a62848fd 613 bCont = false;
c801d85f
KB
614 }
615 }
616 }
617 else { // a key
17a1ebd1 618 pEnd = pStart;
7dfdce6b 619 while ( *pEnd && *pEnd != wxT('=') /* && !wxIsspace(*pEnd)*/ ) {
223d09f6 620 if ( *pEnd == wxT('\\') ) {
b8e9dd43 621 // next character may be space or not - still take it because it's
409c4ffd 622 // quoted (unless there is nothing)
b8e9dd43 623 pEnd++;
409c4ffd
VZ
624 if ( !*pEnd ) {
625 // the error message will be given below anyhow
626 break;
627 }
b8e9dd43
VZ
628 }
629
c801d85f 630 pEnd++;
b8e9dd43 631 }
c801d85f 632
17256d1e 633 wxString strKey(FilterInEntryName(wxString(pStart, pEnd).Trim()));
c801d85f
KB
634
635 // skip whitespace
f6bcfd97 636 while ( wxIsspace(*pEnd) )
c801d85f
KB
637 pEnd++;
638
223d09f6 639 if ( *pEnd++ != wxT('=') ) {
7502ba29 640 wxLogError(_("file '%s', line %d: '=' expected."),
a3a584a7 641 buffer.GetName(), n + 1);
c801d85f
KB
642 }
643 else {
0516e0e8 644 wxFileConfigEntry *pEntry = m_pCurrentGroup->FindEntry(strKey);
c801d85f
KB
645
646 if ( pEntry == NULL ) {
647 // new entry
648 pEntry = m_pCurrentGroup->AddEntry(strKey, n);
c801d85f
KB
649 }
650 else {
651 if ( bLocal && pEntry->IsImmutable() ) {
652 // immutable keys can't be changed by user
f6bcfd97 653 wxLogWarning(_("file '%s', line %d: value for immutable key '%s' ignored."),
a3a584a7 654 buffer.GetName(), n + 1, strKey.c_str());
c801d85f
KB
655 continue;
656 }
657 // the condition below catches the cases (a) and (b) but not (c):
658 // (a) global key found second time in global file
659 // (b) key found second (or more) time in local file
660 // (c) key from global file now found in local one
661 // which is exactly what we want.
662 else if ( !bLocal || pEntry->IsLocal() ) {
f6bcfd97 663 wxLogWarning(_("file '%s', line %d: key '%s' was first found at line %d."),
d89b7c19 664 buffer.GetName(), (int)n + 1, strKey.c_str(), pEntry->Line());
c801d85f 665
c801d85f
KB
666 }
667 }
668
80fdb8d6
VZ
669 if ( bLocal )
670 pEntry->SetLine(m_linesTail);
671
c801d85f 672 // skip whitespace
50920146 673 while ( wxIsspace(*pEnd) )
c801d85f
KB
674 pEnd++;
675
8dce54c9
VZ
676 wxString value = pEnd;
677 if ( !(GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS) )
678 value = FilterInValue(value);
679
a62848fd 680 pEntry->SetValue(value, false);
c801d85f
KB
681 }
682 }
683 }
684}
685
686// ----------------------------------------------------------------------------
687// set/retrieve path
688// ----------------------------------------------------------------------------
689
690void wxFileConfig::SetRootPath()
691{
127eab18
WS
692 m_strPath.Empty();
693 m_pCurrentGroup = m_pRootGroup;
c801d85f
KB
694}
695
6c99cd3d
VZ
696bool
697wxFileConfig::DoSetPath(const wxString& strPath, bool createMissingComponents)
c801d85f 698{
127eab18 699 wxArrayString aParts;
c801d85f 700
127eab18
WS
701 if ( strPath.empty() ) {
702 SetRootPath();
703 return true;
704 }
c801d85f 705
127eab18
WS
706 if ( strPath[0] == wxCONFIG_PATH_SEPARATOR ) {
707 // absolute path
708 wxSplitPath(aParts, strPath);
709 }
710 else {
711 // relative path, combine with current one
712 wxString strFullPath = m_strPath;
713 strFullPath << wxCONFIG_PATH_SEPARATOR << strPath;
714 wxSplitPath(aParts, strFullPath);
715 }
c801d85f 716
127eab18
WS
717 // change current group
718 size_t n;
719 m_pCurrentGroup = m_pRootGroup;
b4a980f4 720 for ( n = 0; n < aParts.GetCount(); n++ ) {
127eab18
WS
721 wxFileConfigGroup *pNextGroup = m_pCurrentGroup->FindSubgroup(aParts[n]);
722 if ( pNextGroup == NULL )
723 {
724 if ( !createMissingComponents )
725 return false;
6c99cd3d 726
127eab18
WS
727 pNextGroup = m_pCurrentGroup->AddSubgroup(aParts[n]);
728 }
6c99cd3d 729
127eab18
WS
730 m_pCurrentGroup = pNextGroup;
731 }
c801d85f 732
127eab18
WS
733 // recombine path parts in one variable
734 m_strPath.Empty();
b4a980f4 735 for ( n = 0; n < aParts.GetCount(); n++ ) {
127eab18
WS
736 m_strPath << wxCONFIG_PATH_SEPARATOR << aParts[n];
737 }
6c99cd3d 738
127eab18 739 return true;
6c99cd3d
VZ
740}
741
742void wxFileConfig::SetPath(const wxString& strPath)
743{
127eab18 744 DoSetPath(strPath, true /* create missing path components */);
c801d85f
KB
745}
746
d8a78293
VZ
747const wxString& wxFileConfig::GetPath() const
748{
749 return m_strPath;
750}
751
c801d85f
KB
752// ----------------------------------------------------------------------------
753// enumeration
754// ----------------------------------------------------------------------------
755
5fe256de 756bool wxFileConfig::GetFirstGroup(wxString& str, long& lIndex) const
c801d85f 757{
127eab18
WS
758 lIndex = 0;
759 return GetNextGroup(str, lIndex);
c801d85f
KB
760}
761
5fe256de 762bool wxFileConfig::GetNextGroup (wxString& str, long& lIndex) const
c801d85f 763{
b4a980f4 764 if ( size_t(lIndex) < m_pCurrentGroup->Groups().GetCount() ) {
127eab18
WS
765 str = m_pCurrentGroup->Groups()[(size_t)lIndex++]->Name();
766 return true;
767 }
768 else
769 return false;
c801d85f
KB
770}
771
5fe256de 772bool wxFileConfig::GetFirstEntry(wxString& str, long& lIndex) const
c801d85f 773{
127eab18
WS
774 lIndex = 0;
775 return GetNextEntry(str, lIndex);
c801d85f
KB
776}
777
5fe256de 778bool wxFileConfig::GetNextEntry (wxString& str, long& lIndex) const
c801d85f 779{
b4a980f4 780 if ( size_t(lIndex) < m_pCurrentGroup->Entries().GetCount() ) {
127eab18
WS
781 str = m_pCurrentGroup->Entries()[(size_t)lIndex++]->Name();
782 return true;
783 }
784 else
785 return false;
c801d85f
KB
786}
787
c86f1403 788size_t wxFileConfig::GetNumberOfEntries(bool bRecursive) const
9fbd8b8d 789{
b4a980f4 790 size_t n = m_pCurrentGroup->Entries().GetCount();
127eab18 791 if ( bRecursive ) {
a57bfed9
VZ
792 wxFileConfig * const self = const_cast<wxFileConfig *>(this);
793
127eab18 794 wxFileConfigGroup *pOldCurrentGroup = m_pCurrentGroup;
b4a980f4 795 size_t nSubgroups = m_pCurrentGroup->Groups().GetCount();
127eab18 796 for ( size_t nGroup = 0; nGroup < nSubgroups; nGroup++ ) {
a57bfed9 797 self->m_pCurrentGroup = m_pCurrentGroup->Groups()[nGroup];
127eab18 798 n += GetNumberOfEntries(true);
a57bfed9 799 self->m_pCurrentGroup = pOldCurrentGroup;
127eab18 800 }
9fbd8b8d 801 }
9fbd8b8d 802
127eab18 803 return n;
9fbd8b8d
VZ
804}
805
c86f1403 806size_t wxFileConfig::GetNumberOfGroups(bool bRecursive) const
9fbd8b8d 807{
b4a980f4 808 size_t n = m_pCurrentGroup->Groups().GetCount();
127eab18 809 if ( bRecursive ) {
a57bfed9
VZ
810 wxFileConfig * const self = const_cast<wxFileConfig *>(this);
811
127eab18 812 wxFileConfigGroup *pOldCurrentGroup = m_pCurrentGroup;
b4a980f4 813 size_t nSubgroups = m_pCurrentGroup->Groups().GetCount();
127eab18 814 for ( size_t nGroup = 0; nGroup < nSubgroups; nGroup++ ) {
a57bfed9 815 self->m_pCurrentGroup = m_pCurrentGroup->Groups()[nGroup];
127eab18 816 n += GetNumberOfGroups(true);
a57bfed9 817 self->m_pCurrentGroup = pOldCurrentGroup;
127eab18 818 }
9fbd8b8d 819 }
9fbd8b8d 820
127eab18 821 return n;
9fbd8b8d
VZ
822}
823
876419ce
VZ
824// ----------------------------------------------------------------------------
825// tests for existence
826// ----------------------------------------------------------------------------
827
828bool wxFileConfig::HasGroup(const wxString& strName) const
829{
127eab18
WS
830 // special case: DoSetPath("") does work as it's equivalent to DoSetPath("/")
831 // but there is no group with empty name so treat this separately
832 if ( strName.empty() )
833 return false;
6c99cd3d 834
127eab18 835 const wxString pathOld = GetPath();
6c99cd3d 836
5c33522f 837 wxFileConfig *self = const_cast<wxFileConfig *>(this);
127eab18
WS
838 const bool
839 rc = self->DoSetPath(strName, false /* don't create missing components */);
6c99cd3d 840
127eab18 841 self->SetPath(pathOld);
876419ce 842
127eab18 843 return rc;
876419ce
VZ
844}
845
2cf3a6d7 846bool wxFileConfig::HasEntry(const wxString& entry) const
876419ce 847{
2cf3a6d7
VZ
848 // path is the part before the last "/"
849 wxString path = entry.BeforeLast(wxCONFIG_PATH_SEPARATOR);
876419ce 850
2cf3a6d7
VZ
851 // except in the special case of "/keyname" when there is nothing before "/"
852 if ( path.empty() && *entry.c_str() == wxCONFIG_PATH_SEPARATOR )
853 {
854 path = wxCONFIG_PATH_SEPARATOR;
855 }
856
857 // change to the path of the entry if necessary and remember the old path
858 // to restore it later
859 wxString pathOld;
5c33522f 860 wxFileConfig * const self = const_cast<wxFileConfig *>(this);
2cf3a6d7
VZ
861 if ( !path.empty() )
862 {
863 pathOld = GetPath();
864 if ( pathOld.empty() )
865 pathOld = wxCONFIG_PATH_SEPARATOR;
866
867 if ( !self->DoSetPath(path, false /* don't create if doesn't exist */) )
868 {
869 return false;
870 }
871 }
872
873 // check if the entry exists in this group
874 const bool exists = m_pCurrentGroup->FindEntry(
875 entry.AfterLast(wxCONFIG_PATH_SEPARATOR)) != NULL;
876
877 // restore the old path if we changed it above
878 if ( !pathOld.empty() )
879 {
880 self->SetPath(pathOld);
881 }
882
883 return exists;
876419ce
VZ
884}
885
c801d85f
KB
886// ----------------------------------------------------------------------------
887// read/write values
888// ----------------------------------------------------------------------------
889
2ba41305 890bool wxFileConfig::DoReadString(const wxString& key, wxString* pStr) const
c801d85f 891{
127eab18 892 wxConfigPathChanger path(this, key);
1f905dc5 893
127eab18
WS
894 wxFileConfigEntry *pEntry = m_pCurrentGroup->FindEntry(path.Name());
895 if (pEntry == NULL) {
896 return false;
897 }
f6bcfd97 898
127eab18 899 *pStr = pEntry->Value();
1f905dc5 900
127eab18 901 return true;
9fbd8b8d
VZ
902}
903
2ba41305 904bool wxFileConfig::DoReadLong(const wxString& key, long *pl) const
1f905dc5 905{
444d3e01
VZ
906 wxString str;
907 if ( !Read(key, &str) )
a62848fd 908 return false;
444d3e01
VZ
909
910 // extra spaces shouldn't prevent us from reading numeric values
911 str.Trim();
912
913 return str.ToLong(pl);
c801d85f
KB
914}
915
434e2903
VZ
916#if wxUSE_BASE64
917
5814e8ba
VZ
918bool wxFileConfig::DoReadBinary(const wxString& key, wxMemoryBuffer* buf) const
919{
9a83f860 920 wxCHECK_MSG( buf, false, wxT("NULL buffer") );
5814e8ba
VZ
921
922 wxString str;
923 if ( !Read(key, &str) )
924 return false;
925
d20d5ee8 926 *buf = wxBase64Decode(str);
5814e8ba
VZ
927 return true;
928}
929
434e2903
VZ
930#endif // wxUSE_BASE64
931
2ba41305 932bool wxFileConfig::DoWriteString(const wxString& key, const wxString& szValue)
c801d85f 933{
2b5f62a0
VZ
934 wxConfigPathChanger path(this, key);
935 wxString strName = path.Name();
bc33be3b 936
701fb11e 937 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 938 wxT(" Writing String '%s' = '%s' to Group '%s'"),
2b5f62a0
VZ
939 strName.c_str(),
940 szValue.c_str(),
941 GetPath().c_str() );
c801d85f 942
b494c48b 943 if ( strName.empty() )
2b5f62a0
VZ
944 {
945 // setting the value of a group is an error
c3b0ff9c 946
b494c48b 947 wxASSERT_MSG( szValue.empty(), wxT("can't set value of a group!") );
c3b0ff9c 948
2b5f62a0 949 // ... except if it's empty in which case it's a way to force it's creation
c3b0ff9c 950
701fb11e 951 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 952 wxT(" Creating group %s"),
2b5f62a0
VZ
953 m_pCurrentGroup->Name().c_str() );
954
e1cc6874 955 SetDirty();
2b5f62a0 956
9a7b7798
VZ
957 // this will add a line for this group if it didn't have it before (or
958 // do nothing for the root but it's ok as it always exists anyhow)
2b5f62a0 959 (void)m_pCurrentGroup->GetGroupLine();
c3b0ff9c 960 }
2b5f62a0
VZ
961 else
962 {
e1cc6874 963 // writing an entry check that the name is reasonable
2b5f62a0
VZ
964 if ( strName[0u] == wxCONFIG_IMMUTABLE_PREFIX )
965 {
966 wxLogError( _("Config entry name cannot start with '%c'."),
967 wxCONFIG_IMMUTABLE_PREFIX);
a62848fd 968 return false;
2b5f62a0 969 }
c3b0ff9c 970
2b5f62a0 971 wxFileConfigEntry *pEntry = m_pCurrentGroup->FindEntry(strName);
c3b0ff9c 972
2b5f62a0
VZ
973 if ( pEntry == 0 )
974 {
701fb11e 975 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 976 wxT(" Adding Entry %s"),
2b5f62a0
VZ
977 strName.c_str() );
978 pEntry = m_pCurrentGroup->AddEntry(strName);
979 }
c801d85f 980
701fb11e 981 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 982 wxT(" Setting value %s"),
2b5f62a0
VZ
983 szValue.c_str() );
984 pEntry->SetValue(szValue);
e1cc6874
VZ
985
986 SetDirty();
2b5f62a0
VZ
987 }
988
a62848fd 989 return true;
c801d85f
KB
990}
991
2ba41305 992bool wxFileConfig::DoWriteLong(const wxString& key, long lValue)
c801d85f 993{
9a83f860 994 return Write(key, wxString::Format(wxT("%ld"), lValue));
c801d85f
KB
995}
996
434e2903
VZ
997#if wxUSE_BASE64
998
5814e8ba
VZ
999bool wxFileConfig::DoWriteBinary(const wxString& key, const wxMemoryBuffer& buf)
1000{
1001 return Write(key, wxBase64Encode(buf));
1002}
1003
434e2903
VZ
1004#endif // wxUSE_BASE64
1005
c801d85f
KB
1006bool wxFileConfig::Flush(bool /* bCurrentOnly */)
1007{
466e87bd 1008 if ( !IsDirty() || !m_fnLocalFile.GetFullPath() )
a62848fd 1009 return true;
c801d85f 1010
f6bcfd97 1011 // set the umask if needed
8482e4bd 1012 wxCHANGE_UMASK(m_umask);
f6bcfd97 1013
466e87bd 1014 wxTempFile file(m_fnLocalFile.GetFullPath());
c801d85f 1015
ca11abde
RR
1016 if ( !file.IsOpened() )
1017 {
7502ba29 1018 wxLogError(_("can't open user configuration file."));
a62848fd 1019 return false;
c801d85f
KB
1020 }
1021
1022 // write all strings to file
20160a32
VZ
1023 wxString filetext;
1024 filetext.reserve(4096);
ca11abde
RR
1025 for ( wxFileConfigLineList *p = m_linesHead; p != NULL; p = p->Next() )
1026 {
20160a32
VZ
1027 filetext << p->Text() << wxTextFile::GetEOL();
1028 }
1029
1030 if ( !file.Write(filetext, *m_conv) )
1031 {
1032 wxLogError(_("can't write user configuration file."));
1033 return false;
c801d85f
KB
1034 }
1035
60829985
VZ
1036 if ( !file.Commit() )
1037 {
1038 wxLogError(_("Failed to update user configuration file."));
f6bcfd97 1039
60829985
VZ
1040 return false;
1041 }
a62848fd 1042
e1cc6874
VZ
1043 ResetDirty();
1044
26eef304 1045#if defined( __WXOSX_MAC__ ) && wxOSX_USE_CARBON
466e87bd 1046 m_fnLocalFile.MacSetTypeAndCreator('TEXT', 'ttxt');
e7e1b01e 1047#endif // __WXMAC__
f6bcfd97 1048
60829985 1049 return true;
c801d85f
KB
1050}
1051
a121d720
VZ
1052#if wxUSE_STREAMS
1053
830f8f11 1054bool wxFileConfig::Save(wxOutputStream& os, const wxMBConv& conv)
a121d720
VZ
1055{
1056 // save unconditionally, even if not dirty
1057 for ( wxFileConfigLineList *p = m_linesHead; p != NULL; p = p->Next() )
1058 {
1059 wxString line = p->Text();
1060 line += wxTextFile::GetEOL();
894d74dc
VZ
1061
1062 wxCharBuffer buf(line.mb_str(conv));
1063 if ( !os.Write(buf, strlen(buf)) )
a121d720
VZ
1064 {
1065 wxLogError(_("Error saving user configuration data."));
1066
1067 return false;
1068 }
1069 }
1070
1071 ResetDirty();
1072
1073 return true;
1074}
1075
1076#endif // wxUSE_STREAMS
1077
5d1902d6
VZ
1078// ----------------------------------------------------------------------------
1079// renaming groups/entries
1080// ----------------------------------------------------------------------------
1081
1082bool wxFileConfig::RenameEntry(const wxString& oldName,
1083 const wxString& newName)
1084{
86501081 1085 wxASSERT_MSG( oldName.find(wxCONFIG_PATH_SEPARATOR) == wxString::npos,
9a83f860 1086 wxT("RenameEntry(): paths are not supported") );
6dda7a75 1087
5d1902d6 1088 // check that the entry exists
0516e0e8 1089 wxFileConfigEntry *oldEntry = m_pCurrentGroup->FindEntry(oldName);
5d1902d6 1090 if ( !oldEntry )
a62848fd 1091 return false;
5d1902d6
VZ
1092
1093 // check that the new entry doesn't already exist
1094 if ( m_pCurrentGroup->FindEntry(newName) )
a62848fd 1095 return false;
5d1902d6
VZ
1096
1097 // delete the old entry, create the new one
1098 wxString value = oldEntry->Value();
1099 if ( !m_pCurrentGroup->DeleteEntry(oldName) )
a62848fd 1100 return false;
5d1902d6 1101
e1cc6874
VZ
1102 SetDirty();
1103
0516e0e8 1104 wxFileConfigEntry *newEntry = m_pCurrentGroup->AddEntry(newName);
5d1902d6
VZ
1105 newEntry->SetValue(value);
1106
a62848fd 1107 return true;
5d1902d6
VZ
1108}
1109
1110bool wxFileConfig::RenameGroup(const wxString& oldName,
1111 const wxString& newName)
1112{
1113 // check that the group exists
0516e0e8 1114 wxFileConfigGroup *group = m_pCurrentGroup->FindSubgroup(oldName);
5d1902d6 1115 if ( !group )
a62848fd 1116 return false;
5d1902d6
VZ
1117
1118 // check that the new group doesn't already exist
1119 if ( m_pCurrentGroup->FindSubgroup(newName) )
a62848fd 1120 return false;
5d1902d6
VZ
1121
1122 group->Rename(newName);
1123
e1cc6874
VZ
1124 SetDirty();
1125
a62848fd 1126 return true;
5d1902d6
VZ
1127}
1128
c801d85f
KB
1129// ----------------------------------------------------------------------------
1130// delete groups/entries
1131// ----------------------------------------------------------------------------
1132
18244936 1133bool wxFileConfig::DeleteEntry(const wxString& key, bool bGroupIfEmptyAlso)
c801d85f 1134{
18244936 1135 wxConfigPathChanger path(this, key);
c801d85f
KB
1136
1137 if ( !m_pCurrentGroup->DeleteEntry(path.Name()) )
a62848fd 1138 return false;
c801d85f 1139
a625d949
RD
1140 SetDirty();
1141
c801d85f
KB
1142 if ( bGroupIfEmptyAlso && m_pCurrentGroup->IsEmpty() ) {
1143 if ( m_pCurrentGroup != m_pRootGroup ) {
0516e0e8 1144 wxFileConfigGroup *pGroup = m_pCurrentGroup;
223d09f6 1145 SetPath(wxT("..")); // changes m_pCurrentGroup!
a625d949 1146 m_pCurrentGroup->DeleteSubgroupByName(pGroup->Name());
c801d85f
KB
1147 }
1148 //else: never delete the root group
1149 }
1150
a62848fd 1151 return true;
c801d85f
KB
1152}
1153
18244936 1154bool wxFileConfig::DeleteGroup(const wxString& key)
c801d85f 1155{
35c4b4da 1156 wxConfigPathChanger path(this, RemoveTrailingSeparator(key));
c801d85f 1157
e1cc6874
VZ
1158 if ( !m_pCurrentGroup->DeleteSubgroupByName(path.Name()) )
1159 return false;
1160
41f30152
VZ
1161 path.UpdateIfDeleted();
1162
e1cc6874
VZ
1163 SetDirty();
1164
1165 return true;
c801d85f
KB
1166}
1167
1168bool wxFileConfig::DeleteAll()
1169{
da468d38
VZ
1170 CleanUp();
1171
466e87bd 1172 if ( m_fnLocalFile.IsOk() )
cb820f80 1173 {
86501081
VS
1174 if ( m_fnLocalFile.FileExists() &&
1175 !wxRemoveFile(m_fnLocalFile.GetFullPath()) )
c8adf5ef
VZ
1176 {
1177 wxLogSysError(_("can't delete user configuration file '%s'"),
466e87bd 1178 m_fnLocalFile.GetFullPath().c_str());
c8adf5ef
VZ
1179 return false;
1180 }
cb820f80 1181 }
da468d38 1182
275bf4c1
VZ
1183 Init();
1184
a62848fd 1185 return true;
c801d85f
KB
1186}
1187
1188// ----------------------------------------------------------------------------
1189// linked list functions
1190// ----------------------------------------------------------------------------
1191
2b5f62a0
VZ
1192 // append a new line to the end of the list
1193
0516e0e8 1194wxFileConfigLineList *wxFileConfig::LineListAppend(const wxString& str)
c801d85f 1195{
701fb11e 1196 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1197 wxT(" ** Adding Line '%s'"),
2b5f62a0 1198 str.c_str() );
701fb11e 1199 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1200 wxT(" head: %s"),
c9f78968
VS
1201 ((m_linesHead) ? (const wxChar*)m_linesHead->Text().c_str()
1202 : wxEmptyString) );
701fb11e 1203 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1204 wxT(" tail: %s"),
c9f78968
VS
1205 ((m_linesTail) ? (const wxChar*)m_linesTail->Text().c_str()
1206 : wxEmptyString) );
c801d85f 1207
2b5f62a0 1208 wxFileConfigLineList *pLine = new wxFileConfigLineList(str);
c801d85f 1209
2b5f62a0
VZ
1210 if ( m_linesTail == NULL )
1211 {
1212 // list is empty
1213 m_linesHead = pLine;
1214 }
1215 else
1216 {
1217 // adjust pointers
1218 m_linesTail->SetNext(pLine);
1219 pLine->SetPrev(m_linesTail);
1220 }
1221
1222 m_linesTail = pLine;
1223
701fb11e 1224 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1225 wxT(" head: %s"),
c9f78968
VS
1226 ((m_linesHead) ? (const wxChar*)m_linesHead->Text().c_str()
1227 : wxEmptyString) );
701fb11e 1228 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1229 wxT(" tail: %s"),
c9f78968
VS
1230 ((m_linesTail) ? (const wxChar*)m_linesTail->Text().c_str()
1231 : wxEmptyString) );
2b5f62a0
VZ
1232
1233 return m_linesTail;
c801d85f
KB
1234}
1235
128e0251 1236// insert a new line after the given one or in the very beginning if !pLine
0516e0e8 1237wxFileConfigLineList *wxFileConfig::LineListInsert(const wxString& str,
2b5f62a0
VZ
1238 wxFileConfigLineList *pLine)
1239{
701fb11e 1240 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1241 wxT(" ** Inserting Line '%s' after '%s'"),
2b5f62a0 1242 str.c_str(),
c9f78968
VS
1243 ((pLine) ? (const wxChar*)pLine->Text().c_str()
1244 : wxEmptyString) );
701fb11e 1245 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1246 wxT(" head: %s"),
c9f78968
VS
1247 ((m_linesHead) ? (const wxChar*)m_linesHead->Text().c_str()
1248 : wxEmptyString) );
701fb11e 1249 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1250 wxT(" tail: %s"),
c9f78968
VS
1251 ((m_linesTail) ? (const wxChar*)m_linesTail->Text().c_str()
1252 : wxEmptyString) );
2b5f62a0
VZ
1253
1254 if ( pLine == m_linesTail )
1255 return LineListAppend(str);
1256
1257 wxFileConfigLineList *pNewLine = new wxFileConfigLineList(str);
1258 if ( pLine == NULL )
1259 {
1260 // prepend to the list
1261 pNewLine->SetNext(m_linesHead);
1262 m_linesHead->SetPrev(pNewLine);
1263 m_linesHead = pNewLine;
1264 }
1265 else
1266 {
1267 // insert before pLine
1268 wxFileConfigLineList *pNext = pLine->Next();
1269 pNewLine->SetNext(pNext);
1270 pNewLine->SetPrev(pLine);
1271 pNext->SetPrev(pNewLine);
1272 pLine->SetNext(pNewLine);
1273 }
c801d85f 1274
701fb11e 1275 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1276 wxT(" head: %s"),
c9f78968
VS
1277 ((m_linesHead) ? (const wxChar*)m_linesHead->Text().c_str()
1278 : wxEmptyString) );
701fb11e 1279 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1280 wxT(" tail: %s"),
c9f78968
VS
1281 ((m_linesTail) ? (const wxChar*)m_linesTail->Text().c_str()
1282 : wxEmptyString) );
c801d85f 1283
2b5f62a0 1284 return pNewLine;
c801d85f
KB
1285}
1286
0516e0e8 1287void wxFileConfig::LineListRemove(wxFileConfigLineList *pLine)
876419ce 1288{
701fb11e 1289 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1290 wxT(" ** Removing Line '%s'"),
2b5f62a0 1291 pLine->Text().c_str() );
701fb11e 1292 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1293 wxT(" head: %s"),
c9f78968
VS
1294 ((m_linesHead) ? (const wxChar*)m_linesHead->Text().c_str()
1295 : wxEmptyString) );
701fb11e 1296 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1297 wxT(" tail: %s"),
c9f78968
VS
1298 ((m_linesTail) ? (const wxChar*)m_linesTail->Text().c_str()
1299 : wxEmptyString) );
c3b0ff9c 1300
2b5f62a0
VZ
1301 wxFileConfigLineList *pPrev = pLine->Prev(),
1302 *pNext = pLine->Next();
876419ce 1303
2b5f62a0
VZ
1304 // first entry?
1305
1306 if ( pPrev == NULL )
1307 m_linesHead = pNext;
1308 else
1309 pPrev->SetNext(pNext);
1310
1311 // last entry?
876419ce 1312
2b5f62a0
VZ
1313 if ( pNext == NULL )
1314 m_linesTail = pPrev;
1315 else
1316 pNext->SetPrev(pPrev);
1317
701fb11e 1318 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1319 wxT(" head: %s"),
c9f78968
VS
1320 ((m_linesHead) ? (const wxChar*)m_linesHead->Text().c_str()
1321 : wxEmptyString) );
701fb11e 1322 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1323 wxT(" tail: %s"),
c9f78968
VS
1324 ((m_linesTail) ? (const wxChar*)m_linesTail->Text().c_str()
1325 : wxEmptyString) );
2b5f62a0
VZ
1326
1327 delete pLine;
876419ce
VZ
1328}
1329
c801d85f
KB
1330bool wxFileConfig::LineListIsEmpty()
1331{
2b5f62a0 1332 return m_linesHead == NULL;
c801d85f
KB
1333}
1334
1335// ============================================================================
0516e0e8 1336// wxFileConfig::wxFileConfigGroup
c801d85f
KB
1337// ============================================================================
1338
1339// ----------------------------------------------------------------------------
1340// ctor/dtor
1341// ----------------------------------------------------------------------------
1342
1343// ctor
0516e0e8 1344wxFileConfigGroup::wxFileConfigGroup(wxFileConfigGroup *pParent,
c801d85f
KB
1345 const wxString& strName,
1346 wxFileConfig *pConfig)
f5ae0449
VZ
1347 : m_aEntries(CompareEntries),
1348 m_aSubgroups(CompareGroups),
1349 m_strName(strName)
c801d85f
KB
1350{
1351 m_pConfig = pConfig;
1352 m_pParent = pParent;
c3b0ff9c
VZ
1353 m_pLine = NULL;
1354
b841e0e3
VZ
1355 m_pLastEntry = NULL;
1356 m_pLastGroup = NULL;
c801d85f
KB
1357}
1358
1359// dtor deletes all children
0516e0e8 1360wxFileConfigGroup::~wxFileConfigGroup()
c801d85f
KB
1361{
1362 // entries
b4a980f4 1363 size_t n, nCount = m_aEntries.GetCount();
c801d85f
KB
1364 for ( n = 0; n < nCount; n++ )
1365 delete m_aEntries[n];
1366
1367 // subgroups
b4a980f4 1368 nCount = m_aSubgroups.GetCount();
c801d85f
KB
1369 for ( n = 0; n < nCount; n++ )
1370 delete m_aSubgroups[n];
1371}
1372
1373// ----------------------------------------------------------------------------
1374// line
1375// ----------------------------------------------------------------------------
1376
0516e0e8 1377void wxFileConfigGroup::SetLine(wxFileConfigLineList *pLine)
c801d85f 1378{
b3a9e150
VZ
1379 // for a normal (i.e. not root) group this method shouldn't be called twice
1380 // unless we are resetting the line
1381 wxASSERT_MSG( !m_pParent || !m_pLine || !pLine,
9a83f860 1382 wxT("changing line for a non-root group?") );
b3a9e150 1383
2b5f62a0 1384 m_pLine = pLine;
c801d85f
KB
1385}
1386
c3b0ff9c
VZ
1387/*
1388 This is a bit complicated, so let me explain it in details. All lines that
1389 were read from the local file (the only one we will ever modify) are stored
1390 in a (doubly) linked list. Our problem is to know at which position in this
1391 list should we insert the new entries/subgroups. To solve it we keep three
1392 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1393
1394 m_pLine points to the line containing "[group_name]"
1395 m_pLastEntry points to the last entry of this group in the local file.
1396 m_pLastGroup subgroup
1397
1398 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1399 from the local file, the corresponding variable is set. However, if the group
1400 was read from the global file and then modified or created by the application
1401 these variables are still NULL and we need to create the corresponding lines.
1402 See the following functions (and comments preceding them) for the details of
1403 how we do it.
1404
1405 Also, when our last entry/group are deleted we need to find the new last
1406 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1407 of lines until it either founds an entry/subgroup (and this is the new last
1408 element) or the m_pLine of the group, in which case there are no more entries
1409 (or subgroups) left and m_pLast<element> becomes NULL.
1410
1411 NB: This last problem could be avoided for entries if we added new entries
1412 immediately after m_pLine, but in this case the entries would appear
1413 backwards in the config file (OTOH, it's not that important) and as we
1414 would still need to do it for the subgroups the code wouldn't have been
1415 significantly less complicated.
5d1902d6 1416*/
c3b0ff9c
VZ
1417
1418// Return the line which contains "[our name]". If we're still not in the list,
1419// add our line to it immediately after the last line of our parent group if we
1420// have it or in the very beginning if we're the root group.
0516e0e8 1421wxFileConfigLineList *wxFileConfigGroup::GetGroupLine()
c801d85f 1422{
701fb11e 1423 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1424 wxT(" GetGroupLine() for Group '%s'"),
2b5f62a0
VZ
1425 Name().c_str() );
1426
128e0251 1427 if ( !m_pLine )
2b5f62a0 1428 {
701fb11e 1429 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1430 wxT(" Getting Line item pointer") );
2b5f62a0
VZ
1431
1432 wxFileConfigGroup *pParent = Parent();
1433
128e0251
VZ
1434 // this group wasn't present in local config file, add it now
1435 if ( pParent )
2b5f62a0 1436 {
701fb11e 1437 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1438 wxT(" checking parent '%s'"),
2b5f62a0
VZ
1439 pParent->Name().c_str() );
1440
1441 wxString strFullName;
1442
128e0251
VZ
1443 // add 1 to the name because we don't want to start with '/'
1444 strFullName << wxT("[")
2b5f62a0
VZ
1445 << FilterOutEntryName(GetFullName().c_str() + 1)
1446 << wxT("]");
1447 m_pLine = m_pConfig->LineListInsert(strFullName,
1448 pParent->GetLastGroupLine());
1449 pParent->SetLastGroup(this); // we're surely after all the others
1450 }
128e0251
VZ
1451 //else: this is the root group and so we return NULL because we don't
1452 // have any group line
c801d85f 1453 }
c801d85f 1454
2b5f62a0 1455 return m_pLine;
c801d85f
KB
1456}
1457
c3b0ff9c
VZ
1458// Return the last line belonging to the subgroups of this group (after which
1459// we can add a new subgroup), if we don't have any subgroups or entries our
1460// last line is the group line (m_pLine) itself.
0516e0e8 1461wxFileConfigLineList *wxFileConfigGroup::GetLastGroupLine()
c801d85f 1462{
128e0251
VZ
1463 // if we have any subgroups, our last line is the last line of the last
1464 // subgroup
1465 if ( m_pLastGroup )
2b5f62a0
VZ
1466 {
1467 wxFileConfigLineList *pLine = m_pLastGroup->GetLastGroupLine();
1468
9a83f860 1469 wxASSERT_MSG( pLine, wxT("last group must have !NULL associated line") );
128e0251 1470
2b5f62a0
VZ
1471 return pLine;
1472 }
c801d85f 1473
128e0251 1474 // no subgroups, so the last line is the line of thelast entry (if any)
2b5f62a0 1475 return GetLastEntryLine();
c801d85f
KB
1476}
1477
c3b0ff9c
VZ
1478// return the last line belonging to the entries of this group (after which
1479// we can add a new entry), if we don't have any entries we will add the new
1480// one immediately after the group line itself.
0516e0e8 1481wxFileConfigLineList *wxFileConfigGroup::GetLastEntryLine()
c801d85f 1482{
701fb11e 1483 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1484 wxT(" GetLastEntryLine() for Group '%s'"),
2b5f62a0 1485 Name().c_str() );
b841e0e3 1486
128e0251 1487 if ( m_pLastEntry )
2b5f62a0
VZ
1488 {
1489 wxFileConfigLineList *pLine = m_pLastEntry->GetLine();
1490
9a83f860 1491 wxASSERT_MSG( pLine, wxT("last entry must have !NULL associated line") );
128e0251 1492
2b5f62a0
VZ
1493 return pLine;
1494 }
b841e0e3 1495
128e0251 1496 // no entries: insert after the group header, if any
2b5f62a0 1497 return GetGroupLine();
c801d85f
KB
1498}
1499
128e0251
VZ
1500void wxFileConfigGroup::SetLastEntry(wxFileConfigEntry *pEntry)
1501{
1502 m_pLastEntry = pEntry;
1503
1504 if ( !m_pLine )
1505 {
1506 // the only situation in which a group without its own line can have
1507 // an entry is when the first entry is added to the initially empty
1508 // root pseudo-group
9a83f860 1509 wxASSERT_MSG( !m_pParent, wxT("unexpected for non root group") );
128e0251
VZ
1510
1511 // let the group know that it does have a line in the file now
1512 m_pLine = pEntry->GetLine();
1513 }
1514}
1515
c801d85f
KB
1516// ----------------------------------------------------------------------------
1517// group name
1518// ----------------------------------------------------------------------------
1519
6dda7a75
VZ
1520void wxFileConfigGroup::UpdateGroupAndSubgroupsLines()
1521{
1522 // update the line of this group
1523 wxFileConfigLineList *line = GetGroupLine();
9a83f860 1524 wxCHECK_RET( line, wxT("a non root group must have a corresponding line!") );
6dda7a75
VZ
1525
1526 // +1: skip the leading '/'
9a83f860 1527 line->SetText(wxString::Format(wxT("[%s]"), GetFullName().c_str() + 1));
6dda7a75
VZ
1528
1529
1530 // also update all subgroups as they have this groups name in their lines
b4a980f4 1531 const size_t nCount = m_aSubgroups.GetCount();
6dda7a75
VZ
1532 for ( size_t n = 0; n < nCount; n++ )
1533 {
1534 m_aSubgroups[n]->UpdateGroupAndSubgroupsLines();
1535 }
1536}
1537
0516e0e8 1538void wxFileConfigGroup::Rename(const wxString& newName)
5d1902d6 1539{
9a83f860 1540 wxCHECK_RET( m_pParent, wxT("the root group can't be renamed") );
128e0251 1541
e10b8ce8
VZ
1542 if ( newName == m_strName )
1543 return;
1544
1545 // we need to remove the group from the parent and it back under the new
1546 // name to keep the parents array of subgroups alphabetically sorted
1547 m_pParent->m_aSubgroups.Remove(this);
1548
5d1902d6
VZ
1549 m_strName = newName;
1550
e10b8ce8
VZ
1551 m_pParent->m_aSubgroups.Add(this);
1552
6dda7a75
VZ
1553 // update the group lines recursively
1554 UpdateGroupAndSubgroupsLines();
5d1902d6
VZ
1555}
1556
0516e0e8 1557wxString wxFileConfigGroup::GetFullName() const
c801d85f 1558{
6dda7a75
VZ
1559 wxString fullname;
1560 if ( Parent() )
1561 fullname = Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR + Name();
1562
1563 return fullname;
c801d85f
KB
1564}
1565
1566// ----------------------------------------------------------------------------
1567// find an item
1568// ----------------------------------------------------------------------------
1569
f5ae0449 1570// use binary search because the array is sorted
0516e0e8 1571wxFileConfigEntry *
86501081 1572wxFileConfigGroup::FindEntry(const wxString& name) const
c801d85f 1573{
c86f1403 1574 size_t i,
f5ae0449 1575 lo = 0,
b4a980f4 1576 hi = m_aEntries.GetCount();
f5ae0449 1577 int res;
0516e0e8 1578 wxFileConfigEntry *pEntry;
f5ae0449
VZ
1579
1580 while ( lo < hi ) {
1581 i = (lo + hi)/2;
1582 pEntry = m_aEntries[i];
1583
da468d38 1584 #if wxCONFIG_CASE_SENSITIVE
86501081 1585 res = pEntry->Name().compare(name);
f5ae0449 1586 #else
86501081 1587 res = pEntry->Name().CmpNoCase(name);
f5ae0449
VZ
1588 #endif
1589
9fbd8b8d 1590 if ( res > 0 )
f5ae0449 1591 hi = i;
9fbd8b8d 1592 else if ( res < 0 )
f5ae0449
VZ
1593 lo = i + 1;
1594 else
1595 return pEntry;
c801d85f
KB
1596 }
1597
1598 return NULL;
1599}
1600
0516e0e8 1601wxFileConfigGroup *
86501081 1602wxFileConfigGroup::FindSubgroup(const wxString& name) const
c801d85f 1603{
c86f1403 1604 size_t i,
f5ae0449 1605 lo = 0,
b4a980f4 1606 hi = m_aSubgroups.GetCount();
f5ae0449 1607 int res;
0516e0e8 1608 wxFileConfigGroup *pGroup;
f5ae0449
VZ
1609
1610 while ( lo < hi ) {
1611 i = (lo + hi)/2;
1612 pGroup = m_aSubgroups[i];
1613
da468d38 1614 #if wxCONFIG_CASE_SENSITIVE
86501081 1615 res = pGroup->Name().compare(name);
f5ae0449 1616 #else
86501081 1617 res = pGroup->Name().CmpNoCase(name);
f5ae0449
VZ
1618 #endif
1619
9fbd8b8d 1620 if ( res > 0 )
f5ae0449 1621 hi = i;
9fbd8b8d 1622 else if ( res < 0 )
f5ae0449
VZ
1623 lo = i + 1;
1624 else
1625 return pGroup;
c801d85f
KB
1626 }
1627
1628 return NULL;
1629}
1630
1631// ----------------------------------------------------------------------------
1632// create a new item
1633// ----------------------------------------------------------------------------
1634
1635// create a new entry and add it to the current group
2b5f62a0 1636wxFileConfigEntry *wxFileConfigGroup::AddEntry(const wxString& strName, int nLine)
c801d85f 1637{
2b5f62a0 1638 wxASSERT( FindEntry(strName) == 0 );
c801d85f 1639
2b5f62a0 1640 wxFileConfigEntry *pEntry = new wxFileConfigEntry(this, strName, nLine);
c801d85f 1641
2b5f62a0
VZ
1642 m_aEntries.Add(pEntry);
1643 return pEntry;
c801d85f
KB
1644}
1645
1646// create a new group and add it to the current group
2b5f62a0 1647wxFileConfigGroup *wxFileConfigGroup::AddSubgroup(const wxString& strName)
c801d85f 1648{
2b5f62a0 1649 wxASSERT( FindSubgroup(strName) == 0 );
c801d85f 1650
2b5f62a0 1651 wxFileConfigGroup *pGroup = new wxFileConfigGroup(this, strName, m_pConfig);
c801d85f 1652
2b5f62a0
VZ
1653 m_aSubgroups.Add(pGroup);
1654 return pGroup;
c801d85f
KB
1655}
1656
1657// ----------------------------------------------------------------------------
1658// delete an item
1659// ----------------------------------------------------------------------------
1660
c3b0ff9c
VZ
1661/*
1662 The delete operations are _very_ slow if we delete the last item of this
1663 group (see comments before GetXXXLineXXX functions for more details),
1664 so it's much better to start with the first entry/group if we want to
1665 delete several of them.
1666 */
1667
86501081 1668bool wxFileConfigGroup::DeleteSubgroupByName(const wxString& name)
5fe256de 1669{
86501081 1670 wxFileConfigGroup * const pGroup = FindSubgroup(name);
bc33be3b 1671
a62848fd 1672 return pGroup ? DeleteSubgroup(pGroup) : false;
5fe256de
VZ
1673}
1674
2b5f62a0
VZ
1675// Delete the subgroup and remove all references to it from
1676// other data structures.
0516e0e8 1677bool wxFileConfigGroup::DeleteSubgroup(wxFileConfigGroup *pGroup)
c801d85f 1678{
9a83f860 1679 wxCHECK_MSG( pGroup, false, wxT("deleting non existing group?") );
bc33be3b 1680
701fb11e 1681 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1682 wxT("Deleting group '%s' from '%s'"),
2b5f62a0
VZ
1683 pGroup->Name().c_str(),
1684 Name().c_str() );
c801d85f 1685
701fb11e 1686 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1687 wxT(" (m_pLine) = prev: %p, this %p, next %p"),
5c33522f
VZ
1688 m_pLine ? static_cast<void*>(m_pLine->Prev()) : 0,
1689 static_cast<void*>(m_pLine),
1690 m_pLine ? static_cast<void*>(m_pLine->Next()) : 0 );
701fb11e 1691 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1692 wxT(" text: '%s'"),
c9f78968
VS
1693 m_pLine ? (const wxChar*)m_pLine->Text().c_str()
1694 : wxEmptyString );
876419ce 1695
701fb11e 1696 // delete all entries...
b4a980f4 1697 size_t nCount = pGroup->m_aEntries.GetCount();
2b5f62a0 1698
701fb11e 1699 wxLogTrace(FILECONF_TRACE_MASK,
9a83f860 1700 wxT("Removing %lu entries"), (unsigned long)nCount );
2b5f62a0
VZ
1701
1702 for ( size_t nEntry = 0; nEntry < nCount; nEntry++ )
1703 {
701fb11e 1704 wxFileConfigLineList *pLine = pGroup->m_aEntries[nEntry]->GetLine();
2b5f62a0 1705
701fb11e 1706 if ( pLine )
2b5f62a0 1707 {
701fb11e 1708 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1709 wxT(" '%s'"),
2b5f62a0
VZ
1710 pLine->Text().c_str() );
1711 m_pConfig->LineListRemove(pLine);
c3b0ff9c 1712 }
2b5f62a0 1713 }
c3b0ff9c 1714
701fb11e 1715 // ...and subgroups of this subgroup
b4a980f4 1716 nCount = pGroup->m_aSubgroups.GetCount();
c3b0ff9c 1717
701fb11e 1718 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1719 wxT("Removing %lu subgroups"), (unsigned long)nCount );
2b5f62a0
VZ
1720
1721 for ( size_t nGroup = 0; nGroup < nCount; nGroup++ )
1722 {
1723 pGroup->DeleteSubgroup(pGroup->m_aSubgroups[0]);
c3b0ff9c
VZ
1724 }
1725
701fb11e
VZ
1726 // and then finally the group itself
1727 wxFileConfigLineList *pLine = pGroup->m_pLine;
1728 if ( pLine )
2b5f62a0 1729 {
701fb11e 1730 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1731 wxT(" Removing line for group '%s' : '%s'"),
2b5f62a0
VZ
1732 pGroup->Name().c_str(),
1733 pLine->Text().c_str() );
701fb11e 1734 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1735 wxT(" Removing from group '%s' : '%s'"),
2b5f62a0 1736 Name().c_str(),
c9f78968
VS
1737 ((m_pLine) ? (const wxChar*)m_pLine->Text().c_str()
1738 : wxEmptyString) );
2b5f62a0 1739
701fb11e
VZ
1740 // notice that we may do this test inside the previous "if"
1741 // because the last entry's line is surely !NULL
2b5f62a0
VZ
1742 if ( pGroup == m_pLastGroup )
1743 {
701fb11e 1744 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1745 wxT(" Removing last group") );
701fb11e
VZ
1746
1747 // our last entry is being deleted, so find the last one which
1748 // stays by going back until we find a subgroup or reach the
1749 // group line
b4a980f4 1750 const size_t nSubgroups = m_aSubgroups.GetCount();
701fb11e
VZ
1751
1752 m_pLastGroup = NULL;
1753 for ( wxFileConfigLineList *pl = pLine->Prev();
6ad0a7d5 1754 pl && !m_pLastGroup;
701fb11e 1755 pl = pl->Prev() )
2b5f62a0 1756 {
701fb11e
VZ
1757 // does this line belong to our subgroup?
1758 for ( size_t n = 0; n < nSubgroups; n++ )
2b5f62a0 1759 {
701fb11e
VZ
1760 // do _not_ call GetGroupLine! we don't want to add it to
1761 // the local file if it's not already there
1762 if ( m_aSubgroups[n]->m_pLine == pl )
1763 {
1764 m_pLastGroup = m_aSubgroups[n];
1765 break;
1766 }
2b5f62a0 1767 }
6ad0a7d5
VZ
1768
1769 if ( pl == m_pLine )
1770 break;
2b5f62a0
VZ
1771 }
1772 }
9fbd8b8d 1773
2b5f62a0
VZ
1774 m_pConfig->LineListRemove(pLine);
1775 }
1776 else
1777 {
701fb11e 1778 wxLogTrace( FILECONF_TRACE_MASK,
9a83f860 1779 wxT(" No line entry for Group '%s'?"),
2b5f62a0
VZ
1780 pGroup->Name().c_str() );
1781 }
1782
2b5f62a0
VZ
1783 m_aSubgroups.Remove(pGroup);
1784 delete pGroup;
1785
a62848fd 1786 return true;
c801d85f
KB
1787}
1788
86501081 1789bool wxFileConfigGroup::DeleteEntry(const wxString& name)
c801d85f 1790{
86501081 1791 wxFileConfigEntry *pEntry = FindEntry(name);
c8adf5ef
VZ
1792 if ( !pEntry )
1793 {
1794 // entry doesn't exist, nothing to do
1795 return false;
1796 }
c801d85f 1797
0516e0e8 1798 wxFileConfigLineList *pLine = pEntry->GetLine();
c3b0ff9c
VZ
1799 if ( pLine != NULL ) {
1800 // notice that we may do this test inside the previous "if" because the
1801 // last entry's line is surely !NULL
1802 if ( pEntry == m_pLastEntry ) {
1803 // our last entry is being deleted - find the last one which stays
1804 wxASSERT( m_pLine != NULL ); // if we have an entry with !NULL pLine...
1805
e86882e3 1806 // find the previous entry (if any)
0516e0e8 1807 wxFileConfigEntry *pNewLast = NULL;
e86882e3
VZ
1808 const wxFileConfigLineList * const
1809 pNewLastLine = m_pLastEntry->GetLine()->Prev();
1810 const size_t nEntries = m_aEntries.GetCount();
1811 for ( size_t n = 0; n < nEntries; n++ ) {
1812 if ( m_aEntries[n]->GetLine() == pNewLastLine ) {
1813 pNewLast = m_aEntries[n];
c3b0ff9c 1814 break;
e86882e3 1815 }
c3b0ff9c
VZ
1816 }
1817
e86882e3
VZ
1818 // pNewLast can be NULL here -- it's ok and can happen if we have no
1819 // entries left
1820 m_pLastEntry = pNewLast;
a610eb73
VZ
1821
1822 // For the root group only, we could be removing the first group line
1823 // here, so update m_pLine to avoid keeping a dangling pointer.
1824 if ( pLine == m_pLine )
1825 SetLine(NULL);
c3b0ff9c
VZ
1826 }
1827
876419ce 1828 m_pConfig->LineListRemove(pLine);
c3b0ff9c 1829 }
876419ce 1830
9fbd8b8d
VZ
1831 m_aEntries.Remove(pEntry);
1832 delete pEntry;
1833
a62848fd 1834 return true;
c801d85f
KB
1835}
1836
c801d85f 1837// ============================================================================
0516e0e8 1838// wxFileConfig::wxFileConfigEntry
c801d85f
KB
1839// ============================================================================
1840
1841// ----------------------------------------------------------------------------
1842// ctor
1843// ----------------------------------------------------------------------------
0516e0e8 1844wxFileConfigEntry::wxFileConfigEntry(wxFileConfigGroup *pParent,
c801d85f
KB
1845 const wxString& strName,
1846 int nLine)
1847 : m_strName(strName)
1848{
b494c48b 1849 wxASSERT( !strName.empty() );
c3b0ff9c 1850
c801d85f
KB
1851 m_pParent = pParent;
1852 m_nLine = nLine;
1853 m_pLine = NULL;
1854
a62848fd 1855 m_bHasValue = false;
c801d85f 1856
da468d38 1857 m_bImmutable = strName[0] == wxCONFIG_IMMUTABLE_PREFIX;
c801d85f
KB
1858 if ( m_bImmutable )
1859 m_strName.erase(0, 1); // remove first character
1860}
1861
1862// ----------------------------------------------------------------------------
1863// set value
1864// ----------------------------------------------------------------------------
1865
0516e0e8 1866void wxFileConfigEntry::SetLine(wxFileConfigLineList *pLine)
c801d85f 1867{
1f905dc5 1868 if ( m_pLine != NULL ) {
7502ba29 1869 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1f905dc5
VZ
1870 Name().c_str(), m_pParent->GetFullName().c_str());
1871 }
c801d85f
KB
1872
1873 m_pLine = pLine;
b841e0e3 1874 Group()->SetLastEntry(this);
c801d85f
KB
1875}
1876
a62848fd 1877// second parameter is false if we read the value from file and prevents the
c801d85f 1878// entry from being marked as 'dirty'
0516e0e8 1879void wxFileConfigEntry::SetValue(const wxString& strValue, bool bUser)
c801d85f 1880{
2b5f62a0
VZ
1881 if ( bUser && IsImmutable() )
1882 {
1883 wxLogWarning( _("attempt to change immutable key '%s' ignored."),
1884 Name().c_str());
1885 return;
1886 }
c801d85f 1887
e1cc6874
VZ
1888 // do nothing if it's the same value: but don't test for it if m_bHasValue
1889 // hadn't been set yet or we'd never write empty values to the file
2b5f62a0
VZ
1890 if ( m_bHasValue && strValue == m_strValue )
1891 return;
c801d85f 1892
a62848fd 1893 m_bHasValue = true;
2b5f62a0 1894 m_strValue = strValue;
8dce54c9 1895
2b5f62a0
VZ
1896 if ( bUser )
1897 {
e1cc6874 1898 wxString strValFiltered;
c801d85f 1899
2b5f62a0
VZ
1900 if ( Group()->Config()->GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS )
1901 {
1902 strValFiltered = strValue;
1903 }
1904 else {
1905 strValFiltered = FilterOutValue(strValue);
1906 }
c801d85f 1907
2b5f62a0
VZ
1908 wxString strLine;
1909 strLine << FilterOutEntryName(m_strName) << wxT('=') << strValFiltered;
c801d85f 1910
128e0251 1911 if ( m_pLine )
2b5f62a0
VZ
1912 {
1913 // entry was read from the local config file, just modify the line
1914 m_pLine->SetText(strLine);
1915 }
128e0251
VZ
1916 else // this entry didn't exist in the local file
1917 {
b1143304
VZ
1918 // add a new line to the file: note that line returned by
1919 // GetLastEntryLine() may be NULL if we're in the root group and it
1920 // doesn't have any entries yet, but this is ok as passing NULL
1921 // line to LineListInsert() means to prepend new line to the list
128e0251
VZ
1922 wxFileConfigLineList *line = Group()->GetLastEntryLine();
1923 m_pLine = Group()->Config()->LineListInsert(strLine, line);
1924
2b5f62a0
VZ
1925 Group()->SetLastEntry(this);
1926 }
2b5f62a0 1927 }
c801d85f
KB
1928}
1929
c801d85f
KB
1930// ============================================================================
1931// global functions
1932// ============================================================================
1933
f5ae0449
VZ
1934// ----------------------------------------------------------------------------
1935// compare functions for array sorting
1936// ----------------------------------------------------------------------------
1937
0516e0e8 1938int CompareEntries(wxFileConfigEntry *p1, wxFileConfigEntry *p2)
f5ae0449 1939{
670f9935 1940#if wxCONFIG_CASE_SENSITIVE
86501081 1941 return p1->Name().compare(p2->Name());
670f9935 1942#else
86501081 1943 return p1->Name().CmpNoCase(p2->Name());
670f9935 1944#endif
f5ae0449
VZ
1945}
1946
0516e0e8 1947int CompareGroups(wxFileConfigGroup *p1, wxFileConfigGroup *p2)
f5ae0449 1948{
670f9935 1949#if wxCONFIG_CASE_SENSITIVE
86501081 1950 return p1->Name().compare(p2->Name());
670f9935 1951#else
86501081 1952 return p1->Name().CmpNoCase(p2->Name());
670f9935 1953#endif
f5ae0449
VZ
1954}
1955
1956// ----------------------------------------------------------------------------
1957// filter functions
1958// ----------------------------------------------------------------------------
1959
b8e9dd43
VZ
1960// undo FilterOutValue
1961static wxString FilterInValue(const wxString& str)
c801d85f 1962{
cdbcd6c1
VZ
1963 wxString strResult;
1964 if ( str.empty() )
1965 return strResult;
c801d85f 1966
cdbcd6c1 1967 strResult.reserve(str.length());
c801d85f 1968
cdbcd6c1
VZ
1969 wxString::const_iterator i = str.begin();
1970 const bool bQuoted = *i == '"';
1971 if ( bQuoted )
1972 ++i;
c801d85f 1973
cdbcd6c1
VZ
1974 for ( const wxString::const_iterator end = str.end(); i != end; ++i )
1975 {
1976 if ( *i == wxT('\\') )
1977 {
1978 if ( ++i == end )
1979 {
1980 wxLogWarning(_("trailing backslash ignored in '%s'"), str.c_str());
1981 break;
1982 }
7502ba29 1983
cdbcd6c1
VZ
1984 switch ( (*i).GetValue() )
1985 {
1986 case wxT('n'):
1987 strResult += wxT('\n');
1988 break;
c801d85f 1989
cdbcd6c1
VZ
1990 case wxT('r'):
1991 strResult += wxT('\r');
1992 break;
c801d85f 1993
cdbcd6c1
VZ
1994 case wxT('t'):
1995 strResult += wxT('\t');
1996 break;
1997
1998 case wxT('\\'):
1999 strResult += wxT('\\');
2000 break;
2001
2002 case wxT('"'):
2003 strResult += wxT('"');
2004 break;
2005 }
2006 }
2007 else // not a backslash
2008 {
2009 if ( *i != wxT('"') || !bQuoted )
2010 {
2011 strResult += *i;
2012 }
2013 else if ( i != end - 1 )
2014 {
2015 wxLogWarning(_("unexpected \" at position %d in '%s'."),
2016 i - str.begin(), str.c_str());
2017 }
2018 //else: it's the last quote of a quoted string, ok
2019 }
c801d85f 2020 }
c801d85f 2021
cdbcd6c1 2022 return strResult;
c801d85f
KB
2023}
2024
2025// quote the string before writing it to file
b8e9dd43 2026static wxString FilterOutValue(const wxString& str)
c801d85f 2027{
b8e9dd43 2028 if ( !str )
76f53a0e 2029 return str;
8bbe427f 2030
c801d85f 2031 wxString strResult;
ba7f9a90 2032 strResult.Alloc(str.Len());
c801d85f
KB
2033
2034 // quoting is necessary to preserve spaces in the beginning of the string
223d09f6 2035 bool bQuote = wxIsspace(str[0]) || str[0] == wxT('"');
c801d85f
KB
2036
2037 if ( bQuote )
223d09f6 2038 strResult += wxT('"');
c801d85f 2039
50920146 2040 wxChar c;
c86f1403 2041 for ( size_t n = 0; n < str.Len(); n++ ) {
c9f78968 2042 switch ( str[n].GetValue() ) {
223d09f6
KB
2043 case wxT('\n'):
2044 c = wxT('n');
c801d85f
KB
2045 break;
2046
223d09f6
KB
2047 case wxT('\r'):
2048 c = wxT('r');
7502ba29
VZ
2049 break;
2050
223d09f6
KB
2051 case wxT('\t'):
2052 c = wxT('t');
c801d85f
KB
2053 break;
2054
223d09f6
KB
2055 case wxT('\\'):
2056 c = wxT('\\');
c801d85f
KB
2057 break;
2058
223d09f6 2059 case wxT('"'):
c5c16a30 2060 if ( bQuote ) {
223d09f6 2061 c = wxT('"');
c5c16a30
VZ
2062 break;
2063 }
c801d85f
KB
2064 //else: fall through
2065
2066 default:
2067 strResult += str[n];
2068 continue; // nothing special to do
2069 }
2070
2071 // we get here only for special characters
223d09f6 2072 strResult << wxT('\\') << c;
c801d85f
KB
2073 }
2074
2075 if ( bQuote )
223d09f6 2076 strResult += wxT('"');
c801d85f
KB
2077
2078 return strResult;
2079}
ac57418f 2080
b8e9dd43
VZ
2081// undo FilterOutEntryName
2082static wxString FilterInEntryName(const wxString& str)
2083{
2084 wxString strResult;
2085 strResult.Alloc(str.Len());
2086
50920146 2087 for ( const wxChar *pc = str.c_str(); *pc != '\0'; pc++ ) {
d9f5d54a
VZ
2088 if ( *pc == wxT('\\') ) {
2089 // we need to test it here or we'd skip past the NUL in the loop line
9a83f860 2090 if ( *++pc == wxT('\0') )
d9f5d54a
VZ
2091 break;
2092 }
b8e9dd43
VZ
2093
2094 strResult += *pc;
2095 }
2096
2097 return strResult;
2098}
ac57418f 2099
b8e9dd43
VZ
2100// sanitize entry or group name: insert '\\' before any special characters
2101static wxString FilterOutEntryName(const wxString& str)
2102{
2103 wxString strResult;
2104 strResult.Alloc(str.Len());
a3ef5bf5 2105
223d09f6 2106 for ( const wxChar *pc = str.c_str(); *pc != wxT('\0'); pc++ ) {
3c9642b5 2107 const wxChar c = *pc;
a3ef5bf5 2108
b8e9dd43 2109 // we explicitly allow some of "safe" chars and 8bit ASCII characters
3c9642b5
VZ
2110 // which will probably never have special meaning and with which we can't
2111 // use isalnum() anyhow (in ASCII built, in Unicode it's just fine)
2112 //
b8e9dd43
VZ
2113 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
2114 // should *not* be quoted
a62848fd 2115 if (
3c9642b5 2116#if !wxUSE_UNICODE
cc3dd6fc 2117 ((unsigned char)c < 127) &&
3c9642b5 2118#endif // ANSI
8709d947 2119 !wxIsalnum(c) && !wxStrchr(wxT("@_/-!.*%()"), c) )
3c9642b5 2120 {
223d09f6 2121 strResult += wxT('\\');
3c9642b5 2122 }
a3ef5bf5 2123
b8e9dd43
VZ
2124 strResult += c;
2125 }
a3ef5bf5 2126
b8e9dd43
VZ
2127 return strResult;
2128}
a3ef5bf5 2129
004c69ab
VZ
2130// we can't put ?: in the ctor initializer list because it confuses some
2131// broken compilers (Borland C++)
2132static wxString GetAppName(const wxString& appName)
2133{
2134 if ( !appName && wxTheApp )
2135 return wxTheApp->GetAppName();
2136 else
2137 return appName;
2138}
d427503c
VZ
2139
2140#endif // wxUSE_CONFIG