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