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