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