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