]> git.saurik.com Git - wxWidgets.git/blob - src/common/fileconf.cpp
implemented better paths handling: dir1/../dir2/file is replaced by dir2/file
[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 license
11 ///////////////////////////////////////////////////////////////////////////////
12
13 #ifdef __GNUG__
14 #pragma implementation "fileconf.h"
15 #endif
16
17 // ----------------------------------------------------------------------------
18 // headers
19 // ----------------------------------------------------------------------------
20
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif //__BORLANDC__
26
27 #if wxUSE_CONFIG
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/config.h"
40 #include "wx/fileconf.h"
41
42 #include "wx/utils.h" // for wxGetHomeDir
43
44 // _WINDOWS_ is defined when windows.h is included,
45 // __WXMSW__ is defined for MS Windows compilation
46 #if defined(__WXMSW__) && !defined(_WINDOWS_)
47 #include <windows.h>
48 #endif //windows.h
49 #if defined(__WXPM__)
50 #define INCL_DOS
51 #include <os2.h>
52 #endif
53
54 #include <stdlib.h>
55 #include <ctype.h>
56
57 // ----------------------------------------------------------------------------
58 // macros
59 // ----------------------------------------------------------------------------
60 #define CONST_CAST ((wxFileConfig *)this)->
61
62 // ----------------------------------------------------------------------------
63 // constants
64 // ----------------------------------------------------------------------------
65 #ifndef MAX_PATH
66 #define MAX_PATH 512
67 #endif
68
69 // ----------------------------------------------------------------------------
70 // global functions declarations
71 // ----------------------------------------------------------------------------
72
73 // compare functions for sorting the arrays
74 static int LINKAGEMODE CompareEntries(ConfigEntry *p1, ConfigEntry *p2);
75 static int LINKAGEMODE CompareGroups(ConfigGroup *p1, ConfigGroup *p2);
76
77 // filter strings
78 static wxString FilterInValue(const wxString& str);
79 static wxString FilterOutValue(const wxString& str);
80
81 static wxString FilterInEntryName(const wxString& str);
82 static wxString FilterOutEntryName(const wxString& str);
83
84 // get the name to use in wxFileConfig ctor
85 static wxString GetAppName(const wxString& appname);
86
87 // ============================================================================
88 // implementation
89 // ============================================================================
90
91 // ----------------------------------------------------------------------------
92 // static functions
93 // ----------------------------------------------------------------------------
94 wxString wxFileConfig::GetGlobalDir()
95 {
96 wxString strDir;
97
98 #ifdef __VMS__ // Note if __VMS is defined __UNIX is also defined
99 strDir = wxT("sys$manager:");
100 #elif defined( __UNIX__ )
101 strDir = wxT("/etc/");
102 #elif defined(__WXPM__)
103 ULONG aulSysInfo[QSV_MAX] = {0};
104 UINT drive;
105 APIRET rc;
106
107 rc = DosQuerySysInfo( 1L, QSV_MAX, (PVOID)aulSysInfo, sizeof(ULONG)*QSV_MAX);
108 if (rc == 0)
109 {
110 drive = aulSysInfo[QSV_BOOT_DRIVE - 1];
111 switch(drive)
112 {
113 case 1:
114 strDir = "A:\\OS2\\";
115 break;
116 case 2:
117 strDir = "B:\\OS2\\";
118 break;
119 case 3:
120 strDir = "C:\\OS2\\";
121 break;
122 case 4:
123 strDir = "D:\\OS2\\";
124 break;
125 case 5:
126 strDir = "E:\\OS2\\";
127 break;
128 case 6:
129 strDir = "F:\\OS2\\";
130 break;
131 case 7:
132 strDir = "G:\\OS2\\";
133 break;
134 case 8:
135 strDir = "H:\\OS2\\";
136 break;
137 case 9:
138 strDir = "I:\\OS2\\";
139 break;
140 case 10:
141 strDir = "J:\\OS2\\";
142 break;
143 case 11:
144 strDir = "K:\\OS2\\";
145 break;
146 case 12:
147 strDir = "L:\\OS2\\";
148 break;
149 case 13:
150 strDir = "M:\\OS2\\";
151 break;
152 case 14:
153 strDir = "N:\\OS2\\";
154 break;
155 case 15:
156 strDir = "O:\\OS2\\";
157 break;
158 case 16:
159 strDir = "P:\\OS2\\";
160 break;
161 case 17:
162 strDir = "Q:\\OS2\\";
163 break;
164 case 18:
165 strDir = "R:\\OS2\\";
166 break;
167 case 19:
168 strDir = "S:\\OS2\\";
169 break;
170 case 20:
171 strDir = "T:\\OS2\\";
172 break;
173 case 21:
174 strDir = "U:\\OS2\\";
175 break;
176 case 22:
177 strDir = "V:\\OS2\\";
178 break;
179 case 23:
180 strDir = "W:\\OS2\\";
181 break;
182 case 24:
183 strDir = "X:\\OS2\\";
184 break;
185 case 25:
186 strDir = "Y:\\OS2\\";
187 break;
188 case 26:
189 strDir = "Z:\\OS2\\";
190 break;
191 }
192 }
193 #elif defined(__WXSTUBS__)
194 wxASSERT_MSG( FALSE, wxT("TODO") ) ;
195 #elif defined(__WXMAC__)
196 {
197 short vRefNum ;
198 long dirID ;
199
200 if ( FindFolder( (short) kOnSystemDisk, kPreferencesFolderType, kDontCreateFolder, &vRefNum, &dirID) == noErr)
201 {
202 FSSpec file ;
203 if ( FSMakeFSSpec( vRefNum , dirID , "\p" , &file ) == noErr )
204 {
205 strDir = wxMacFSSpec2UnixFilename( &file ) + "/" ;
206 }
207 }
208 }
209 #else // Windows
210 wxChar szWinDir[MAX_PATH];
211 ::GetWindowsDirectory(szWinDir, MAX_PATH);
212
213 strDir = szWinDir;
214 strDir << wxT('\\');
215 #endif // Unix/Windows
216
217 return strDir;
218 }
219
220 wxString wxFileConfig::GetLocalDir()
221 {
222 wxString strDir;
223
224 #ifndef __WXMAC__
225 wxGetHomeDir(&strDir);
226
227 #ifndef __VMS__
228 # ifdef __UNIX__
229 if (strDir.Last() != wxT('/')) strDir << wxT('/');
230 #else
231 if (strDir.Last() != wxT('\\')) strDir << wxT('\\');
232 #endif
233 #endif
234 #else
235 // no local dir concept on mac
236 return GetGlobalDir() ;
237 #endif
238
239 return strDir;
240 }
241
242 wxString wxFileConfig::GetGlobalFileName(const wxChar *szFile)
243 {
244 wxString str = GetGlobalDir();
245 str << szFile;
246
247 if ( wxStrchr(szFile, wxT('.')) == NULL )
248 #ifdef __UNIX__
249 str << wxT(".conf");
250 #elif defined( __WXMAC__ )
251 str << " Preferences";
252 #else // Windows
253 str << wxT(".ini");
254 #endif // UNIX/Win
255
256 return str;
257 }
258
259 wxString wxFileConfig::GetLocalFileName(const wxChar *szFile)
260 {
261 #ifdef __VMS__ // On VMS I saw the problem that the home directory was appended
262 // twice for the configuration file. Does that also happen for other
263 // platforms?
264 wxString str = wxT( ' ' );
265 #else
266 wxString str = GetLocalDir();
267 #endif
268
269 #ifdef __UNIX__
270 str << wxT('.');
271 #endif
272
273 str << szFile;
274
275 #ifdef __WXMSW__
276 if ( wxStrchr(szFile, wxT('.')) == NULL )
277 str << wxT(".ini");
278 #endif
279
280
281 #ifdef __WXMAC__
282 str << " Preferences";
283 #endif
284 return str;
285 }
286
287 // ----------------------------------------------------------------------------
288 // ctor
289 // ----------------------------------------------------------------------------
290
291 void wxFileConfig::Init()
292 {
293 m_pCurrentGroup =
294 m_pRootGroup = new ConfigGroup(NULL, "", this);
295
296 m_linesHead =
297 m_linesTail = NULL;
298
299 // it's not an error if (one of the) file(s) doesn't exist
300
301 // parse the global file
302 if ( !m_strGlobalFile.IsEmpty() && wxFile::Exists(m_strGlobalFile) ) {
303 wxTextFile fileGlobal(m_strGlobalFile);
304
305 if ( fileGlobal.Open() ) {
306 Parse(fileGlobal, FALSE /* global */);
307 SetRootPath();
308 }
309 else
310 wxLogWarning(_("can't open global configuration file '%s'."),
311 m_strGlobalFile.c_str());
312 }
313
314 // parse the local file
315 if ( !m_strLocalFile.IsEmpty() && wxFile::Exists(m_strLocalFile) ) {
316 wxTextFile fileLocal(m_strLocalFile);
317 if ( fileLocal.Open() ) {
318 Parse(fileLocal, TRUE /* local */);
319 SetRootPath();
320 }
321 else
322 wxLogWarning(_("can't open user configuration file '%s'."),
323 m_strLocalFile.c_str());
324 }
325 }
326
327 // constructor supports creation of wxFileConfig objects of any type
328 wxFileConfig::wxFileConfig(const wxString& appName, const wxString& vendorName,
329 const wxString& strLocal, const wxString& strGlobal,
330 long style)
331 : wxConfigBase(::GetAppName(appName), vendorName,
332 strLocal, strGlobal,
333 style),
334 m_strLocalFile(strLocal), m_strGlobalFile(strGlobal)
335 {
336 // Make up names for files if empty
337 if ( m_strLocalFile.IsEmpty() && (style & wxCONFIG_USE_LOCAL_FILE) )
338 {
339 m_strLocalFile = GetLocalFileName(GetAppName());
340 }
341
342 if ( m_strGlobalFile.IsEmpty() && (style & wxCONFIG_USE_GLOBAL_FILE) )
343 {
344 m_strGlobalFile = GetGlobalFileName(GetAppName());
345 }
346
347 // Check if styles are not supplied, but filenames are, in which case
348 // add the correct styles.
349 if ( !m_strLocalFile.IsEmpty() )
350 SetStyle(GetStyle() | wxCONFIG_USE_LOCAL_FILE);
351
352 if ( !m_strGlobalFile.IsEmpty() )
353 SetStyle(GetStyle() | wxCONFIG_USE_GLOBAL_FILE);
354
355 // if the path is not absolute, prepend the standard directory to it
356 // UNLESS wxCONFIG_USE_RELATIVE_PATH style is set
357 if ( !(style & wxCONFIG_USE_RELATIVE_PATH) )
358 {
359 if ( !m_strLocalFile.IsEmpty() && !wxIsAbsolutePath(m_strLocalFile) )
360 {
361 wxString strLocal = m_strLocalFile;
362 m_strLocalFile = GetLocalDir();
363 m_strLocalFile << strLocal;
364 }
365
366 if ( !m_strGlobalFile.IsEmpty() && !wxIsAbsolutePath(m_strGlobalFile) )
367 {
368 wxString strGlobal = m_strGlobalFile;
369 m_strGlobalFile = GetGlobalDir();
370 m_strGlobalFile << strGlobal;
371 }
372 }
373
374 Init();
375 }
376
377 void wxFileConfig::CleanUp()
378 {
379 delete m_pRootGroup;
380
381 LineList *pCur = m_linesHead;
382 while ( pCur != NULL ) {
383 LineList *pNext = pCur->Next();
384 delete pCur;
385 pCur = pNext;
386 }
387 }
388
389 wxFileConfig::~wxFileConfig()
390 {
391 Flush();
392
393 CleanUp();
394 }
395
396 // ----------------------------------------------------------------------------
397 // parse a config file
398 // ----------------------------------------------------------------------------
399
400 void wxFileConfig::Parse(wxTextFile& file, bool bLocal)
401 {
402 const wxChar *pStart;
403 const wxChar *pEnd;
404 wxString strLine;
405
406 size_t nLineCount = file.GetLineCount();
407 for ( size_t n = 0; n < nLineCount; n++ ) {
408 strLine = file[n];
409
410 // add the line to linked list
411 if ( bLocal )
412 LineListAppend(strLine);
413
414 // skip leading spaces
415 for ( pStart = strLine; wxIsspace(*pStart); pStart++ )
416 ;
417
418 // skip blank/comment lines
419 if ( *pStart == wxT('\0')|| *pStart == wxT(';') || *pStart == wxT('#') )
420 continue;
421
422 if ( *pStart == wxT('[') ) { // a new group
423 pEnd = pStart;
424
425 while ( *++pEnd != wxT(']') ) {
426 if ( *pEnd == wxT('\n') || *pEnd == wxT('\0') )
427 break;
428 }
429
430 if ( *pEnd != wxT(']') ) {
431 wxLogError(_("file '%s': unexpected character %c at line %d."),
432 file.GetName(), *pEnd, n + 1);
433 continue; // skip this line
434 }
435
436 // group name here is always considered as abs path
437 wxString strGroup;
438 pStart++;
439 strGroup << wxCONFIG_PATH_SEPARATOR
440 << FilterInEntryName(wxString(pStart, pEnd - pStart));
441
442 // will create it if doesn't yet exist
443 SetPath(strGroup);
444
445 if ( bLocal )
446 m_pCurrentGroup->SetLine(m_linesTail);
447
448 // check that there is nothing except comments left on this line
449 bool bCont = TRUE;
450 while ( *++pEnd != wxT('\0') && bCont ) {
451 switch ( *pEnd ) {
452 case wxT('#'):
453 case wxT(';'):
454 bCont = FALSE;
455 break;
456
457 case wxT(' '):
458 case wxT('\t'):
459 // ignore whitespace ('\n' impossible here)
460 break;
461
462 default:
463 wxLogWarning(_("file '%s', line %d: '%s' "
464 "ignored after group header."),
465 file.GetName(), n + 1, pEnd);
466 bCont = FALSE;
467 }
468 }
469 }
470 else { // a key
471 const wxChar *pEnd = pStart;
472 while ( *pEnd != wxT('=') && !wxIsspace(*pEnd) ) {
473 if ( *pEnd == wxT('\\') ) {
474 // next character may be space or not - still take it because it's
475 // quoted
476 pEnd++;
477 }
478
479 pEnd++;
480 }
481
482 wxString strKey(FilterInEntryName(wxString(pStart, pEnd)));
483
484 // skip whitespace
485 while ( isspace(*pEnd) )
486 pEnd++;
487
488 if ( *pEnd++ != wxT('=') ) {
489 wxLogError(_("file '%s', line %d: '=' expected."),
490 file.GetName(), n + 1);
491 }
492 else {
493 ConfigEntry *pEntry = m_pCurrentGroup->FindEntry(strKey);
494
495 if ( pEntry == NULL ) {
496 // new entry
497 pEntry = m_pCurrentGroup->AddEntry(strKey, n);
498
499 if ( bLocal )
500 pEntry->SetLine(m_linesTail);
501 }
502 else {
503 if ( bLocal && pEntry->IsImmutable() ) {
504 // immutable keys can't be changed by user
505 wxLogWarning(_("file '%s', line %d: value for "
506 "immutable key '%s' ignored."),
507 file.GetName(), n + 1, strKey.c_str());
508 continue;
509 }
510 // the condition below catches the cases (a) and (b) but not (c):
511 // (a) global key found second time in global file
512 // (b) key found second (or more) time in local file
513 // (c) key from global file now found in local one
514 // which is exactly what we want.
515 else if ( !bLocal || pEntry->IsLocal() ) {
516 wxLogWarning(_("file '%s', line %d: key '%s' was first "
517 "found at line %d."),
518 file.GetName(), n + 1, strKey.c_str(), pEntry->Line());
519
520 if ( bLocal )
521 pEntry->SetLine(m_linesTail);
522 }
523 }
524
525 // skip whitespace
526 while ( wxIsspace(*pEnd) )
527 pEnd++;
528
529 pEntry->SetValue(FilterInValue(pEnd), FALSE /* read from file */);
530 }
531 }
532 }
533 }
534
535 // ----------------------------------------------------------------------------
536 // set/retrieve path
537 // ----------------------------------------------------------------------------
538
539 void wxFileConfig::SetRootPath()
540 {
541 m_strPath.Empty();
542 m_pCurrentGroup = m_pRootGroup;
543 }
544
545 void wxFileConfig::SetPath(const wxString& strPath)
546 {
547 wxArrayString aParts;
548
549 if ( strPath.IsEmpty() ) {
550 SetRootPath();
551 return;
552 }
553
554 if ( strPath[0] == wxCONFIG_PATH_SEPARATOR ) {
555 // absolute path
556 wxSplitPath(aParts, strPath);
557 }
558 else {
559 // relative path, combine with current one
560 wxString strFullPath = m_strPath;
561 strFullPath << wxCONFIG_PATH_SEPARATOR << strPath;
562 wxSplitPath(aParts, strFullPath);
563 }
564
565 // change current group
566 size_t n;
567 m_pCurrentGroup = m_pRootGroup;
568 for ( n = 0; n < aParts.Count(); n++ ) {
569 ConfigGroup *pNextGroup = m_pCurrentGroup->FindSubgroup(aParts[n]);
570 if ( pNextGroup == NULL )
571 pNextGroup = m_pCurrentGroup->AddSubgroup(aParts[n]);
572 m_pCurrentGroup = pNextGroup;
573 }
574
575 // recombine path parts in one variable
576 m_strPath.Empty();
577 for ( n = 0; n < aParts.Count(); n++ ) {
578 m_strPath << wxCONFIG_PATH_SEPARATOR << aParts[n];
579 }
580 }
581
582 // ----------------------------------------------------------------------------
583 // enumeration
584 // ----------------------------------------------------------------------------
585
586 bool wxFileConfig::GetFirstGroup(wxString& str, long& lIndex) const
587 {
588 lIndex = 0;
589 return GetNextGroup(str, lIndex);
590 }
591
592 bool wxFileConfig::GetNextGroup (wxString& str, long& lIndex) const
593 {
594 if ( size_t(lIndex) < m_pCurrentGroup->Groups().Count() ) {
595 str = m_pCurrentGroup->Groups()[(size_t)lIndex++]->Name();
596 return TRUE;
597 }
598 else
599 return FALSE;
600 }
601
602 bool wxFileConfig::GetFirstEntry(wxString& str, long& lIndex) const
603 {
604 lIndex = 0;
605 return GetNextEntry(str, lIndex);
606 }
607
608 bool wxFileConfig::GetNextEntry (wxString& str, long& lIndex) const
609 {
610 if ( size_t(lIndex) < m_pCurrentGroup->Entries().Count() ) {
611 str = m_pCurrentGroup->Entries()[(size_t)lIndex++]->Name();
612 return TRUE;
613 }
614 else
615 return FALSE;
616 }
617
618 size_t wxFileConfig::GetNumberOfEntries(bool bRecursive) const
619 {
620 size_t n = m_pCurrentGroup->Entries().Count();
621 if ( bRecursive ) {
622 ConfigGroup *pOldCurrentGroup = m_pCurrentGroup;
623 size_t nSubgroups = m_pCurrentGroup->Groups().Count();
624 for ( size_t nGroup = 0; nGroup < nSubgroups; nGroup++ ) {
625 CONST_CAST m_pCurrentGroup = m_pCurrentGroup->Groups()[nGroup];
626 n += GetNumberOfEntries(TRUE);
627 CONST_CAST m_pCurrentGroup = pOldCurrentGroup;
628 }
629 }
630
631 return n;
632 }
633
634 size_t wxFileConfig::GetNumberOfGroups(bool bRecursive) const
635 {
636 size_t n = m_pCurrentGroup->Groups().Count();
637 if ( bRecursive ) {
638 ConfigGroup *pOldCurrentGroup = m_pCurrentGroup;
639 size_t nSubgroups = m_pCurrentGroup->Groups().Count();
640 for ( size_t nGroup = 0; nGroup < nSubgroups; nGroup++ ) {
641 CONST_CAST m_pCurrentGroup = m_pCurrentGroup->Groups()[nGroup];
642 n += GetNumberOfGroups(TRUE);
643 CONST_CAST m_pCurrentGroup = pOldCurrentGroup;
644 }
645 }
646
647 return n;
648 }
649
650 // ----------------------------------------------------------------------------
651 // tests for existence
652 // ----------------------------------------------------------------------------
653
654 bool wxFileConfig::HasGroup(const wxString& strName) const
655 {
656 wxConfigPathChanger path(this, strName);
657
658 ConfigGroup *pGroup = m_pCurrentGroup->FindSubgroup(path.Name());
659 return pGroup != NULL;
660 }
661
662 bool wxFileConfig::HasEntry(const wxString& strName) const
663 {
664 wxConfigPathChanger path(this, strName);
665
666 ConfigEntry *pEntry = m_pCurrentGroup->FindEntry(path.Name());
667 return pEntry != NULL;
668 }
669
670 // ----------------------------------------------------------------------------
671 // read/write values
672 // ----------------------------------------------------------------------------
673
674 bool wxFileConfig::Read(const wxString& key,
675 wxString* pStr) const
676 {
677 wxConfigPathChanger path(this, key);
678
679 ConfigEntry *pEntry = m_pCurrentGroup->FindEntry(path.Name());
680 if (pEntry == NULL) {
681 return FALSE;
682 }
683 else {
684 *pStr = ExpandEnvVars(pEntry->Value());
685 return TRUE;
686 }
687 }
688
689 bool wxFileConfig::Read(const wxString& key,
690 wxString* pStr, const wxString& defVal) const
691 {
692 wxConfigPathChanger path(this, key);
693
694 ConfigEntry *pEntry = m_pCurrentGroup->FindEntry(path.Name());
695 if (pEntry == NULL) {
696 if( IsRecordingDefaults() )
697 ((wxFileConfig *)this)->Write(key,defVal);
698 *pStr = ExpandEnvVars(defVal);
699 return FALSE;
700 }
701 else {
702 *pStr = ExpandEnvVars(pEntry->Value());
703 return TRUE;
704 }
705 }
706
707 bool wxFileConfig::Read(const wxString& key, long *pl) const
708 {
709 wxString str;
710 if ( Read(key, & str) ) {
711 *pl = wxAtol(str);
712 return TRUE;
713 }
714 else {
715 return FALSE;
716 }
717 }
718
719 bool wxFileConfig::Write(const wxString& key, const wxString& szValue)
720 {
721 wxConfigPathChanger path(this, key);
722
723 wxString strName = path.Name();
724 if ( strName.IsEmpty() ) {
725 // setting the value of a group is an error
726 wxASSERT_MSG( wxIsEmpty(szValue), wxT("can't set value of a group!") );
727
728 // ... except if it's empty in which case it's a way to force it's creation
729 m_pCurrentGroup->SetDirty();
730
731 // this will add a line for this group if it didn't have it before
732 (void)m_pCurrentGroup->GetGroupLine();
733 }
734 else {
735 // writing an entry
736
737 // check that the name is reasonable
738 if ( strName[0u] == wxCONFIG_IMMUTABLE_PREFIX ) {
739 wxLogError(_("Config entry name cannot start with '%c'."),
740 wxCONFIG_IMMUTABLE_PREFIX);
741 return FALSE;
742 }
743
744 ConfigEntry *pEntry = m_pCurrentGroup->FindEntry(strName);
745 if ( pEntry == NULL )
746 pEntry = m_pCurrentGroup->AddEntry(strName);
747
748 pEntry->SetValue(szValue);
749 }
750
751 return TRUE;
752 }
753
754 bool wxFileConfig::Write(const wxString& key, long lValue)
755 {
756 // ltoa() is not ANSI :-(
757 wxString buf;
758 buf.Printf(wxT("%ld"), lValue);
759 return Write(key, buf);
760 }
761
762 bool wxFileConfig::Flush(bool /* bCurrentOnly */)
763 {
764 if ( LineListIsEmpty() || !m_pRootGroup->IsDirty() || !m_strLocalFile )
765 return TRUE;
766
767 wxTempFile file(m_strLocalFile);
768
769 if ( !file.IsOpened() ) {
770 wxLogError(_("can't open user configuration file."));
771 return FALSE;
772 }
773
774 // write all strings to file
775 for ( LineList *p = m_linesHead; p != NULL; p = p->Next() ) {
776 if ( !file.Write(p->Text() + wxTextFile::GetEOL()) ) {
777 wxLogError(_("can't write user configuration file."));
778 return FALSE;
779 }
780 }
781
782 #ifndef __WXMAC__
783 return file.Commit();
784 #else
785 bool ret = file.Commit();
786 if ( ret )
787 {
788 FSSpec spec ;
789
790 wxUnixFilename2FSSpec( m_strLocalFile , &spec ) ;
791 FInfo finfo ;
792 if ( FSpGetFInfo( &spec , &finfo ) == noErr )
793 {
794 finfo.fdType = 'TEXT' ;
795 finfo.fdCreator = 'ttxt' ;
796 FSpSetFInfo( &spec , &finfo ) ;
797 }
798 }
799 return ret ;
800 #endif
801 }
802
803 // ----------------------------------------------------------------------------
804 // renaming groups/entries
805 // ----------------------------------------------------------------------------
806
807 bool wxFileConfig::RenameEntry(const wxString& oldName,
808 const wxString& newName)
809 {
810 // check that the entry exists
811 ConfigEntry *oldEntry = m_pCurrentGroup->FindEntry(oldName);
812 if ( !oldEntry )
813 return FALSE;
814
815 // check that the new entry doesn't already exist
816 if ( m_pCurrentGroup->FindEntry(newName) )
817 return FALSE;
818
819 // delete the old entry, create the new one
820 wxString value = oldEntry->Value();
821 if ( !m_pCurrentGroup->DeleteEntry(oldName) )
822 return FALSE;
823
824 ConfigEntry *newEntry = m_pCurrentGroup->AddEntry(newName);
825 newEntry->SetValue(value);
826
827 return TRUE;
828 }
829
830 bool wxFileConfig::RenameGroup(const wxString& oldName,
831 const wxString& newName)
832 {
833 // check that the group exists
834 ConfigGroup *group = m_pCurrentGroup->FindSubgroup(oldName);
835 if ( !group )
836 return FALSE;
837
838 // check that the new group doesn't already exist
839 if ( m_pCurrentGroup->FindSubgroup(newName) )
840 return FALSE;
841
842 group->Rename(newName);
843
844 return TRUE;
845 }
846
847 // ----------------------------------------------------------------------------
848 // delete groups/entries
849 // ----------------------------------------------------------------------------
850
851 bool wxFileConfig::DeleteEntry(const wxString& key, bool bGroupIfEmptyAlso)
852 {
853 wxConfigPathChanger path(this, key);
854
855 if ( !m_pCurrentGroup->DeleteEntry(path.Name()) )
856 return FALSE;
857
858 if ( bGroupIfEmptyAlso && m_pCurrentGroup->IsEmpty() ) {
859 if ( m_pCurrentGroup != m_pRootGroup ) {
860 ConfigGroup *pGroup = m_pCurrentGroup;
861 SetPath(wxT("..")); // changes m_pCurrentGroup!
862 m_pCurrentGroup->DeleteSubgroupByName(pGroup->Name());
863 }
864 //else: never delete the root group
865 }
866
867 return TRUE;
868 }
869
870 bool wxFileConfig::DeleteGroup(const wxString& key)
871 {
872 wxConfigPathChanger path(this, key);
873
874 return m_pCurrentGroup->DeleteSubgroupByName(path.Name());
875 }
876
877 bool wxFileConfig::DeleteAll()
878 {
879 CleanUp();
880
881 if ( remove(m_strLocalFile.fn_str()) == -1 )
882 wxLogSysError(_("can't delete user configuration file '%s'"), m_strLocalFile.c_str());
883
884 m_strLocalFile = m_strGlobalFile = wxT("");
885 Init();
886
887 return TRUE;
888 }
889
890 // ----------------------------------------------------------------------------
891 // linked list functions
892 // ----------------------------------------------------------------------------
893
894 // append a new line to the end of the list
895 LineList *wxFileConfig::LineListAppend(const wxString& str)
896 {
897 LineList *pLine = new LineList(str);
898
899 if ( m_linesTail == NULL ) {
900 // list is empty
901 m_linesHead = pLine;
902 }
903 else {
904 // adjust pointers
905 m_linesTail->SetNext(pLine);
906 pLine->SetPrev(m_linesTail);
907 }
908
909 m_linesTail = pLine;
910 return m_linesTail;
911 }
912
913 // insert a new line after the given one or in the very beginning if !pLine
914 LineList *wxFileConfig::LineListInsert(const wxString& str,
915 LineList *pLine)
916 {
917 if ( pLine == m_linesTail )
918 return LineListAppend(str);
919
920 LineList *pNewLine = new LineList(str);
921 if ( pLine == NULL ) {
922 // prepend to the list
923 pNewLine->SetNext(m_linesHead);
924 m_linesHead->SetPrev(pNewLine);
925 m_linesHead = pNewLine;
926 }
927 else {
928 // insert before pLine
929 LineList *pNext = pLine->Next();
930 pNewLine->SetNext(pNext);
931 pNewLine->SetPrev(pLine);
932 pNext->SetPrev(pNewLine);
933 pLine->SetNext(pNewLine);
934 }
935
936 return pNewLine;
937 }
938
939 void wxFileConfig::LineListRemove(LineList *pLine)
940 {
941 LineList *pPrev = pLine->Prev(),
942 *pNext = pLine->Next();
943
944 // first entry?
945 if ( pPrev == NULL )
946 m_linesHead = pNext;
947 else
948 pPrev->SetNext(pNext);
949
950 // last entry?
951 if ( pNext == NULL )
952 m_linesTail = pPrev;
953 else
954 pNext->SetPrev(pPrev);
955
956 delete pLine;
957 }
958
959 bool wxFileConfig::LineListIsEmpty()
960 {
961 return m_linesHead == NULL;
962 }
963
964 // ============================================================================
965 // wxFileConfig::ConfigGroup
966 // ============================================================================
967
968 // ----------------------------------------------------------------------------
969 // ctor/dtor
970 // ----------------------------------------------------------------------------
971
972 // ctor
973 ConfigGroup::ConfigGroup(ConfigGroup *pParent,
974 const wxString& strName,
975 wxFileConfig *pConfig)
976 : m_aEntries(CompareEntries),
977 m_aSubgroups(CompareGroups),
978 m_strName(strName)
979 {
980 m_pConfig = pConfig;
981 m_pParent = pParent;
982 m_bDirty = FALSE;
983 m_pLine = NULL;
984
985 m_pLastEntry = NULL;
986 m_pLastGroup = NULL;
987 }
988
989 // dtor deletes all children
990 ConfigGroup::~ConfigGroup()
991 {
992 // entries
993 size_t n, nCount = m_aEntries.Count();
994 for ( n = 0; n < nCount; n++ )
995 delete m_aEntries[n];
996
997 // subgroups
998 nCount = m_aSubgroups.Count();
999 for ( n = 0; n < nCount; n++ )
1000 delete m_aSubgroups[n];
1001 }
1002
1003 // ----------------------------------------------------------------------------
1004 // line
1005 // ----------------------------------------------------------------------------
1006
1007 void ConfigGroup::SetLine(LineList *pLine)
1008 {
1009 wxASSERT( m_pLine == NULL ); // shouldn't be called twice
1010
1011 m_pLine = pLine;
1012 }
1013
1014 /*
1015 This is a bit complicated, so let me explain it in details. All lines that
1016 were read from the local file (the only one we will ever modify) are stored
1017 in a (doubly) linked list. Our problem is to know at which position in this
1018 list should we insert the new entries/subgroups. To solve it we keep three
1019 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1020
1021 m_pLine points to the line containing "[group_name]"
1022 m_pLastEntry points to the last entry of this group in the local file.
1023 m_pLastGroup subgroup
1024
1025 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1026 from the local file, the corresponding variable is set. However, if the group
1027 was read from the global file and then modified or created by the application
1028 these variables are still NULL and we need to create the corresponding lines.
1029 See the following functions (and comments preceding them) for the details of
1030 how we do it.
1031
1032 Also, when our last entry/group are deleted we need to find the new last
1033 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1034 of lines until it either founds an entry/subgroup (and this is the new last
1035 element) or the m_pLine of the group, in which case there are no more entries
1036 (or subgroups) left and m_pLast<element> becomes NULL.
1037
1038 NB: This last problem could be avoided for entries if we added new entries
1039 immediately after m_pLine, but in this case the entries would appear
1040 backwards in the config file (OTOH, it's not that important) and as we
1041 would still need to do it for the subgroups the code wouldn't have been
1042 significantly less complicated.
1043 */
1044
1045 // Return the line which contains "[our name]". If we're still not in the list,
1046 // add our line to it immediately after the last line of our parent group if we
1047 // have it or in the very beginning if we're the root group.
1048 LineList *ConfigGroup::GetGroupLine()
1049 {
1050 if ( m_pLine == NULL ) {
1051 ConfigGroup *pParent = Parent();
1052
1053 // this group wasn't present in local config file, add it now
1054 if ( pParent != NULL ) {
1055 wxString strFullName;
1056 strFullName << wxT("[")
1057 // +1: no '/'
1058 << FilterOutEntryName(GetFullName().c_str() + 1)
1059 << wxT("]");
1060 m_pLine = m_pConfig->LineListInsert(strFullName,
1061 pParent->GetLastGroupLine());
1062 pParent->SetLastGroup(this); // we're surely after all the others
1063 }
1064 else {
1065 // we return NULL, so that LineListInsert() will insert us in the
1066 // very beginning
1067 }
1068 }
1069
1070 return m_pLine;
1071 }
1072
1073 // Return the last line belonging to the subgroups of this group (after which
1074 // we can add a new subgroup), if we don't have any subgroups or entries our
1075 // last line is the group line (m_pLine) itself.
1076 LineList *ConfigGroup::GetLastGroupLine()
1077 {
1078 // if we have any subgroups, our last line is the last line of the last
1079 // subgroup
1080 if ( m_pLastGroup != NULL ) {
1081 LineList *pLine = m_pLastGroup->GetLastGroupLine();
1082
1083 wxASSERT( pLine != NULL ); // last group must have !NULL associated line
1084 return pLine;
1085 }
1086
1087 // no subgroups, so the last line is the line of thelast entry (if any)
1088 return GetLastEntryLine();
1089 }
1090
1091 // return the last line belonging to the entries of this group (after which
1092 // we can add a new entry), if we don't have any entries we will add the new
1093 // one immediately after the group line itself.
1094 LineList *ConfigGroup::GetLastEntryLine()
1095 {
1096 if ( m_pLastEntry != NULL ) {
1097 LineList *pLine = m_pLastEntry->GetLine();
1098
1099 wxASSERT( pLine != NULL ); // last entry must have !NULL associated line
1100 return pLine;
1101 }
1102
1103 // no entries: insert after the group header
1104 return GetGroupLine();
1105 }
1106
1107 // ----------------------------------------------------------------------------
1108 // group name
1109 // ----------------------------------------------------------------------------
1110
1111 void ConfigGroup::Rename(const wxString& newName)
1112 {
1113 m_strName = newName;
1114
1115 LineList *line = GetGroupLine();
1116 wxString strFullName;
1117 strFullName << wxT("[") << (GetFullName().c_str() + 1) << wxT("]"); // +1: no '/'
1118 line->SetText(strFullName);
1119
1120 SetDirty();
1121 }
1122
1123 wxString ConfigGroup::GetFullName() const
1124 {
1125 if ( Parent() )
1126 return Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR + Name();
1127 else
1128 return wxT("");
1129 }
1130
1131 // ----------------------------------------------------------------------------
1132 // find an item
1133 // ----------------------------------------------------------------------------
1134
1135 // use binary search because the array is sorted
1136 ConfigEntry *
1137 ConfigGroup::FindEntry(const wxChar *szName) const
1138 {
1139 size_t i,
1140 lo = 0,
1141 hi = m_aEntries.Count();
1142 int res;
1143 ConfigEntry *pEntry;
1144
1145 while ( lo < hi ) {
1146 i = (lo + hi)/2;
1147 pEntry = m_aEntries[i];
1148
1149 #if wxCONFIG_CASE_SENSITIVE
1150 res = wxStrcmp(pEntry->Name(), szName);
1151 #else
1152 res = wxStricmp(pEntry->Name(), szName);
1153 #endif
1154
1155 if ( res > 0 )
1156 hi = i;
1157 else if ( res < 0 )
1158 lo = i + 1;
1159 else
1160 return pEntry;
1161 }
1162
1163 return NULL;
1164 }
1165
1166 ConfigGroup *
1167 ConfigGroup::FindSubgroup(const wxChar *szName) const
1168 {
1169 size_t i,
1170 lo = 0,
1171 hi = m_aSubgroups.Count();
1172 int res;
1173 ConfigGroup *pGroup;
1174
1175 while ( lo < hi ) {
1176 i = (lo + hi)/2;
1177 pGroup = m_aSubgroups[i];
1178
1179 #if wxCONFIG_CASE_SENSITIVE
1180 res = wxStrcmp(pGroup->Name(), szName);
1181 #else
1182 res = wxStricmp(pGroup->Name(), szName);
1183 #endif
1184
1185 if ( res > 0 )
1186 hi = i;
1187 else if ( res < 0 )
1188 lo = i + 1;
1189 else
1190 return pGroup;
1191 }
1192
1193 return NULL;
1194 }
1195
1196 // ----------------------------------------------------------------------------
1197 // create a new item
1198 // ----------------------------------------------------------------------------
1199
1200 // create a new entry and add it to the current group
1201 ConfigEntry *
1202 ConfigGroup::AddEntry(const wxString& strName, int nLine)
1203 {
1204 wxASSERT( FindEntry(strName) == NULL );
1205
1206 ConfigEntry *pEntry = new ConfigEntry(this, strName, nLine);
1207 m_aEntries.Add(pEntry);
1208
1209 return pEntry;
1210 }
1211
1212 // create a new group and add it to the current group
1213 ConfigGroup *
1214 ConfigGroup::AddSubgroup(const wxString& strName)
1215 {
1216 wxASSERT( FindSubgroup(strName) == NULL );
1217
1218 ConfigGroup *pGroup = new ConfigGroup(this, strName, m_pConfig);
1219 m_aSubgroups.Add(pGroup);
1220
1221 return pGroup;
1222 }
1223
1224 // ----------------------------------------------------------------------------
1225 // delete an item
1226 // ----------------------------------------------------------------------------
1227
1228 /*
1229 The delete operations are _very_ slow if we delete the last item of this
1230 group (see comments before GetXXXLineXXX functions for more details),
1231 so it's much better to start with the first entry/group if we want to
1232 delete several of them.
1233 */
1234
1235 bool ConfigGroup::DeleteSubgroupByName(const wxChar *szName)
1236 {
1237 return DeleteSubgroup(FindSubgroup(szName));
1238 }
1239
1240 // doesn't delete the subgroup itself, but does remove references to it from
1241 // all other data structures (and normally the returned pointer should be
1242 // deleted a.s.a.p. because there is nothing much to be done with it anyhow)
1243 bool ConfigGroup::DeleteSubgroup(ConfigGroup *pGroup)
1244 {
1245 wxCHECK( pGroup != NULL, FALSE ); // deleting non existing group?
1246
1247 // delete all entries
1248 size_t nCount = pGroup->m_aEntries.Count();
1249 for ( size_t nEntry = 0; nEntry < nCount; nEntry++ ) {
1250 LineList *pLine = pGroup->m_aEntries[nEntry]->GetLine();
1251 if ( pLine != NULL )
1252 m_pConfig->LineListRemove(pLine);
1253 }
1254
1255 // and subgroups of this sungroup
1256 nCount = pGroup->m_aSubgroups.Count();
1257 for ( size_t nGroup = 0; nGroup < nCount; nGroup++ ) {
1258 pGroup->DeleteSubgroup(pGroup->m_aSubgroups[0]);
1259 }
1260
1261 LineList *pLine = pGroup->m_pLine;
1262 if ( pLine != NULL ) {
1263 // notice that we may do this test inside the previous "if" because the
1264 // last entry's line is surely !NULL
1265 if ( pGroup == m_pLastGroup ) {
1266 // our last entry is being deleted - find the last one which stays
1267 wxASSERT( m_pLine != NULL ); // we have a subgroup with !NULL pLine...
1268
1269 // go back until we find a subgroup or reach the group's line
1270 ConfigGroup *pNewLast = NULL;
1271 size_t n, nSubgroups = m_aSubgroups.Count();
1272 LineList *pl;
1273 for ( pl = pLine->Prev(); pl != m_pLine; pl = pl->Prev() ) {
1274 // is it our subgroup?
1275 for ( n = 0; (pNewLast == NULL) && (n < nSubgroups); n++ ) {
1276 // do _not_ call GetGroupLine! we don't want to add it to the local
1277 // file if it's not already there
1278 if ( m_aSubgroups[n]->m_pLine == m_pLine )
1279 pNewLast = m_aSubgroups[n];
1280 }
1281
1282 if ( pNewLast != NULL ) // found?
1283 break;
1284 }
1285
1286 if ( pl == m_pLine ) {
1287 wxASSERT( !pNewLast ); // how comes it has the same line as we?
1288
1289 // we've reached the group line without finding any subgroups
1290 m_pLastGroup = NULL;
1291 }
1292 else
1293 m_pLastGroup = pNewLast;
1294 }
1295
1296 m_pConfig->LineListRemove(pLine);
1297 }
1298
1299 SetDirty();
1300
1301 m_aSubgroups.Remove(pGroup);
1302 delete pGroup;
1303
1304 return TRUE;
1305 }
1306
1307 bool ConfigGroup::DeleteEntry(const wxChar *szName)
1308 {
1309 ConfigEntry *pEntry = FindEntry(szName);
1310 wxCHECK( pEntry != NULL, FALSE ); // deleting non existing item?
1311
1312 LineList *pLine = pEntry->GetLine();
1313 if ( pLine != NULL ) {
1314 // notice that we may do this test inside the previous "if" because the
1315 // last entry's line is surely !NULL
1316 if ( pEntry == m_pLastEntry ) {
1317 // our last entry is being deleted - find the last one which stays
1318 wxASSERT( m_pLine != NULL ); // if we have an entry with !NULL pLine...
1319
1320 // go back until we find another entry or reach the group's line
1321 ConfigEntry *pNewLast = NULL;
1322 size_t n, nEntries = m_aEntries.Count();
1323 LineList *pl;
1324 for ( pl = pLine->Prev(); pl != m_pLine; pl = pl->Prev() ) {
1325 // is it our subgroup?
1326 for ( n = 0; (pNewLast == NULL) && (n < nEntries); n++ ) {
1327 if ( m_aEntries[n]->GetLine() == m_pLine )
1328 pNewLast = m_aEntries[n];
1329 }
1330
1331 if ( pNewLast != NULL ) // found?
1332 break;
1333 }
1334
1335 if ( pl == m_pLine ) {
1336 wxASSERT( !pNewLast ); // how comes it has the same line as we?
1337
1338 // we've reached the group line without finding any subgroups
1339 m_pLastEntry = NULL;
1340 }
1341 else
1342 m_pLastEntry = pNewLast;
1343 }
1344
1345 m_pConfig->LineListRemove(pLine);
1346 }
1347
1348 // we must be written back for the changes to be saved
1349 SetDirty();
1350
1351 m_aEntries.Remove(pEntry);
1352 delete pEntry;
1353
1354 return TRUE;
1355 }
1356
1357 // ----------------------------------------------------------------------------
1358 //
1359 // ----------------------------------------------------------------------------
1360 void ConfigGroup::SetDirty()
1361 {
1362 m_bDirty = TRUE;
1363 if ( Parent() != NULL ) // propagate upwards
1364 Parent()->SetDirty();
1365 }
1366
1367 // ============================================================================
1368 // wxFileConfig::ConfigEntry
1369 // ============================================================================
1370
1371 // ----------------------------------------------------------------------------
1372 // ctor
1373 // ----------------------------------------------------------------------------
1374 ConfigEntry::ConfigEntry(ConfigGroup *pParent,
1375 const wxString& strName,
1376 int nLine)
1377 : m_strName(strName)
1378 {
1379 wxASSERT( !strName.IsEmpty() );
1380
1381 m_pParent = pParent;
1382 m_nLine = nLine;
1383 m_pLine = NULL;
1384
1385 m_bDirty = FALSE;
1386
1387 m_bImmutable = strName[0] == wxCONFIG_IMMUTABLE_PREFIX;
1388 if ( m_bImmutable )
1389 m_strName.erase(0, 1); // remove first character
1390 }
1391
1392 // ----------------------------------------------------------------------------
1393 // set value
1394 // ----------------------------------------------------------------------------
1395
1396 void ConfigEntry::SetLine(LineList *pLine)
1397 {
1398 if ( m_pLine != NULL ) {
1399 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1400 Name().c_str(), m_pParent->GetFullName().c_str());
1401 }
1402
1403 m_pLine = pLine;
1404 Group()->SetLastEntry(this);
1405 }
1406
1407 // second parameter is FALSE if we read the value from file and prevents the
1408 // entry from being marked as 'dirty'
1409 void ConfigEntry::SetValue(const wxString& strValue, bool bUser)
1410 {
1411 if ( bUser && IsImmutable() ) {
1412 wxLogWarning(_("attempt to change immutable key '%s' ignored."),
1413 Name().c_str());
1414 return;
1415 }
1416
1417 // do nothing if it's the same value
1418 if ( strValue == m_strValue )
1419 return;
1420
1421 m_strValue = strValue;
1422
1423 if ( bUser ) {
1424 wxString strVal = FilterOutValue(strValue);
1425 wxString strLine;
1426 strLine << FilterOutEntryName(m_strName) << wxT('=') << strVal;
1427
1428 if ( m_pLine != NULL ) {
1429 // entry was read from the local config file, just modify the line
1430 m_pLine->SetText(strLine);
1431 }
1432 else {
1433 // add a new line to the file
1434 wxASSERT( m_nLine == wxNOT_FOUND ); // consistency check
1435
1436 m_pLine = Group()->Config()->LineListInsert(strLine,
1437 Group()->GetLastEntryLine());
1438 Group()->SetLastEntry(this);
1439 }
1440
1441 SetDirty();
1442 }
1443 }
1444
1445 void ConfigEntry::SetDirty()
1446 {
1447 m_bDirty = TRUE;
1448 Group()->SetDirty();
1449 }
1450
1451 // ============================================================================
1452 // global functions
1453 // ============================================================================
1454
1455 // ----------------------------------------------------------------------------
1456 // compare functions for array sorting
1457 // ----------------------------------------------------------------------------
1458
1459 int CompareEntries(ConfigEntry *p1,
1460 ConfigEntry *p2)
1461 {
1462 #if wxCONFIG_CASE_SENSITIVE
1463 return wxStrcmp(p1->Name(), p2->Name());
1464 #else
1465 return wxStricmp(p1->Name(), p2->Name());
1466 #endif
1467 }
1468
1469 int CompareGroups(ConfigGroup *p1,
1470 ConfigGroup *p2)
1471 {
1472 #if wxCONFIG_CASE_SENSITIVE
1473 return wxStrcmp(p1->Name(), p2->Name());
1474 #else
1475 return wxStricmp(p1->Name(), p2->Name());
1476 #endif
1477 }
1478
1479 // ----------------------------------------------------------------------------
1480 // filter functions
1481 // ----------------------------------------------------------------------------
1482
1483 // undo FilterOutValue
1484 static wxString FilterInValue(const wxString& str)
1485 {
1486 wxString strResult;
1487 strResult.Alloc(str.Len());
1488
1489 bool bQuoted = !str.IsEmpty() && str[0] == '"';
1490
1491 for ( size_t n = bQuoted ? 1 : 0; n < str.Len(); n++ ) {
1492 if ( str[n] == wxT('\\') ) {
1493 switch ( str[++n] ) {
1494 case wxT('n'):
1495 strResult += wxT('\n');
1496 break;
1497
1498 case wxT('r'):
1499 strResult += wxT('\r');
1500 break;
1501
1502 case wxT('t'):
1503 strResult += wxT('\t');
1504 break;
1505
1506 case wxT('\\'):
1507 strResult += wxT('\\');
1508 break;
1509
1510 case wxT('"'):
1511 strResult += wxT('"');
1512 break;
1513 }
1514 }
1515 else {
1516 if ( str[n] != wxT('"') || !bQuoted )
1517 strResult += str[n];
1518 else if ( n != str.Len() - 1 ) {
1519 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1520 n, str.c_str());
1521 }
1522 //else: it's the last quote of a quoted string, ok
1523 }
1524 }
1525
1526 return strResult;
1527 }
1528
1529 // quote the string before writing it to file
1530 static wxString FilterOutValue(const wxString& str)
1531 {
1532 if ( !str )
1533 return str;
1534
1535 wxString strResult;
1536 strResult.Alloc(str.Len());
1537
1538 // quoting is necessary to preserve spaces in the beginning of the string
1539 bool bQuote = wxIsspace(str[0]) || str[0] == wxT('"');
1540
1541 if ( bQuote )
1542 strResult += wxT('"');
1543
1544 wxChar c;
1545 for ( size_t n = 0; n < str.Len(); n++ ) {
1546 switch ( str[n] ) {
1547 case wxT('\n'):
1548 c = wxT('n');
1549 break;
1550
1551 case wxT('\r'):
1552 c = wxT('r');
1553 break;
1554
1555 case wxT('\t'):
1556 c = wxT('t');
1557 break;
1558
1559 case wxT('\\'):
1560 c = wxT('\\');
1561 break;
1562
1563 case wxT('"'):
1564 if ( bQuote ) {
1565 c = wxT('"');
1566 break;
1567 }
1568 //else: fall through
1569
1570 default:
1571 strResult += str[n];
1572 continue; // nothing special to do
1573 }
1574
1575 // we get here only for special characters
1576 strResult << wxT('\\') << c;
1577 }
1578
1579 if ( bQuote )
1580 strResult += wxT('"');
1581
1582 return strResult;
1583 }
1584
1585 // undo FilterOutEntryName
1586 static wxString FilterInEntryName(const wxString& str)
1587 {
1588 wxString strResult;
1589 strResult.Alloc(str.Len());
1590
1591 for ( const wxChar *pc = str.c_str(); *pc != '\0'; pc++ ) {
1592 if ( *pc == wxT('\\') )
1593 pc++;
1594
1595 strResult += *pc;
1596 }
1597
1598 return strResult;
1599 }
1600
1601 // sanitize entry or group name: insert '\\' before any special characters
1602 static wxString FilterOutEntryName(const wxString& str)
1603 {
1604 wxString strResult;
1605 strResult.Alloc(str.Len());
1606
1607 for ( const wxChar *pc = str.c_str(); *pc != wxT('\0'); pc++ ) {
1608 wxChar c = *pc;
1609
1610 // we explicitly allow some of "safe" chars and 8bit ASCII characters
1611 // which will probably never have special meaning
1612 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
1613 // should *not* be quoted
1614 if ( !wxIsalnum(c) && !wxStrchr(wxT("@_/-!.*%"), c) && ((c & 0x80) == 0) )
1615 strResult += wxT('\\');
1616
1617 strResult += c;
1618 }
1619
1620 return strResult;
1621 }
1622
1623 // we can't put ?: in the ctor initializer list because it confuses some
1624 // broken compilers (Borland C++)
1625 static wxString GetAppName(const wxString& appName)
1626 {
1627 if ( !appName && wxTheApp )
1628 return wxTheApp->GetAppName();
1629 else
1630 return appName;
1631 }
1632
1633 #endif // wxUSE_CONFIG
1634