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