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