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