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