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