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