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