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