added wxUmaskChanger class and wxCHANGE_UMASK macro and use them instead of duplicati...
[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 bool ret = file.Commit();
987
988 #if defined(__WXMAC__)
989 if ( ret )
990 {
991 FSRef fsRef ;
992 FSCatalogInfo catInfo;
993 FileInfo *finfo ;
994
995 if ( wxMacPathToFSRef( m_strLocalFile , &fsRef ) == noErr )
996 {
997 if ( FSGetCatalogInfo (&fsRef, kFSCatInfoFinderInfo, &catInfo, NULL, NULL, NULL) == noErr )
998 {
999 finfo = (FileInfo*)&catInfo.finderInfo;
1000 finfo->fileType = 'TEXT' ;
1001 finfo->fileCreator = 'ttxt' ;
1002 FSSetCatalogInfo( &fsRef, kFSCatInfoFinderInfo, &catInfo ) ;
1003 }
1004 }
1005 }
1006 #endif // __WXMAC__
1007
1008 return ret;
1009 }
1010
1011 // ----------------------------------------------------------------------------
1012 // renaming groups/entries
1013 // ----------------------------------------------------------------------------
1014
1015 bool wxFileConfig::RenameEntry(const wxString& oldName,
1016 const wxString& newName)
1017 {
1018 // check that the entry exists
1019 wxFileConfigEntry *oldEntry = m_pCurrentGroup->FindEntry(oldName);
1020 if ( !oldEntry )
1021 return false;
1022
1023 // check that the new entry doesn't already exist
1024 if ( m_pCurrentGroup->FindEntry(newName) )
1025 return false;
1026
1027 // delete the old entry, create the new one
1028 wxString value = oldEntry->Value();
1029 if ( !m_pCurrentGroup->DeleteEntry(oldName) )
1030 return false;
1031
1032 wxFileConfigEntry *newEntry = m_pCurrentGroup->AddEntry(newName);
1033 newEntry->SetValue(value);
1034
1035 return true;
1036 }
1037
1038 bool wxFileConfig::RenameGroup(const wxString& oldName,
1039 const wxString& newName)
1040 {
1041 // check that the group exists
1042 wxFileConfigGroup *group = m_pCurrentGroup->FindSubgroup(oldName);
1043 if ( !group )
1044 return false;
1045
1046 // check that the new group doesn't already exist
1047 if ( m_pCurrentGroup->FindSubgroup(newName) )
1048 return false;
1049
1050 group->Rename(newName);
1051
1052 return true;
1053 }
1054
1055 // ----------------------------------------------------------------------------
1056 // delete groups/entries
1057 // ----------------------------------------------------------------------------
1058
1059 bool wxFileConfig::DeleteEntry(const wxString& key, bool bGroupIfEmptyAlso)
1060 {
1061 wxConfigPathChanger path(this, key);
1062
1063 if ( !m_pCurrentGroup->DeleteEntry(path.Name()) )
1064 return false;
1065
1066 if ( bGroupIfEmptyAlso && m_pCurrentGroup->IsEmpty() ) {
1067 if ( m_pCurrentGroup != m_pRootGroup ) {
1068 wxFileConfigGroup *pGroup = m_pCurrentGroup;
1069 SetPath(wxT("..")); // changes m_pCurrentGroup!
1070 m_pCurrentGroup->DeleteSubgroupByName(pGroup->Name());
1071 }
1072 //else: never delete the root group
1073 }
1074
1075 return true;
1076 }
1077
1078 bool wxFileConfig::DeleteGroup(const wxString& key)
1079 {
1080 wxConfigPathChanger path(this, key);
1081
1082 return m_pCurrentGroup->DeleteSubgroupByName(path.Name());
1083 }
1084
1085 bool wxFileConfig::DeleteAll()
1086 {
1087 CleanUp();
1088
1089 if ( wxFile::Exists(m_strLocalFile) && wxRemove(m_strLocalFile) == -1 )
1090 {
1091 wxLogSysError(_("can't delete user configuration file '%s'"), m_strLocalFile.c_str());
1092 return false;
1093 }
1094
1095 m_strLocalFile = m_strGlobalFile = wxT("");
1096 Init();
1097
1098 return true;
1099 }
1100
1101 // ----------------------------------------------------------------------------
1102 // linked list functions
1103 // ----------------------------------------------------------------------------
1104
1105 // append a new line to the end of the list
1106
1107 wxFileConfigLineList *wxFileConfig::LineListAppend(const wxString& str)
1108 {
1109 wxLogTrace( _T("wxFileConfig"),
1110 _T(" ** Adding Line '%s'"),
1111 str.c_str() );
1112 wxLogTrace( _T("wxFileConfig"),
1113 _T(" head: %s"),
1114 ((m_linesHead) ? m_linesHead->Text().c_str() : wxEmptyString) );
1115 wxLogTrace( _T("wxFileConfig"),
1116 _T(" tail: %s"),
1117 ((m_linesTail) ? m_linesTail->Text().c_str() : wxEmptyString) );
1118
1119 wxFileConfigLineList *pLine = new wxFileConfigLineList(str);
1120
1121 if ( m_linesTail == NULL )
1122 {
1123 // list is empty
1124 m_linesHead = pLine;
1125 }
1126 else
1127 {
1128 // adjust pointers
1129 m_linesTail->SetNext(pLine);
1130 pLine->SetPrev(m_linesTail);
1131 }
1132
1133 m_linesTail = pLine;
1134
1135 wxLogTrace( _T("wxFileConfig"),
1136 _T(" head: %s"),
1137 ((m_linesHead) ? m_linesHead->Text().c_str() : wxEmptyString) );
1138 wxLogTrace( _T("wxFileConfig"),
1139 _T(" tail: %s"),
1140 ((m_linesTail) ? m_linesTail->Text().c_str() : wxEmptyString) );
1141
1142 return m_linesTail;
1143 }
1144
1145 // insert a new line after the given one or in the very beginning if !pLine
1146 wxFileConfigLineList *wxFileConfig::LineListInsert(const wxString& str,
1147 wxFileConfigLineList *pLine)
1148 {
1149 wxLogTrace( _T("wxFileConfig"),
1150 _T(" ** Inserting Line '%s' after '%s'"),
1151 str.c_str(),
1152 ((pLine) ? pLine->Text().c_str() : wxEmptyString) );
1153 wxLogTrace( _T("wxFileConfig"),
1154 _T(" head: %s"),
1155 ((m_linesHead) ? m_linesHead->Text().c_str() : wxEmptyString) );
1156 wxLogTrace( _T("wxFileConfig"),
1157 _T(" tail: %s"),
1158 ((m_linesTail) ? m_linesTail->Text().c_str() : wxEmptyString) );
1159
1160 if ( pLine == m_linesTail )
1161 return LineListAppend(str);
1162
1163 wxFileConfigLineList *pNewLine = new wxFileConfigLineList(str);
1164 if ( pLine == NULL )
1165 {
1166 // prepend to the list
1167 pNewLine->SetNext(m_linesHead);
1168 m_linesHead->SetPrev(pNewLine);
1169 m_linesHead = pNewLine;
1170 }
1171 else
1172 {
1173 // insert before pLine
1174 wxFileConfigLineList *pNext = pLine->Next();
1175 pNewLine->SetNext(pNext);
1176 pNewLine->SetPrev(pLine);
1177 pNext->SetPrev(pNewLine);
1178 pLine->SetNext(pNewLine);
1179 }
1180
1181 wxLogTrace( _T("wxFileConfig"),
1182 _T(" head: %s"),
1183 ((m_linesHead) ? m_linesHead->Text().c_str() : wxEmptyString) );
1184 wxLogTrace( _T("wxFileConfig"),
1185 _T(" tail: %s"),
1186 ((m_linesTail) ? m_linesTail->Text().c_str() : wxEmptyString) );
1187
1188 return pNewLine;
1189 }
1190
1191 void wxFileConfig::LineListRemove(wxFileConfigLineList *pLine)
1192 {
1193 wxLogTrace( _T("wxFileConfig"),
1194 _T(" ** Removing Line '%s'"),
1195 pLine->Text().c_str() );
1196 wxLogTrace( _T("wxFileConfig"),
1197 _T(" head: %s"),
1198 ((m_linesHead) ? m_linesHead->Text().c_str() : wxEmptyString) );
1199 wxLogTrace( _T("wxFileConfig"),
1200 _T(" tail: %s"),
1201 ((m_linesTail) ? m_linesTail->Text().c_str() : wxEmptyString) );
1202
1203 wxFileConfigLineList *pPrev = pLine->Prev(),
1204 *pNext = pLine->Next();
1205
1206 // first entry?
1207
1208 if ( pPrev == NULL )
1209 m_linesHead = pNext;
1210 else
1211 pPrev->SetNext(pNext);
1212
1213 // last entry?
1214
1215 if ( pNext == NULL )
1216 m_linesTail = pPrev;
1217 else
1218 pNext->SetPrev(pPrev);
1219
1220 wxLogTrace( _T("wxFileConfig"),
1221 _T(" head: %s"),
1222 ((m_linesHead) ? m_linesHead->Text().c_str() : wxEmptyString) );
1223 wxLogTrace( _T("wxFileConfig"),
1224 _T(" tail: %s"),
1225 ((m_linesTail) ? m_linesTail->Text().c_str() : wxEmptyString) );
1226
1227 delete pLine;
1228 }
1229
1230 bool wxFileConfig::LineListIsEmpty()
1231 {
1232 return m_linesHead == NULL;
1233 }
1234
1235 // ============================================================================
1236 // wxFileConfig::wxFileConfigGroup
1237 // ============================================================================
1238
1239 // ----------------------------------------------------------------------------
1240 // ctor/dtor
1241 // ----------------------------------------------------------------------------
1242
1243 // ctor
1244 wxFileConfigGroup::wxFileConfigGroup(wxFileConfigGroup *pParent,
1245 const wxString& strName,
1246 wxFileConfig *pConfig)
1247 : m_aEntries(CompareEntries),
1248 m_aSubgroups(CompareGroups),
1249 m_strName(strName)
1250 {
1251 m_pConfig = pConfig;
1252 m_pParent = pParent;
1253 m_bDirty = false;
1254 m_pLine = NULL;
1255
1256 m_pLastEntry = NULL;
1257 m_pLastGroup = NULL;
1258 }
1259
1260 // dtor deletes all children
1261 wxFileConfigGroup::~wxFileConfigGroup()
1262 {
1263 // entries
1264 size_t n, nCount = m_aEntries.Count();
1265 for ( n = 0; n < nCount; n++ )
1266 delete m_aEntries[n];
1267
1268 // subgroups
1269 nCount = m_aSubgroups.Count();
1270 for ( n = 0; n < nCount; n++ )
1271 delete m_aSubgroups[n];
1272 }
1273
1274 // ----------------------------------------------------------------------------
1275 // line
1276 // ----------------------------------------------------------------------------
1277
1278 void wxFileConfigGroup::SetLine(wxFileConfigLineList *pLine)
1279 {
1280 wxASSERT( m_pLine == 0 ); // shouldn't be called twice
1281 m_pLine = pLine;
1282 }
1283
1284 /*
1285 This is a bit complicated, so let me explain it in details. All lines that
1286 were read from the local file (the only one we will ever modify) are stored
1287 in a (doubly) linked list. Our problem is to know at which position in this
1288 list should we insert the new entries/subgroups. To solve it we keep three
1289 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1290
1291 m_pLine points to the line containing "[group_name]"
1292 m_pLastEntry points to the last entry of this group in the local file.
1293 m_pLastGroup subgroup
1294
1295 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1296 from the local file, the corresponding variable is set. However, if the group
1297 was read from the global file and then modified or created by the application
1298 these variables are still NULL and we need to create the corresponding lines.
1299 See the following functions (and comments preceding them) for the details of
1300 how we do it.
1301
1302 Also, when our last entry/group are deleted we need to find the new last
1303 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1304 of lines until it either founds an entry/subgroup (and this is the new last
1305 element) or the m_pLine of the group, in which case there are no more entries
1306 (or subgroups) left and m_pLast<element> becomes NULL.
1307
1308 NB: This last problem could be avoided for entries if we added new entries
1309 immediately after m_pLine, but in this case the entries would appear
1310 backwards in the config file (OTOH, it's not that important) and as we
1311 would still need to do it for the subgroups the code wouldn't have been
1312 significantly less complicated.
1313 */
1314
1315 // Return the line which contains "[our name]". If we're still not in the list,
1316 // add our line to it immediately after the last line of our parent group if we
1317 // have it or in the very beginning if we're the root group.
1318 wxFileConfigLineList *wxFileConfigGroup::GetGroupLine()
1319 {
1320 wxLogTrace( _T("wxFileConfig"),
1321 _T(" GetGroupLine() for Group '%s'"),
1322 Name().c_str() );
1323
1324 if ( !m_pLine )
1325 {
1326 wxLogTrace( _T("wxFileConfig"),
1327 _T(" Getting Line item pointer") );
1328
1329 wxFileConfigGroup *pParent = Parent();
1330
1331 // this group wasn't present in local config file, add it now
1332 if ( pParent )
1333 {
1334 wxLogTrace( _T("wxFileConfig"),
1335 _T(" checking parent '%s'"),
1336 pParent->Name().c_str() );
1337
1338 wxString strFullName;
1339
1340 // add 1 to the name because we don't want to start with '/'
1341 strFullName << wxT("[")
1342 << FilterOutEntryName(GetFullName().c_str() + 1)
1343 << wxT("]");
1344 m_pLine = m_pConfig->LineListInsert(strFullName,
1345 pParent->GetLastGroupLine());
1346 pParent->SetLastGroup(this); // we're surely after all the others
1347 }
1348 //else: this is the root group and so we return NULL because we don't
1349 // have any group line
1350 }
1351
1352 return m_pLine;
1353 }
1354
1355 // Return the last line belonging to the subgroups of this group (after which
1356 // we can add a new subgroup), if we don't have any subgroups or entries our
1357 // last line is the group line (m_pLine) itself.
1358 wxFileConfigLineList *wxFileConfigGroup::GetLastGroupLine()
1359 {
1360 // if we have any subgroups, our last line is the last line of the last
1361 // subgroup
1362 if ( m_pLastGroup )
1363 {
1364 wxFileConfigLineList *pLine = m_pLastGroup->GetLastGroupLine();
1365
1366 wxASSERT_MSG( pLine, _T("last group must have !NULL associated line") );
1367
1368 return pLine;
1369 }
1370
1371 // no subgroups, so the last line is the line of thelast entry (if any)
1372 return GetLastEntryLine();
1373 }
1374
1375 // return the last line belonging to the entries of this group (after which
1376 // we can add a new entry), if we don't have any entries we will add the new
1377 // one immediately after the group line itself.
1378 wxFileConfigLineList *wxFileConfigGroup::GetLastEntryLine()
1379 {
1380 wxLogTrace( _T("wxFileConfig"),
1381 _T(" GetLastEntryLine() for Group '%s'"),
1382 Name().c_str() );
1383
1384 if ( m_pLastEntry )
1385 {
1386 wxFileConfigLineList *pLine = m_pLastEntry->GetLine();
1387
1388 wxASSERT_MSG( pLine, _T("last entry must have !NULL associated line") );
1389
1390 return pLine;
1391 }
1392
1393 // no entries: insert after the group header, if any
1394 return GetGroupLine();
1395 }
1396
1397 void wxFileConfigGroup::SetLastEntry(wxFileConfigEntry *pEntry)
1398 {
1399 m_pLastEntry = pEntry;
1400
1401 if ( !m_pLine )
1402 {
1403 // the only situation in which a group without its own line can have
1404 // an entry is when the first entry is added to the initially empty
1405 // root pseudo-group
1406 wxASSERT_MSG( !m_pParent, _T("unexpected for non root group") );
1407
1408 // let the group know that it does have a line in the file now
1409 m_pLine = pEntry->GetLine();
1410 }
1411 }
1412
1413 // ----------------------------------------------------------------------------
1414 // group name
1415 // ----------------------------------------------------------------------------
1416
1417 void wxFileConfigGroup::Rename(const wxString& newName)
1418 {
1419 wxCHECK_RET( m_pParent, _T("the root group can't be renamed") );
1420
1421 m_strName = newName;
1422
1423 // +1: no leading '/'
1424 wxString strFullName;
1425 strFullName << wxT("[") << (GetFullName().c_str() + 1) << wxT("]");
1426
1427 wxFileConfigLineList *line = GetGroupLine();
1428 wxCHECK_RET( line, _T("a non root group must have a corresponding line!") );
1429
1430 line->SetText(strFullName);
1431
1432 SetDirty();
1433 }
1434
1435 wxString wxFileConfigGroup::GetFullName() const
1436 {
1437 if ( Parent() )
1438 return Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR + Name();
1439 else
1440 return wxT("");
1441 }
1442
1443 // ----------------------------------------------------------------------------
1444 // find an item
1445 // ----------------------------------------------------------------------------
1446
1447 // use binary search because the array is sorted
1448 wxFileConfigEntry *
1449 wxFileConfigGroup::FindEntry(const wxChar *szName) const
1450 {
1451 size_t i,
1452 lo = 0,
1453 hi = m_aEntries.Count();
1454 int res;
1455 wxFileConfigEntry *pEntry;
1456
1457 while ( lo < hi ) {
1458 i = (lo + hi)/2;
1459 pEntry = m_aEntries[i];
1460
1461 #if wxCONFIG_CASE_SENSITIVE
1462 res = wxStrcmp(pEntry->Name(), szName);
1463 #else
1464 res = wxStricmp(pEntry->Name(), szName);
1465 #endif
1466
1467 if ( res > 0 )
1468 hi = i;
1469 else if ( res < 0 )
1470 lo = i + 1;
1471 else
1472 return pEntry;
1473 }
1474
1475 return NULL;
1476 }
1477
1478 wxFileConfigGroup *
1479 wxFileConfigGroup::FindSubgroup(const wxChar *szName) const
1480 {
1481 size_t i,
1482 lo = 0,
1483 hi = m_aSubgroups.Count();
1484 int res;
1485 wxFileConfigGroup *pGroup;
1486
1487 while ( lo < hi ) {
1488 i = (lo + hi)/2;
1489 pGroup = m_aSubgroups[i];
1490
1491 #if wxCONFIG_CASE_SENSITIVE
1492 res = wxStrcmp(pGroup->Name(), szName);
1493 #else
1494 res = wxStricmp(pGroup->Name(), szName);
1495 #endif
1496
1497 if ( res > 0 )
1498 hi = i;
1499 else if ( res < 0 )
1500 lo = i + 1;
1501 else
1502 return pGroup;
1503 }
1504
1505 return NULL;
1506 }
1507
1508 // ----------------------------------------------------------------------------
1509 // create a new item
1510 // ----------------------------------------------------------------------------
1511
1512 // create a new entry and add it to the current group
1513 wxFileConfigEntry *wxFileConfigGroup::AddEntry(const wxString& strName, int nLine)
1514 {
1515 wxASSERT( FindEntry(strName) == 0 );
1516
1517 wxFileConfigEntry *pEntry = new wxFileConfigEntry(this, strName, nLine);
1518
1519 m_aEntries.Add(pEntry);
1520 return pEntry;
1521 }
1522
1523 // create a new group and add it to the current group
1524 wxFileConfigGroup *wxFileConfigGroup::AddSubgroup(const wxString& strName)
1525 {
1526 wxASSERT( FindSubgroup(strName) == 0 );
1527
1528 wxFileConfigGroup *pGroup = new wxFileConfigGroup(this, strName, m_pConfig);
1529
1530 m_aSubgroups.Add(pGroup);
1531 return pGroup;
1532 }
1533
1534 // ----------------------------------------------------------------------------
1535 // delete an item
1536 // ----------------------------------------------------------------------------
1537
1538 /*
1539 The delete operations are _very_ slow if we delete the last item of this
1540 group (see comments before GetXXXLineXXX functions for more details),
1541 so it's much better to start with the first entry/group if we want to
1542 delete several of them.
1543 */
1544
1545 bool wxFileConfigGroup::DeleteSubgroupByName(const wxChar *szName)
1546 {
1547 wxFileConfigGroup * const pGroup = FindSubgroup(szName);
1548
1549 return pGroup ? DeleteSubgroup(pGroup) : false;
1550 }
1551
1552 // Delete the subgroup and remove all references to it from
1553 // other data structures.
1554 bool wxFileConfigGroup::DeleteSubgroup(wxFileConfigGroup *pGroup)
1555 {
1556 wxCHECK_MSG( pGroup, false, _T("deleting non existing group?") );
1557
1558 wxLogTrace( _T("wxFileConfig"),
1559 _T("Deleting group '%s' from '%s'"),
1560 pGroup->Name().c_str(),
1561 Name().c_str() );
1562
1563 wxLogTrace( _T("wxFileConfig"),
1564 _T(" (m_pLine) = prev: %p, this %p, next %p"),
1565 ((m_pLine) ? m_pLine->Prev() : 0),
1566 m_pLine,
1567 ((m_pLine) ? m_pLine->Next() : 0) );
1568 wxLogTrace( _T("wxFileConfig"),
1569 _T(" text: '%s'"),
1570 ((m_pLine) ? m_pLine->Text().c_str() : wxEmptyString) );
1571
1572 // delete all entries
1573 size_t nCount = pGroup->m_aEntries.Count();
1574
1575 wxLogTrace(_T("wxFileConfig"),
1576 _T("Removing %lu Entries"),
1577 (unsigned long)nCount );
1578
1579 for ( size_t nEntry = 0; nEntry < nCount; nEntry++ )
1580 {
1581 wxFileConfigLineList *pLine = pGroup->m_aEntries[nEntry]->GetLine();
1582
1583 if ( pLine != 0 )
1584 {
1585 wxLogTrace( _T("wxFileConfig"),
1586 _T(" '%s'"),
1587 pLine->Text().c_str() );
1588 m_pConfig->LineListRemove(pLine);
1589 }
1590 }
1591
1592 // and subgroups of this subgroup
1593
1594 nCount = pGroup->m_aSubgroups.Count();
1595
1596 wxLogTrace( _T("wxFileConfig"),
1597 _T("Removing %lu SubGroups"),
1598 (unsigned long)nCount );
1599
1600 for ( size_t nGroup = 0; nGroup < nCount; nGroup++ )
1601 {
1602 pGroup->DeleteSubgroup(pGroup->m_aSubgroups[0]);
1603 }
1604
1605 // finally the group itself
1606
1607 wxFileConfigLineList *pLine = pGroup->m_pLine;
1608
1609 if ( pLine != 0 )
1610 {
1611 wxLogTrace( _T("wxFileConfig"),
1612 _T(" Removing line entry for Group '%s' : '%s'"),
1613 pGroup->Name().c_str(),
1614 pLine->Text().c_str() );
1615 wxLogTrace( _T("wxFileConfig"),
1616 _T(" Removing from Group '%s' : '%s'"),
1617 Name().c_str(),
1618 ((m_pLine) ? m_pLine->Text().c_str() : wxEmptyString) );
1619
1620 // notice that we may do this test inside the previous "if"
1621 // because the last entry's line is surely !NULL
1622
1623 if ( pGroup == m_pLastGroup )
1624 {
1625 wxLogTrace( _T("wxFileConfig"),
1626 _T(" ------- Removing last group -------") );
1627
1628 // our last entry is being deleted, so find the last one which stays.
1629 // go back until we find a subgroup or reach the group's line, unless
1630 // we are the root group, which we'll notice shortly.
1631
1632 wxFileConfigGroup *pNewLast = 0;
1633 size_t nSubgroups = m_aSubgroups.Count();
1634 wxFileConfigLineList *pl;
1635
1636 for ( pl = pLine->Prev(); pl != m_pLine; pl = pl->Prev() )
1637 {
1638 // is it our subgroup?
1639
1640 for ( size_t n = 0; (pNewLast == 0) && (n < nSubgroups); n++ )
1641 {
1642 // do _not_ call GetGroupLine! we don't want to add it to the local
1643 // file if it's not already there
1644
1645 if ( m_aSubgroups[n]->m_pLine == m_pLine )
1646 pNewLast = m_aSubgroups[n];
1647 }
1648
1649 if ( pNewLast != 0 ) // found?
1650 break;
1651 }
1652
1653 if ( pl == m_pLine || m_pParent == 0 )
1654 {
1655 wxLogTrace( _T("wxFileConfig"),
1656 _T(" ------- No previous group found -------") );
1657
1658 wxASSERT_MSG( !pNewLast || m_pLine == 0,
1659 _T("how comes it has the same line as we?") );
1660
1661 // we've reached the group line without finding any subgroups,
1662 // or realised we removed the last group from the root.
1663
1664 m_pLastGroup = 0;
1665 }
1666 else
1667 {
1668 wxLogTrace( _T("wxFileConfig"),
1669 _T(" ------- Last Group set to '%s' -------"),
1670 pNewLast->Name().c_str() );
1671
1672 m_pLastGroup = pNewLast;
1673 }
1674 }
1675
1676 m_pConfig->LineListRemove(pLine);
1677 }
1678 else
1679 {
1680 wxLogTrace( _T("wxFileConfig"),
1681 _T(" No line entry for Group '%s'?"),
1682 pGroup->Name().c_str() );
1683 }
1684
1685 SetDirty();
1686
1687 m_aSubgroups.Remove(pGroup);
1688 delete pGroup;
1689
1690 return true;
1691 }
1692
1693 bool wxFileConfigGroup::DeleteEntry(const wxChar *szName)
1694 {
1695 wxFileConfigEntry *pEntry = FindEntry(szName);
1696 wxCHECK( pEntry != NULL, false ); // deleting non existing item?
1697
1698 wxFileConfigLineList *pLine = pEntry->GetLine();
1699 if ( pLine != NULL ) {
1700 // notice that we may do this test inside the previous "if" because the
1701 // last entry's line is surely !NULL
1702 if ( pEntry == m_pLastEntry ) {
1703 // our last entry is being deleted - find the last one which stays
1704 wxASSERT( m_pLine != NULL ); // if we have an entry with !NULL pLine...
1705
1706 // go back until we find another entry or reach the group's line
1707 wxFileConfigEntry *pNewLast = NULL;
1708 size_t n, nEntries = m_aEntries.Count();
1709 wxFileConfigLineList *pl;
1710 for ( pl = pLine->Prev(); pl != m_pLine; pl = pl->Prev() ) {
1711 // is it our subgroup?
1712 for ( n = 0; (pNewLast == NULL) && (n < nEntries); n++ ) {
1713 if ( m_aEntries[n]->GetLine() == m_pLine )
1714 pNewLast = m_aEntries[n];
1715 }
1716
1717 if ( pNewLast != NULL ) // found?
1718 break;
1719 }
1720
1721 if ( pl == m_pLine ) {
1722 wxASSERT( !pNewLast ); // how comes it has the same line as we?
1723
1724 // we've reached the group line without finding any subgroups
1725 m_pLastEntry = NULL;
1726 }
1727 else
1728 m_pLastEntry = pNewLast;
1729 }
1730
1731 m_pConfig->LineListRemove(pLine);
1732 }
1733
1734 // we must be written back for the changes to be saved
1735 SetDirty();
1736
1737 m_aEntries.Remove(pEntry);
1738 delete pEntry;
1739
1740 return true;
1741 }
1742
1743 // ----------------------------------------------------------------------------
1744 //
1745 // ----------------------------------------------------------------------------
1746 void wxFileConfigGroup::SetDirty()
1747 {
1748 m_bDirty = true;
1749 if ( Parent() != NULL ) // propagate upwards
1750 Parent()->SetDirty();
1751 }
1752
1753 // ============================================================================
1754 // wxFileConfig::wxFileConfigEntry
1755 // ============================================================================
1756
1757 // ----------------------------------------------------------------------------
1758 // ctor
1759 // ----------------------------------------------------------------------------
1760 wxFileConfigEntry::wxFileConfigEntry(wxFileConfigGroup *pParent,
1761 const wxString& strName,
1762 int nLine)
1763 : m_strName(strName)
1764 {
1765 wxASSERT( !strName.IsEmpty() );
1766
1767 m_pParent = pParent;
1768 m_nLine = nLine;
1769 m_pLine = NULL;
1770
1771 m_bDirty =
1772 m_bHasValue = false;
1773
1774 m_bImmutable = strName[0] == wxCONFIG_IMMUTABLE_PREFIX;
1775 if ( m_bImmutable )
1776 m_strName.erase(0, 1); // remove first character
1777 }
1778
1779 // ----------------------------------------------------------------------------
1780 // set value
1781 // ----------------------------------------------------------------------------
1782
1783 void wxFileConfigEntry::SetLine(wxFileConfigLineList *pLine)
1784 {
1785 if ( m_pLine != NULL ) {
1786 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1787 Name().c_str(), m_pParent->GetFullName().c_str());
1788 }
1789
1790 m_pLine = pLine;
1791 Group()->SetLastEntry(this);
1792 }
1793
1794 // second parameter is false if we read the value from file and prevents the
1795 // entry from being marked as 'dirty'
1796 void wxFileConfigEntry::SetValue(const wxString& strValue, bool bUser)
1797 {
1798 if ( bUser && IsImmutable() )
1799 {
1800 wxLogWarning( _("attempt to change immutable key '%s' ignored."),
1801 Name().c_str());
1802 return;
1803 }
1804
1805 // do nothing if it's the same value: but don't test for it
1806 // if m_bHasValue hadn't been set yet or we'd never write
1807 // empty values to the file
1808
1809 if ( m_bHasValue && strValue == m_strValue )
1810 return;
1811
1812 m_bHasValue = true;
1813 m_strValue = strValue;
1814
1815 if ( bUser )
1816 {
1817 wxString strValFiltered;
1818
1819 if ( Group()->Config()->GetStyle() & wxCONFIG_USE_NO_ESCAPE_CHARACTERS )
1820 {
1821 strValFiltered = strValue;
1822 }
1823 else {
1824 strValFiltered = FilterOutValue(strValue);
1825 }
1826
1827 wxString strLine;
1828 strLine << FilterOutEntryName(m_strName) << wxT('=') << strValFiltered;
1829
1830 if ( m_pLine )
1831 {
1832 // entry was read from the local config file, just modify the line
1833 m_pLine->SetText(strLine);
1834 }
1835 else // this entry didn't exist in the local file
1836 {
1837 // add a new line to the file
1838 wxFileConfigLineList *line = Group()->GetLastEntryLine();
1839 m_pLine = Group()->Config()->LineListInsert(strLine, line);
1840
1841 Group()->SetLastEntry(this);
1842 }
1843
1844 SetDirty();
1845 }
1846 }
1847
1848 void wxFileConfigEntry::SetDirty()
1849 {
1850 m_bDirty = true;
1851 Group()->SetDirty();
1852 }
1853
1854 // ============================================================================
1855 // global functions
1856 // ============================================================================
1857
1858 // ----------------------------------------------------------------------------
1859 // compare functions for array sorting
1860 // ----------------------------------------------------------------------------
1861
1862 int CompareEntries(wxFileConfigEntry *p1, wxFileConfigEntry *p2)
1863 {
1864 #if wxCONFIG_CASE_SENSITIVE
1865 return wxStrcmp(p1->Name(), p2->Name());
1866 #else
1867 return wxStricmp(p1->Name(), p2->Name());
1868 #endif
1869 }
1870
1871 int CompareGroups(wxFileConfigGroup *p1, wxFileConfigGroup *p2)
1872 {
1873 #if wxCONFIG_CASE_SENSITIVE
1874 return wxStrcmp(p1->Name(), p2->Name());
1875 #else
1876 return wxStricmp(p1->Name(), p2->Name());
1877 #endif
1878 }
1879
1880 // ----------------------------------------------------------------------------
1881 // filter functions
1882 // ----------------------------------------------------------------------------
1883
1884 // undo FilterOutValue
1885 static wxString FilterInValue(const wxString& str)
1886 {
1887 wxString strResult;
1888 strResult.Alloc(str.Len());
1889
1890 bool bQuoted = !str.IsEmpty() && str[0] == '"';
1891
1892 for ( size_t n = bQuoted ? 1 : 0; n < str.Len(); n++ ) {
1893 if ( str[n] == wxT('\\') ) {
1894 switch ( str[++n] ) {
1895 case wxT('n'):
1896 strResult += wxT('\n');
1897 break;
1898
1899 case wxT('r'):
1900 strResult += wxT('\r');
1901 break;
1902
1903 case wxT('t'):
1904 strResult += wxT('\t');
1905 break;
1906
1907 case wxT('\\'):
1908 strResult += wxT('\\');
1909 break;
1910
1911 case wxT('"'):
1912 strResult += wxT('"');
1913 break;
1914 }
1915 }
1916 else {
1917 if ( str[n] != wxT('"') || !bQuoted )
1918 strResult += str[n];
1919 else if ( n != str.Len() - 1 ) {
1920 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1921 n, str.c_str());
1922 }
1923 //else: it's the last quote of a quoted string, ok
1924 }
1925 }
1926
1927 return strResult;
1928 }
1929
1930 // quote the string before writing it to file
1931 static wxString FilterOutValue(const wxString& str)
1932 {
1933 if ( !str )
1934 return str;
1935
1936 wxString strResult;
1937 strResult.Alloc(str.Len());
1938
1939 // quoting is necessary to preserve spaces in the beginning of the string
1940 bool bQuote = wxIsspace(str[0]) || str[0] == wxT('"');
1941
1942 if ( bQuote )
1943 strResult += wxT('"');
1944
1945 wxChar c;
1946 for ( size_t n = 0; n < str.Len(); n++ ) {
1947 switch ( str[n] ) {
1948 case wxT('\n'):
1949 c = wxT('n');
1950 break;
1951
1952 case wxT('\r'):
1953 c = wxT('r');
1954 break;
1955
1956 case wxT('\t'):
1957 c = wxT('t');
1958 break;
1959
1960 case wxT('\\'):
1961 c = wxT('\\');
1962 break;
1963
1964 case wxT('"'):
1965 if ( bQuote ) {
1966 c = wxT('"');
1967 break;
1968 }
1969 //else: fall through
1970
1971 default:
1972 strResult += str[n];
1973 continue; // nothing special to do
1974 }
1975
1976 // we get here only for special characters
1977 strResult << wxT('\\') << c;
1978 }
1979
1980 if ( bQuote )
1981 strResult += wxT('"');
1982
1983 return strResult;
1984 }
1985
1986 // undo FilterOutEntryName
1987 static wxString FilterInEntryName(const wxString& str)
1988 {
1989 wxString strResult;
1990 strResult.Alloc(str.Len());
1991
1992 for ( const wxChar *pc = str.c_str(); *pc != '\0'; pc++ ) {
1993 if ( *pc == wxT('\\') )
1994 pc++;
1995
1996 strResult += *pc;
1997 }
1998
1999 return strResult;
2000 }
2001
2002 // sanitize entry or group name: insert '\\' before any special characters
2003 static wxString FilterOutEntryName(const wxString& str)
2004 {
2005 wxString strResult;
2006 strResult.Alloc(str.Len());
2007
2008 for ( const wxChar *pc = str.c_str(); *pc != wxT('\0'); pc++ ) {
2009 const wxChar c = *pc;
2010
2011 // we explicitly allow some of "safe" chars and 8bit ASCII characters
2012 // which will probably never have special meaning and with which we can't
2013 // use isalnum() anyhow (in ASCII built, in Unicode it's just fine)
2014 //
2015 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
2016 // should *not* be quoted
2017 if (
2018 #if !wxUSE_UNICODE
2019 ((unsigned char)c < 127) &&
2020 #endif // ANSI
2021 !wxIsalnum(c) && !wxStrchr(wxT("@_/-!.*%"), c) )
2022 {
2023 strResult += wxT('\\');
2024 }
2025
2026 strResult += c;
2027 }
2028
2029 return strResult;
2030 }
2031
2032 // we can't put ?: in the ctor initializer list because it confuses some
2033 // broken compilers (Borland C++)
2034 static wxString GetAppName(const wxString& appName)
2035 {
2036 if ( !appName && wxTheApp )
2037 return wxTheApp->GetAppName();
2038 else
2039 return appName;
2040 }
2041
2042 #endif // wxUSE_CONFIG
2043
2044
2045 // vi:sts=4:sw=4:et