]> git.saurik.com Git - wxWidgets.git/blob - src/common/fileconf.cpp
one of error messages had way too much spaces in it
[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 && *pEnd != wxT('=') && !wxIsspace(*pEnd) ) {
473 if ( *pEnd == wxT('\\') ) {
474 // next character may be space or not - still take it because it's
475 // quoted (unless there is nothing)
476 pEnd++;
477 if ( !*pEnd ) {
478 // the error message will be given below anyhow
479 break;
480 }
481 }
482
483 pEnd++;
484 }
485
486 wxString strKey(FilterInEntryName(wxString(pStart, pEnd)));
487
488 // skip whitespace
489 while ( isspace(*pEnd) )
490 pEnd++;
491
492 if ( *pEnd++ != wxT('=') ) {
493 wxLogError(_("file '%s', line %d: '=' expected."),
494 file.GetName(), n + 1);
495 }
496 else {
497 ConfigEntry *pEntry = m_pCurrentGroup->FindEntry(strKey);
498
499 if ( pEntry == NULL ) {
500 // new entry
501 pEntry = m_pCurrentGroup->AddEntry(strKey, n);
502
503 if ( bLocal )
504 pEntry->SetLine(m_linesTail);
505 }
506 else {
507 if ( bLocal && pEntry->IsImmutable() ) {
508 // immutable keys can't be changed by user
509 wxLogWarning(_("file '%s', line %d: value for "
510 "immutable key '%s' ignored."),
511 file.GetName(), n + 1, strKey.c_str());
512 continue;
513 }
514 // the condition below catches the cases (a) and (b) but not (c):
515 // (a) global key found second time in global file
516 // (b) key found second (or more) time in local file
517 // (c) key from global file now found in local one
518 // which is exactly what we want.
519 else if ( !bLocal || pEntry->IsLocal() ) {
520 wxLogWarning(_("file '%s', line %d: key '%s' was first "
521 "found at line %d."),
522 file.GetName(), n + 1, strKey.c_str(), pEntry->Line());
523
524 if ( bLocal )
525 pEntry->SetLine(m_linesTail);
526 }
527 }
528
529 // skip whitespace
530 while ( wxIsspace(*pEnd) )
531 pEnd++;
532
533 pEntry->SetValue(FilterInValue(pEnd), FALSE /* read from file */);
534 }
535 }
536 }
537 }
538
539 // ----------------------------------------------------------------------------
540 // set/retrieve path
541 // ----------------------------------------------------------------------------
542
543 void wxFileConfig::SetRootPath()
544 {
545 m_strPath.Empty();
546 m_pCurrentGroup = m_pRootGroup;
547 }
548
549 void wxFileConfig::SetPath(const wxString& strPath)
550 {
551 wxArrayString aParts;
552
553 if ( strPath.IsEmpty() ) {
554 SetRootPath();
555 return;
556 }
557
558 if ( strPath[0] == wxCONFIG_PATH_SEPARATOR ) {
559 // absolute path
560 wxSplitPath(aParts, strPath);
561 }
562 else {
563 // relative path, combine with current one
564 wxString strFullPath = m_strPath;
565 strFullPath << wxCONFIG_PATH_SEPARATOR << strPath;
566 wxSplitPath(aParts, strFullPath);
567 }
568
569 // change current group
570 size_t n;
571 m_pCurrentGroup = m_pRootGroup;
572 for ( n = 0; n < aParts.Count(); n++ ) {
573 ConfigGroup *pNextGroup = m_pCurrentGroup->FindSubgroup(aParts[n]);
574 if ( pNextGroup == NULL )
575 pNextGroup = m_pCurrentGroup->AddSubgroup(aParts[n]);
576 m_pCurrentGroup = pNextGroup;
577 }
578
579 // recombine path parts in one variable
580 m_strPath.Empty();
581 for ( n = 0; n < aParts.Count(); n++ ) {
582 m_strPath << wxCONFIG_PATH_SEPARATOR << aParts[n];
583 }
584 }
585
586 // ----------------------------------------------------------------------------
587 // enumeration
588 // ----------------------------------------------------------------------------
589
590 bool wxFileConfig::GetFirstGroup(wxString& str, long& lIndex) const
591 {
592 lIndex = 0;
593 return GetNextGroup(str, lIndex);
594 }
595
596 bool wxFileConfig::GetNextGroup (wxString& str, long& lIndex) const
597 {
598 if ( size_t(lIndex) < m_pCurrentGroup->Groups().Count() ) {
599 str = m_pCurrentGroup->Groups()[(size_t)lIndex++]->Name();
600 return TRUE;
601 }
602 else
603 return FALSE;
604 }
605
606 bool wxFileConfig::GetFirstEntry(wxString& str, long& lIndex) const
607 {
608 lIndex = 0;
609 return GetNextEntry(str, lIndex);
610 }
611
612 bool wxFileConfig::GetNextEntry (wxString& str, long& lIndex) const
613 {
614 if ( size_t(lIndex) < m_pCurrentGroup->Entries().Count() ) {
615 str = m_pCurrentGroup->Entries()[(size_t)lIndex++]->Name();
616 return TRUE;
617 }
618 else
619 return FALSE;
620 }
621
622 size_t wxFileConfig::GetNumberOfEntries(bool bRecursive) const
623 {
624 size_t n = m_pCurrentGroup->Entries().Count();
625 if ( bRecursive ) {
626 ConfigGroup *pOldCurrentGroup = m_pCurrentGroup;
627 size_t nSubgroups = m_pCurrentGroup->Groups().Count();
628 for ( size_t nGroup = 0; nGroup < nSubgroups; nGroup++ ) {
629 CONST_CAST m_pCurrentGroup = m_pCurrentGroup->Groups()[nGroup];
630 n += GetNumberOfEntries(TRUE);
631 CONST_CAST m_pCurrentGroup = pOldCurrentGroup;
632 }
633 }
634
635 return n;
636 }
637
638 size_t wxFileConfig::GetNumberOfGroups(bool bRecursive) const
639 {
640 size_t n = m_pCurrentGroup->Groups().Count();
641 if ( bRecursive ) {
642 ConfigGroup *pOldCurrentGroup = m_pCurrentGroup;
643 size_t nSubgroups = m_pCurrentGroup->Groups().Count();
644 for ( size_t nGroup = 0; nGroup < nSubgroups; nGroup++ ) {
645 CONST_CAST m_pCurrentGroup = m_pCurrentGroup->Groups()[nGroup];
646 n += GetNumberOfGroups(TRUE);
647 CONST_CAST m_pCurrentGroup = pOldCurrentGroup;
648 }
649 }
650
651 return n;
652 }
653
654 // ----------------------------------------------------------------------------
655 // tests for existence
656 // ----------------------------------------------------------------------------
657
658 bool wxFileConfig::HasGroup(const wxString& strName) const
659 {
660 wxConfigPathChanger path(this, strName);
661
662 ConfigGroup *pGroup = m_pCurrentGroup->FindSubgroup(path.Name());
663 return pGroup != NULL;
664 }
665
666 bool wxFileConfig::HasEntry(const wxString& strName) const
667 {
668 wxConfigPathChanger path(this, strName);
669
670 ConfigEntry *pEntry = m_pCurrentGroup->FindEntry(path.Name());
671 return pEntry != NULL;
672 }
673
674 // ----------------------------------------------------------------------------
675 // read/write values
676 // ----------------------------------------------------------------------------
677
678 bool wxFileConfig::Read(const wxString& key,
679 wxString* pStr) const
680 {
681 wxConfigPathChanger path(this, key);
682
683 ConfigEntry *pEntry = m_pCurrentGroup->FindEntry(path.Name());
684 if (pEntry == NULL) {
685 return FALSE;
686 }
687 else {
688 *pStr = ExpandEnvVars(pEntry->Value());
689 return TRUE;
690 }
691 }
692
693 bool wxFileConfig::Read(const wxString& key,
694 wxString* pStr, const wxString& defVal) const
695 {
696 wxConfigPathChanger path(this, key);
697
698 ConfigEntry *pEntry = m_pCurrentGroup->FindEntry(path.Name());
699 if (pEntry == NULL) {
700 if( IsRecordingDefaults() )
701 ((wxFileConfig *)this)->Write(key,defVal);
702 *pStr = ExpandEnvVars(defVal);
703 return FALSE;
704 }
705 else {
706 *pStr = ExpandEnvVars(pEntry->Value());
707 return TRUE;
708 }
709 }
710
711 bool wxFileConfig::Read(const wxString& key, long *pl) const
712 {
713 wxString str;
714 if ( Read(key, & str) ) {
715 *pl = wxAtol(str);
716 return TRUE;
717 }
718 else {
719 return FALSE;
720 }
721 }
722
723 bool wxFileConfig::Write(const wxString& key, const wxString& szValue)
724 {
725 wxConfigPathChanger path(this, key);
726
727 wxString strName = path.Name();
728 if ( strName.IsEmpty() ) {
729 // setting the value of a group is an error
730 wxASSERT_MSG( wxIsEmpty(szValue), wxT("can't set value of a group!") );
731
732 // ... except if it's empty in which case it's a way to force it's creation
733 m_pCurrentGroup->SetDirty();
734
735 // this will add a line for this group if it didn't have it before
736 (void)m_pCurrentGroup->GetGroupLine();
737 }
738 else {
739 // writing an entry
740
741 // check that the name is reasonable
742 if ( strName[0u] == wxCONFIG_IMMUTABLE_PREFIX ) {
743 wxLogError(_("Config entry name cannot start with '%c'."),
744 wxCONFIG_IMMUTABLE_PREFIX);
745 return FALSE;
746 }
747
748 ConfigEntry *pEntry = m_pCurrentGroup->FindEntry(strName);
749 if ( pEntry == NULL )
750 pEntry = m_pCurrentGroup->AddEntry(strName);
751
752 pEntry->SetValue(szValue);
753 }
754
755 return TRUE;
756 }
757
758 bool wxFileConfig::Write(const wxString& key, long lValue)
759 {
760 // ltoa() is not ANSI :-(
761 wxString buf;
762 buf.Printf(wxT("%ld"), lValue);
763 return Write(key, buf);
764 }
765
766 bool wxFileConfig::Flush(bool /* bCurrentOnly */)
767 {
768 if ( LineListIsEmpty() || !m_pRootGroup->IsDirty() || !m_strLocalFile )
769 return TRUE;
770
771 wxTempFile file(m_strLocalFile);
772
773 if ( !file.IsOpened() ) {
774 wxLogError(_("can't open user configuration file."));
775 return FALSE;
776 }
777
778 // write all strings to file
779 for ( LineList *p = m_linesHead; p != NULL; p = p->Next() ) {
780 if ( !file.Write(p->Text() + wxTextFile::GetEOL()) ) {
781 wxLogError(_("can't write user configuration file."));
782 return FALSE;
783 }
784 }
785
786 #ifndef __WXMAC__
787 return file.Commit();
788 #else
789 bool ret = file.Commit();
790 if ( ret )
791 {
792 FSSpec spec ;
793
794 wxUnixFilename2FSSpec( m_strLocalFile , &spec ) ;
795 FInfo finfo ;
796 if ( FSpGetFInfo( &spec , &finfo ) == noErr )
797 {
798 finfo.fdType = 'TEXT' ;
799 finfo.fdCreator = 'ttxt' ;
800 FSpSetFInfo( &spec , &finfo ) ;
801 }
802 }
803 return ret ;
804 #endif
805 }
806
807 // ----------------------------------------------------------------------------
808 // renaming groups/entries
809 // ----------------------------------------------------------------------------
810
811 bool wxFileConfig::RenameEntry(const wxString& oldName,
812 const wxString& newName)
813 {
814 // check that the entry exists
815 ConfigEntry *oldEntry = m_pCurrentGroup->FindEntry(oldName);
816 if ( !oldEntry )
817 return FALSE;
818
819 // check that the new entry doesn't already exist
820 if ( m_pCurrentGroup->FindEntry(newName) )
821 return FALSE;
822
823 // delete the old entry, create the new one
824 wxString value = oldEntry->Value();
825 if ( !m_pCurrentGroup->DeleteEntry(oldName) )
826 return FALSE;
827
828 ConfigEntry *newEntry = m_pCurrentGroup->AddEntry(newName);
829 newEntry->SetValue(value);
830
831 return TRUE;
832 }
833
834 bool wxFileConfig::RenameGroup(const wxString& oldName,
835 const wxString& newName)
836 {
837 // check that the group exists
838 ConfigGroup *group = m_pCurrentGroup->FindSubgroup(oldName);
839 if ( !group )
840 return FALSE;
841
842 // check that the new group doesn't already exist
843 if ( m_pCurrentGroup->FindSubgroup(newName) )
844 return FALSE;
845
846 group->Rename(newName);
847
848 return TRUE;
849 }
850
851 // ----------------------------------------------------------------------------
852 // delete groups/entries
853 // ----------------------------------------------------------------------------
854
855 bool wxFileConfig::DeleteEntry(const wxString& key, bool bGroupIfEmptyAlso)
856 {
857 wxConfigPathChanger path(this, key);
858
859 if ( !m_pCurrentGroup->DeleteEntry(path.Name()) )
860 return FALSE;
861
862 if ( bGroupIfEmptyAlso && m_pCurrentGroup->IsEmpty() ) {
863 if ( m_pCurrentGroup != m_pRootGroup ) {
864 ConfigGroup *pGroup = m_pCurrentGroup;
865 SetPath(wxT("..")); // changes m_pCurrentGroup!
866 m_pCurrentGroup->DeleteSubgroupByName(pGroup->Name());
867 }
868 //else: never delete the root group
869 }
870
871 return TRUE;
872 }
873
874 bool wxFileConfig::DeleteGroup(const wxString& key)
875 {
876 wxConfigPathChanger path(this, key);
877
878 return m_pCurrentGroup->DeleteSubgroupByName(path.Name());
879 }
880
881 bool wxFileConfig::DeleteAll()
882 {
883 CleanUp();
884
885 if ( remove(m_strLocalFile.fn_str()) == -1 )
886 wxLogSysError(_("can't delete user configuration file '%s'"), m_strLocalFile.c_str());
887
888 m_strLocalFile = m_strGlobalFile = wxT("");
889 Init();
890
891 return TRUE;
892 }
893
894 // ----------------------------------------------------------------------------
895 // linked list functions
896 // ----------------------------------------------------------------------------
897
898 // append a new line to the end of the list
899 LineList *wxFileConfig::LineListAppend(const wxString& str)
900 {
901 LineList *pLine = new LineList(str);
902
903 if ( m_linesTail == NULL ) {
904 // list is empty
905 m_linesHead = pLine;
906 }
907 else {
908 // adjust pointers
909 m_linesTail->SetNext(pLine);
910 pLine->SetPrev(m_linesTail);
911 }
912
913 m_linesTail = pLine;
914 return m_linesTail;
915 }
916
917 // insert a new line after the given one or in the very beginning if !pLine
918 LineList *wxFileConfig::LineListInsert(const wxString& str,
919 LineList *pLine)
920 {
921 if ( pLine == m_linesTail )
922 return LineListAppend(str);
923
924 LineList *pNewLine = new LineList(str);
925 if ( pLine == NULL ) {
926 // prepend to the list
927 pNewLine->SetNext(m_linesHead);
928 m_linesHead->SetPrev(pNewLine);
929 m_linesHead = pNewLine;
930 }
931 else {
932 // insert before pLine
933 LineList *pNext = pLine->Next();
934 pNewLine->SetNext(pNext);
935 pNewLine->SetPrev(pLine);
936 pNext->SetPrev(pNewLine);
937 pLine->SetNext(pNewLine);
938 }
939
940 return pNewLine;
941 }
942
943 void wxFileConfig::LineListRemove(LineList *pLine)
944 {
945 LineList *pPrev = pLine->Prev(),
946 *pNext = pLine->Next();
947
948 // first entry?
949 if ( pPrev == NULL )
950 m_linesHead = pNext;
951 else
952 pPrev->SetNext(pNext);
953
954 // last entry?
955 if ( pNext == NULL )
956 m_linesTail = pPrev;
957 else
958 pNext->SetPrev(pPrev);
959
960 delete pLine;
961 }
962
963 bool wxFileConfig::LineListIsEmpty()
964 {
965 return m_linesHead == NULL;
966 }
967
968 // ============================================================================
969 // wxFileConfig::ConfigGroup
970 // ============================================================================
971
972 // ----------------------------------------------------------------------------
973 // ctor/dtor
974 // ----------------------------------------------------------------------------
975
976 // ctor
977 ConfigGroup::ConfigGroup(ConfigGroup *pParent,
978 const wxString& strName,
979 wxFileConfig *pConfig)
980 : m_aEntries(CompareEntries),
981 m_aSubgroups(CompareGroups),
982 m_strName(strName)
983 {
984 m_pConfig = pConfig;
985 m_pParent = pParent;
986 m_bDirty = FALSE;
987 m_pLine = NULL;
988
989 m_pLastEntry = NULL;
990 m_pLastGroup = NULL;
991 }
992
993 // dtor deletes all children
994 ConfigGroup::~ConfigGroup()
995 {
996 // entries
997 size_t n, nCount = m_aEntries.Count();
998 for ( n = 0; n < nCount; n++ )
999 delete m_aEntries[n];
1000
1001 // subgroups
1002 nCount = m_aSubgroups.Count();
1003 for ( n = 0; n < nCount; n++ )
1004 delete m_aSubgroups[n];
1005 }
1006
1007 // ----------------------------------------------------------------------------
1008 // line
1009 // ----------------------------------------------------------------------------
1010
1011 void ConfigGroup::SetLine(LineList *pLine)
1012 {
1013 wxASSERT( m_pLine == NULL ); // shouldn't be called twice
1014
1015 m_pLine = pLine;
1016 }
1017
1018 /*
1019 This is a bit complicated, so let me explain it in details. All lines that
1020 were read from the local file (the only one we will ever modify) are stored
1021 in a (doubly) linked list. Our problem is to know at which position in this
1022 list should we insert the new entries/subgroups. To solve it we keep three
1023 variables for each group: m_pLine, m_pLastEntry and m_pLastGroup.
1024
1025 m_pLine points to the line containing "[group_name]"
1026 m_pLastEntry points to the last entry of this group in the local file.
1027 m_pLastGroup subgroup
1028
1029 Initially, they're NULL all three. When the group (an entry/subgroup) is read
1030 from the local file, the corresponding variable is set. However, if the group
1031 was read from the global file and then modified or created by the application
1032 these variables are still NULL and we need to create the corresponding lines.
1033 See the following functions (and comments preceding them) for the details of
1034 how we do it.
1035
1036 Also, when our last entry/group are deleted we need to find the new last
1037 element - the code in DeleteEntry/Subgroup does this by backtracking the list
1038 of lines until it either founds an entry/subgroup (and this is the new last
1039 element) or the m_pLine of the group, in which case there are no more entries
1040 (or subgroups) left and m_pLast<element> becomes NULL.
1041
1042 NB: This last problem could be avoided for entries if we added new entries
1043 immediately after m_pLine, but in this case the entries would appear
1044 backwards in the config file (OTOH, it's not that important) and as we
1045 would still need to do it for the subgroups the code wouldn't have been
1046 significantly less complicated.
1047 */
1048
1049 // Return the line which contains "[our name]". If we're still not in the list,
1050 // add our line to it immediately after the last line of our parent group if we
1051 // have it or in the very beginning if we're the root group.
1052 LineList *ConfigGroup::GetGroupLine()
1053 {
1054 if ( m_pLine == NULL ) {
1055 ConfigGroup *pParent = Parent();
1056
1057 // this group wasn't present in local config file, add it now
1058 if ( pParent != NULL ) {
1059 wxString strFullName;
1060 strFullName << wxT("[")
1061 // +1: no '/'
1062 << FilterOutEntryName(GetFullName().c_str() + 1)
1063 << wxT("]");
1064 m_pLine = m_pConfig->LineListInsert(strFullName,
1065 pParent->GetLastGroupLine());
1066 pParent->SetLastGroup(this); // we're surely after all the others
1067 }
1068 else {
1069 // we return NULL, so that LineListInsert() will insert us in the
1070 // very beginning
1071 }
1072 }
1073
1074 return m_pLine;
1075 }
1076
1077 // Return the last line belonging to the subgroups of this group (after which
1078 // we can add a new subgroup), if we don't have any subgroups or entries our
1079 // last line is the group line (m_pLine) itself.
1080 LineList *ConfigGroup::GetLastGroupLine()
1081 {
1082 // if we have any subgroups, our last line is the last line of the last
1083 // subgroup
1084 if ( m_pLastGroup != NULL ) {
1085 LineList *pLine = m_pLastGroup->GetLastGroupLine();
1086
1087 wxASSERT( pLine != NULL ); // last group must have !NULL associated line
1088 return pLine;
1089 }
1090
1091 // no subgroups, so the last line is the line of thelast entry (if any)
1092 return GetLastEntryLine();
1093 }
1094
1095 // return the last line belonging to the entries of this group (after which
1096 // we can add a new entry), if we don't have any entries we will add the new
1097 // one immediately after the group line itself.
1098 LineList *ConfigGroup::GetLastEntryLine()
1099 {
1100 if ( m_pLastEntry != NULL ) {
1101 LineList *pLine = m_pLastEntry->GetLine();
1102
1103 wxASSERT( pLine != NULL ); // last entry must have !NULL associated line
1104 return pLine;
1105 }
1106
1107 // no entries: insert after the group header
1108 return GetGroupLine();
1109 }
1110
1111 // ----------------------------------------------------------------------------
1112 // group name
1113 // ----------------------------------------------------------------------------
1114
1115 void ConfigGroup::Rename(const wxString& newName)
1116 {
1117 m_strName = newName;
1118
1119 LineList *line = GetGroupLine();
1120 wxString strFullName;
1121 strFullName << wxT("[") << (GetFullName().c_str() + 1) << wxT("]"); // +1: no '/'
1122 line->SetText(strFullName);
1123
1124 SetDirty();
1125 }
1126
1127 wxString ConfigGroup::GetFullName() const
1128 {
1129 if ( Parent() )
1130 return Parent()->GetFullName() + wxCONFIG_PATH_SEPARATOR + Name();
1131 else
1132 return wxT("");
1133 }
1134
1135 // ----------------------------------------------------------------------------
1136 // find an item
1137 // ----------------------------------------------------------------------------
1138
1139 // use binary search because the array is sorted
1140 ConfigEntry *
1141 ConfigGroup::FindEntry(const wxChar *szName) const
1142 {
1143 size_t i,
1144 lo = 0,
1145 hi = m_aEntries.Count();
1146 int res;
1147 ConfigEntry *pEntry;
1148
1149 while ( lo < hi ) {
1150 i = (lo + hi)/2;
1151 pEntry = m_aEntries[i];
1152
1153 #if wxCONFIG_CASE_SENSITIVE
1154 res = wxStrcmp(pEntry->Name(), szName);
1155 #else
1156 res = wxStricmp(pEntry->Name(), szName);
1157 #endif
1158
1159 if ( res > 0 )
1160 hi = i;
1161 else if ( res < 0 )
1162 lo = i + 1;
1163 else
1164 return pEntry;
1165 }
1166
1167 return NULL;
1168 }
1169
1170 ConfigGroup *
1171 ConfigGroup::FindSubgroup(const wxChar *szName) const
1172 {
1173 size_t i,
1174 lo = 0,
1175 hi = m_aSubgroups.Count();
1176 int res;
1177 ConfigGroup *pGroup;
1178
1179 while ( lo < hi ) {
1180 i = (lo + hi)/2;
1181 pGroup = m_aSubgroups[i];
1182
1183 #if wxCONFIG_CASE_SENSITIVE
1184 res = wxStrcmp(pGroup->Name(), szName);
1185 #else
1186 res = wxStricmp(pGroup->Name(), szName);
1187 #endif
1188
1189 if ( res > 0 )
1190 hi = i;
1191 else if ( res < 0 )
1192 lo = i + 1;
1193 else
1194 return pGroup;
1195 }
1196
1197 return NULL;
1198 }
1199
1200 // ----------------------------------------------------------------------------
1201 // create a new item
1202 // ----------------------------------------------------------------------------
1203
1204 // create a new entry and add it to the current group
1205 ConfigEntry *
1206 ConfigGroup::AddEntry(const wxString& strName, int nLine)
1207 {
1208 wxASSERT( FindEntry(strName) == NULL );
1209
1210 ConfigEntry *pEntry = new ConfigEntry(this, strName, nLine);
1211 m_aEntries.Add(pEntry);
1212
1213 return pEntry;
1214 }
1215
1216 // create a new group and add it to the current group
1217 ConfigGroup *
1218 ConfigGroup::AddSubgroup(const wxString& strName)
1219 {
1220 wxASSERT( FindSubgroup(strName) == NULL );
1221
1222 ConfigGroup *pGroup = new ConfigGroup(this, strName, m_pConfig);
1223 m_aSubgroups.Add(pGroup);
1224
1225 return pGroup;
1226 }
1227
1228 // ----------------------------------------------------------------------------
1229 // delete an item
1230 // ----------------------------------------------------------------------------
1231
1232 /*
1233 The delete operations are _very_ slow if we delete the last item of this
1234 group (see comments before GetXXXLineXXX functions for more details),
1235 so it's much better to start with the first entry/group if we want to
1236 delete several of them.
1237 */
1238
1239 bool ConfigGroup::DeleteSubgroupByName(const wxChar *szName)
1240 {
1241 return DeleteSubgroup(FindSubgroup(szName));
1242 }
1243
1244 // doesn't delete the subgroup itself, but does remove references to it from
1245 // all other data structures (and normally the returned pointer should be
1246 // deleted a.s.a.p. because there is nothing much to be done with it anyhow)
1247 bool ConfigGroup::DeleteSubgroup(ConfigGroup *pGroup)
1248 {
1249 wxCHECK( pGroup != NULL, FALSE ); // deleting non existing group?
1250
1251 // delete all entries
1252 size_t nCount = pGroup->m_aEntries.Count();
1253 for ( size_t nEntry = 0; nEntry < nCount; nEntry++ ) {
1254 LineList *pLine = pGroup->m_aEntries[nEntry]->GetLine();
1255 if ( pLine != NULL )
1256 m_pConfig->LineListRemove(pLine);
1257 }
1258
1259 // and subgroups of this sungroup
1260 nCount = pGroup->m_aSubgroups.Count();
1261 for ( size_t nGroup = 0; nGroup < nCount; nGroup++ ) {
1262 pGroup->DeleteSubgroup(pGroup->m_aSubgroups[0]);
1263 }
1264
1265 LineList *pLine = pGroup->m_pLine;
1266 if ( pLine != NULL ) {
1267 // notice that we may do this test inside the previous "if" because the
1268 // last entry's line is surely !NULL
1269 if ( pGroup == m_pLastGroup ) {
1270 // our last entry is being deleted - find the last one which stays
1271 wxASSERT( m_pLine != NULL ); // we have a subgroup with !NULL pLine...
1272
1273 // go back until we find a subgroup or reach the group's line
1274 ConfigGroup *pNewLast = NULL;
1275 size_t n, nSubgroups = m_aSubgroups.Count();
1276 LineList *pl;
1277 for ( pl = pLine->Prev(); pl != m_pLine; pl = pl->Prev() ) {
1278 // is it our subgroup?
1279 for ( n = 0; (pNewLast == NULL) && (n < nSubgroups); n++ ) {
1280 // do _not_ call GetGroupLine! we don't want to add it to the local
1281 // file if it's not already there
1282 if ( m_aSubgroups[n]->m_pLine == m_pLine )
1283 pNewLast = m_aSubgroups[n];
1284 }
1285
1286 if ( pNewLast != NULL ) // found?
1287 break;
1288 }
1289
1290 if ( pl == m_pLine ) {
1291 wxASSERT( !pNewLast ); // how comes it has the same line as we?
1292
1293 // we've reached the group line without finding any subgroups
1294 m_pLastGroup = NULL;
1295 }
1296 else
1297 m_pLastGroup = pNewLast;
1298 }
1299
1300 m_pConfig->LineListRemove(pLine);
1301 }
1302
1303 SetDirty();
1304
1305 m_aSubgroups.Remove(pGroup);
1306 delete pGroup;
1307
1308 return TRUE;
1309 }
1310
1311 bool ConfigGroup::DeleteEntry(const wxChar *szName)
1312 {
1313 ConfigEntry *pEntry = FindEntry(szName);
1314 wxCHECK( pEntry != NULL, FALSE ); // deleting non existing item?
1315
1316 LineList *pLine = pEntry->GetLine();
1317 if ( pLine != NULL ) {
1318 // notice that we may do this test inside the previous "if" because the
1319 // last entry's line is surely !NULL
1320 if ( pEntry == m_pLastEntry ) {
1321 // our last entry is being deleted - find the last one which stays
1322 wxASSERT( m_pLine != NULL ); // if we have an entry with !NULL pLine...
1323
1324 // go back until we find another entry or reach the group's line
1325 ConfigEntry *pNewLast = NULL;
1326 size_t n, nEntries = m_aEntries.Count();
1327 LineList *pl;
1328 for ( pl = pLine->Prev(); pl != m_pLine; pl = pl->Prev() ) {
1329 // is it our subgroup?
1330 for ( n = 0; (pNewLast == NULL) && (n < nEntries); n++ ) {
1331 if ( m_aEntries[n]->GetLine() == m_pLine )
1332 pNewLast = m_aEntries[n];
1333 }
1334
1335 if ( pNewLast != NULL ) // found?
1336 break;
1337 }
1338
1339 if ( pl == m_pLine ) {
1340 wxASSERT( !pNewLast ); // how comes it has the same line as we?
1341
1342 // we've reached the group line without finding any subgroups
1343 m_pLastEntry = NULL;
1344 }
1345 else
1346 m_pLastEntry = pNewLast;
1347 }
1348
1349 m_pConfig->LineListRemove(pLine);
1350 }
1351
1352 // we must be written back for the changes to be saved
1353 SetDirty();
1354
1355 m_aEntries.Remove(pEntry);
1356 delete pEntry;
1357
1358 return TRUE;
1359 }
1360
1361 // ----------------------------------------------------------------------------
1362 //
1363 // ----------------------------------------------------------------------------
1364 void ConfigGroup::SetDirty()
1365 {
1366 m_bDirty = TRUE;
1367 if ( Parent() != NULL ) // propagate upwards
1368 Parent()->SetDirty();
1369 }
1370
1371 // ============================================================================
1372 // wxFileConfig::ConfigEntry
1373 // ============================================================================
1374
1375 // ----------------------------------------------------------------------------
1376 // ctor
1377 // ----------------------------------------------------------------------------
1378 ConfigEntry::ConfigEntry(ConfigGroup *pParent,
1379 const wxString& strName,
1380 int nLine)
1381 : m_strName(strName)
1382 {
1383 wxASSERT( !strName.IsEmpty() );
1384
1385 m_pParent = pParent;
1386 m_nLine = nLine;
1387 m_pLine = NULL;
1388
1389 m_bDirty = FALSE;
1390
1391 m_bImmutable = strName[0] == wxCONFIG_IMMUTABLE_PREFIX;
1392 if ( m_bImmutable )
1393 m_strName.erase(0, 1); // remove first character
1394 }
1395
1396 // ----------------------------------------------------------------------------
1397 // set value
1398 // ----------------------------------------------------------------------------
1399
1400 void ConfigEntry::SetLine(LineList *pLine)
1401 {
1402 if ( m_pLine != NULL ) {
1403 wxLogWarning(_("entry '%s' appears more than once in group '%s'"),
1404 Name().c_str(), m_pParent->GetFullName().c_str());
1405 }
1406
1407 m_pLine = pLine;
1408 Group()->SetLastEntry(this);
1409 }
1410
1411 // second parameter is FALSE if we read the value from file and prevents the
1412 // entry from being marked as 'dirty'
1413 void ConfigEntry::SetValue(const wxString& strValue, bool bUser)
1414 {
1415 if ( bUser && IsImmutable() ) {
1416 wxLogWarning(_("attempt to change immutable key '%s' ignored."),
1417 Name().c_str());
1418 return;
1419 }
1420
1421 // do nothing if it's the same value
1422 if ( strValue == m_strValue )
1423 return;
1424
1425 m_strValue = strValue;
1426
1427 if ( bUser ) {
1428 wxString strVal = FilterOutValue(strValue);
1429 wxString strLine;
1430 strLine << FilterOutEntryName(m_strName) << wxT('=') << strVal;
1431
1432 if ( m_pLine != NULL ) {
1433 // entry was read from the local config file, just modify the line
1434 m_pLine->SetText(strLine);
1435 }
1436 else {
1437 // add a new line to the file
1438 wxASSERT( m_nLine == wxNOT_FOUND ); // consistency check
1439
1440 m_pLine = Group()->Config()->LineListInsert(strLine,
1441 Group()->GetLastEntryLine());
1442 Group()->SetLastEntry(this);
1443 }
1444
1445 SetDirty();
1446 }
1447 }
1448
1449 void ConfigEntry::SetDirty()
1450 {
1451 m_bDirty = TRUE;
1452 Group()->SetDirty();
1453 }
1454
1455 // ============================================================================
1456 // global functions
1457 // ============================================================================
1458
1459 // ----------------------------------------------------------------------------
1460 // compare functions for array sorting
1461 // ----------------------------------------------------------------------------
1462
1463 int CompareEntries(ConfigEntry *p1,
1464 ConfigEntry *p2)
1465 {
1466 #if wxCONFIG_CASE_SENSITIVE
1467 return wxStrcmp(p1->Name(), p2->Name());
1468 #else
1469 return wxStricmp(p1->Name(), p2->Name());
1470 #endif
1471 }
1472
1473 int CompareGroups(ConfigGroup *p1,
1474 ConfigGroup *p2)
1475 {
1476 #if wxCONFIG_CASE_SENSITIVE
1477 return wxStrcmp(p1->Name(), p2->Name());
1478 #else
1479 return wxStricmp(p1->Name(), p2->Name());
1480 #endif
1481 }
1482
1483 // ----------------------------------------------------------------------------
1484 // filter functions
1485 // ----------------------------------------------------------------------------
1486
1487 // undo FilterOutValue
1488 static wxString FilterInValue(const wxString& str)
1489 {
1490 wxString strResult;
1491 strResult.Alloc(str.Len());
1492
1493 bool bQuoted = !str.IsEmpty() && str[0] == '"';
1494
1495 for ( size_t n = bQuoted ? 1 : 0; n < str.Len(); n++ ) {
1496 if ( str[n] == wxT('\\') ) {
1497 switch ( str[++n] ) {
1498 case wxT('n'):
1499 strResult += wxT('\n');
1500 break;
1501
1502 case wxT('r'):
1503 strResult += wxT('\r');
1504 break;
1505
1506 case wxT('t'):
1507 strResult += wxT('\t');
1508 break;
1509
1510 case wxT('\\'):
1511 strResult += wxT('\\');
1512 break;
1513
1514 case wxT('"'):
1515 strResult += wxT('"');
1516 break;
1517 }
1518 }
1519 else {
1520 if ( str[n] != wxT('"') || !bQuoted )
1521 strResult += str[n];
1522 else if ( n != str.Len() - 1 ) {
1523 wxLogWarning(_("unexpected \" at position %d in '%s'."),
1524 n, str.c_str());
1525 }
1526 //else: it's the last quote of a quoted string, ok
1527 }
1528 }
1529
1530 return strResult;
1531 }
1532
1533 // quote the string before writing it to file
1534 static wxString FilterOutValue(const wxString& str)
1535 {
1536 if ( !str )
1537 return str;
1538
1539 wxString strResult;
1540 strResult.Alloc(str.Len());
1541
1542 // quoting is necessary to preserve spaces in the beginning of the string
1543 bool bQuote = wxIsspace(str[0]) || str[0] == wxT('"');
1544
1545 if ( bQuote )
1546 strResult += wxT('"');
1547
1548 wxChar c;
1549 for ( size_t n = 0; n < str.Len(); n++ ) {
1550 switch ( str[n] ) {
1551 case wxT('\n'):
1552 c = wxT('n');
1553 break;
1554
1555 case wxT('\r'):
1556 c = wxT('r');
1557 break;
1558
1559 case wxT('\t'):
1560 c = wxT('t');
1561 break;
1562
1563 case wxT('\\'):
1564 c = wxT('\\');
1565 break;
1566
1567 case wxT('"'):
1568 if ( bQuote ) {
1569 c = wxT('"');
1570 break;
1571 }
1572 //else: fall through
1573
1574 default:
1575 strResult += str[n];
1576 continue; // nothing special to do
1577 }
1578
1579 // we get here only for special characters
1580 strResult << wxT('\\') << c;
1581 }
1582
1583 if ( bQuote )
1584 strResult += wxT('"');
1585
1586 return strResult;
1587 }
1588
1589 // undo FilterOutEntryName
1590 static wxString FilterInEntryName(const wxString& str)
1591 {
1592 wxString strResult;
1593 strResult.Alloc(str.Len());
1594
1595 for ( const wxChar *pc = str.c_str(); *pc != '\0'; pc++ ) {
1596 if ( *pc == wxT('\\') )
1597 pc++;
1598
1599 strResult += *pc;
1600 }
1601
1602 return strResult;
1603 }
1604
1605 // sanitize entry or group name: insert '\\' before any special characters
1606 static wxString FilterOutEntryName(const wxString& str)
1607 {
1608 wxString strResult;
1609 strResult.Alloc(str.Len());
1610
1611 for ( const wxChar *pc = str.c_str(); *pc != wxT('\0'); pc++ ) {
1612 wxChar c = *pc;
1613
1614 // we explicitly allow some of "safe" chars and 8bit ASCII characters
1615 // which will probably never have special meaning
1616 // NB: note that wxCONFIG_IMMUTABLE_PREFIX and wxCONFIG_PATH_SEPARATOR
1617 // should *not* be quoted
1618 if ( !wxIsalnum(c) && !wxStrchr(wxT("@_/-!.*%"), c) && ((c & 0x80) == 0) )
1619 strResult += wxT('\\');
1620
1621 strResult += c;
1622 }
1623
1624 return strResult;
1625 }
1626
1627 // we can't put ?: in the ctor initializer list because it confuses some
1628 // broken compilers (Borland C++)
1629 static wxString GetAppName(const wxString& appName)
1630 {
1631 if ( !appName && wxTheApp )
1632 return wxTheApp->GetAppName();
1633 else
1634 return appName;
1635 }
1636
1637 #endif // wxUSE_CONFIG
1638