]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/config.cpp
Corrected IMPLEMENT_CLASS/BEGIN_EVENT_TABLE base class
[wxWidgets.git] / src / common / config.cpp
... / ...
CommitLineData
1///////////////////////////////////////////////////////////////////////////////
2// Name: src/common/config.cpp
3// Purpose: implementation of wxConfigBase class
4// Author: Vadim Zeitlin
5// Modified by:
6// Created: 07.04.98
7// RCS-ID: $Id$
8// Copyright: (c) 1997 Karsten Ballueder Ballueder@usa.net
9// Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
10// Licence: wxWindows licence
11///////////////////////////////////////////////////////////////////////////////
12
13// ----------------------------------------------------------------------------
14// headers
15// ----------------------------------------------------------------------------
16
17#include "wx/wxprec.h"
18
19#ifdef __BORLANDC__
20 #pragma hdrstop
21#endif //__BORLANDC__
22
23#ifndef wxUSE_CONFIG_NATIVE
24 #define wxUSE_CONFIG_NATIVE 1
25#endif
26
27#include "wx/config.h"
28
29#ifndef WX_PRECOMP
30 #include "wx/intl.h"
31 #include "wx/log.h"
32 #include "wx/app.h"
33 #include "wx/utils.h"
34 #include "wx/arrstr.h"
35 #include "wx/math.h"
36#endif //WX_PRECOMP
37
38#if wxUSE_CONFIG && ((wxUSE_FILE && wxUSE_TEXTFILE) || wxUSE_CONFIG_NATIVE)
39
40#include "wx/apptrait.h"
41#include "wx/file.h"
42
43#include <stdlib.h>
44#include <ctype.h>
45#include <limits.h> // for INT_MAX
46
47// ----------------------------------------------------------------------------
48// global and class static variables
49// ----------------------------------------------------------------------------
50
51wxConfigBase *wxConfigBase::ms_pConfig = NULL;
52bool wxConfigBase::ms_bAutoCreate = true;
53
54// ============================================================================
55// implementation
56// ============================================================================
57
58// ----------------------------------------------------------------------------
59// wxAppTraitsBase
60// ----------------------------------------------------------------------------
61
62wxConfigBase *wxAppTraitsBase::CreateConfig()
63{
64 return new
65 #if defined(__WXMSW__) && wxUSE_CONFIG_NATIVE
66 wxRegConfig(wxTheApp->GetAppName(), wxTheApp->GetVendorName());
67 #elif defined(__WXPALMOS__) && wxUSE_CONFIG_NATIVE
68 wxPrefConfig(wxTheApp->GetAppName());
69 #else // either we're under Unix or wish to use files even under Windows
70 wxFileConfig(wxTheApp->GetAppName());
71 #endif
72}
73
74// ----------------------------------------------------------------------------
75// wxConfigBase
76// ----------------------------------------------------------------------------
77IMPLEMENT_ABSTRACT_CLASS(wxConfigBase, wxObject)
78
79// Not all args will always be used by derived classes, but including them all
80// in each class ensures compatibility.
81wxConfigBase::wxConfigBase(const wxString& appName,
82 const wxString& vendorName,
83 const wxString& WXUNUSED(localFilename),
84 const wxString& WXUNUSED(globalFilename),
85 long style)
86 : m_appName(appName), m_vendorName(vendorName), m_style(style)
87{
88 m_bExpandEnvVars = true;
89 m_bRecordDefaults = false;
90}
91
92wxConfigBase::~wxConfigBase()
93{
94 // required here for Darwin
95}
96
97wxConfigBase *wxConfigBase::Set(wxConfigBase *pConfig)
98{
99 wxConfigBase *pOld = ms_pConfig;
100 ms_pConfig = pConfig;
101 return pOld;
102}
103
104wxConfigBase *wxConfigBase::Create()
105{
106 if ( ms_bAutoCreate && ms_pConfig == NULL ) {
107 wxAppTraits * const traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
108 wxCHECK_MSG( traits, NULL, _T("create wxApp before calling this") );
109
110 ms_pConfig = traits->CreateConfig();
111 }
112
113 return ms_pConfig;
114}
115
116// ----------------------------------------------------------------------------
117// wxConfigBase reading entries
118// ----------------------------------------------------------------------------
119
120// implement both Read() overloads for the given type in terms of DoRead()
121#define IMPLEMENT_READ_FOR_TYPE(name, type, deftype, extra) \
122 bool wxConfigBase::Read(const wxString& key, type *val) const \
123 { \
124 wxCHECK_MSG( val, false, _T("wxConfig::Read(): NULL parameter") ); \
125 \
126 if ( !DoRead##name(key, val) ) \
127 return false; \
128 \
129 *val = extra(*val); \
130 \
131 return true; \
132 } \
133 \
134 bool wxConfigBase::Read(const wxString& key, \
135 type *val, \
136 deftype defVal) const \
137 { \
138 wxCHECK_MSG( val, false, _T("wxConfig::Read(): NULL parameter") ); \
139 \
140 bool read = DoRead##name(key, val); \
141 if ( !read ) \
142 { \
143 if ( IsRecordingDefaults() ) \
144 { \
145 ((wxConfigBase *)this)->DoWrite##name(key, defVal); \
146 } \
147 \
148 *val = defVal; \
149 } \
150 \
151 *val = extra(*val); \
152 \
153 return read; \
154 }
155
156
157IMPLEMENT_READ_FOR_TYPE(String, wxString, const wxString&, ExpandEnvVars)
158IMPLEMENT_READ_FOR_TYPE(Long, long, long, long)
159IMPLEMENT_READ_FOR_TYPE(Double, double, double, double)
160IMPLEMENT_READ_FOR_TYPE(Bool, bool, bool, bool)
161
162#undef IMPLEMENT_READ_FOR_TYPE
163
164// int is stored as long
165bool wxConfigBase::Read(const wxString& key, int *pi) const
166{
167 long l = *pi;
168 bool r = Read(key, &l);
169 wxASSERT_MSG( l < INT_MAX, _T("int overflow in wxConfig::Read") );
170 *pi = (int)l;
171 return r;
172}
173
174bool wxConfigBase::Read(const wxString& key, int *pi, int defVal) const
175{
176 long l = *pi;
177 bool r = Read(key, &l, defVal);
178 wxASSERT_MSG( l < INT_MAX, _T("int overflow in wxConfig::Read") );
179 *pi = (int)l;
180 return r;
181}
182
183// the DoReadXXX() for the other types have implementation in the base class
184// but can be overridden in the derived ones
185bool wxConfigBase::DoReadBool(const wxString& key, bool* val) const
186{
187 wxCHECK_MSG( val, false, _T("wxConfig::Read(): NULL parameter") );
188
189 long l;
190 if ( !DoReadLong(key, &l) )
191 return false;
192
193 wxASSERT_MSG( l == 0 || l == 1, _T("bad bool value in wxConfig::DoReadInt") );
194
195 *val = l != 0;
196
197 return true;
198}
199
200bool wxConfigBase::DoReadDouble(const wxString& key, double* val) const
201{
202 wxString str;
203 if ( Read(key, &str) )
204 {
205 return str.ToDouble(val);
206 }
207
208 return false;
209}
210
211// string reading helper
212wxString wxConfigBase::ExpandEnvVars(const wxString& str) const
213{
214 wxString tmp; // Required for BC++
215 if (IsExpandingEnvVars())
216 tmp = wxExpandEnvVars(str);
217 else
218 tmp = str;
219 return tmp;
220}
221
222// ----------------------------------------------------------------------------
223// wxConfigBase writing
224// ----------------------------------------------------------------------------
225
226bool wxConfigBase::DoWriteDouble(const wxString& key, double val)
227{
228 return DoWriteString(key, wxString::Format(_T("%g"), val));
229}
230
231bool wxConfigBase::DoWriteBool(const wxString& key, bool value)
232{
233 return DoWriteLong(key, value ? 1l : 0l);
234}
235
236// ----------------------------------------------------------------------------
237// wxConfigPathChanger
238// ----------------------------------------------------------------------------
239
240wxConfigPathChanger::wxConfigPathChanger(const wxConfigBase *pContainer,
241 const wxString& strEntry)
242{
243 m_bChanged = false;
244 m_pContainer = (wxConfigBase *)pContainer;
245
246 // the path is everything which precedes the last slash
247 wxString strPath = strEntry.BeforeLast(wxCONFIG_PATH_SEPARATOR);
248
249 // except in the special case of "/keyname" when there is nothing before "/"
250 if ( strPath.empty() &&
251 ((!strEntry.empty()) && strEntry[0] == wxCONFIG_PATH_SEPARATOR) )
252 {
253 strPath = wxCONFIG_PATH_SEPARATOR;
254 }
255
256 if ( !strPath.empty() )
257 {
258 if ( m_pContainer->GetPath() != strPath )
259 {
260 // we do change the path so restore it later
261 m_bChanged = true;
262
263 /* JACS: work around a memory bug that causes an assert
264 when using wxRegConfig, related to reference-counting.
265 Can be reproduced by removing .wc_str() below and
266 adding the following code to the config sample OnInit under
267 Windows:
268
269 pConfig->SetPath(wxT("MySettings"));
270 pConfig->SetPath(wxT(".."));
271 int value;
272 pConfig->Read(_T("MainWindowX"), & value);
273 */
274 m_strOldPath = m_pContainer->GetPath().wc_str();
275 if ( *m_strOldPath.c_str() != wxCONFIG_PATH_SEPARATOR )
276 m_strOldPath += wxCONFIG_PATH_SEPARATOR;
277 m_pContainer->SetPath(strPath);
278 }
279
280 // in any case, use the just the name, not full path
281 m_strName = strEntry.AfterLast(wxCONFIG_PATH_SEPARATOR);
282 }
283 else {
284 // it's a name only, without path - nothing to do
285 m_strName = strEntry;
286 }
287}
288
289void wxConfigPathChanger::UpdateIfDeleted()
290{
291 // we don't have to do anything at all if we didn't change the path
292 if ( !m_bChanged )
293 return;
294
295 // find the deepest still existing parent path of the original path
296 while ( !m_pContainer->HasGroup(m_strOldPath) )
297 {
298 m_strOldPath = m_strOldPath.BeforeLast(wxCONFIG_PATH_SEPARATOR);
299 if ( m_strOldPath.empty() )
300 m_strOldPath = wxCONFIG_PATH_SEPARATOR;
301 }
302}
303
304wxConfigPathChanger::~wxConfigPathChanger()
305{
306 // only restore path if it was changed
307 if ( m_bChanged ) {
308 m_pContainer->SetPath(m_strOldPath);
309 }
310}
311
312// this is a wxConfig method but it's mainly used with wxConfigPathChanger
313/* static */
314wxString wxConfigBase::RemoveTrailingSeparator(const wxString& key)
315{
316 wxString path(key);
317
318 // don't remove the only separator from a root group path!
319 while ( path.length() > 1 )
320 {
321 if ( *path.rbegin() != wxCONFIG_PATH_SEPARATOR )
322 break;
323
324 path.erase(path.end() - 1);
325 }
326
327 return path;
328}
329
330#endif // wxUSE_CONFIG
331
332// ----------------------------------------------------------------------------
333// static & global functions
334// ----------------------------------------------------------------------------
335
336// understands both Unix and Windows (but only under Windows) environment
337// variables expansion: i.e. $var, $(var) and ${var} are always understood
338// and in addition under Windows %var% is also.
339
340// don't change the values the enum elements: they must be equal
341// to the matching [closing] delimiter.
342enum Bracket
343{
344 Bracket_None,
345 Bracket_Normal = ')',
346 Bracket_Curly = '}',
347#ifdef __WXMSW__
348 Bracket_Windows = '%', // yeah, Windows people are a bit strange ;-)
349#endif
350 Bracket_Max
351};
352
353wxString wxExpandEnvVars(const wxString& str)
354{
355 wxString strResult;
356 strResult.Alloc(str.length());
357
358 size_t m;
359 for ( size_t n = 0; n < str.length(); n++ ) {
360 switch ( str[n].GetValue() ) {
361#ifdef __WXMSW__
362 case wxT('%'):
363#endif //WINDOWS
364 case wxT('$'):
365 {
366 Bracket bracket;
367 #ifdef __WXMSW__
368 if ( str[n] == wxT('%') )
369 bracket = Bracket_Windows;
370 else
371 #endif //WINDOWS
372 if ( n == str.length() - 1 ) {
373 bracket = Bracket_None;
374 }
375 else {
376 switch ( str[n + 1].GetValue() ) {
377 case wxT('('):
378 bracket = Bracket_Normal;
379 n++; // skip the bracket
380 break;
381
382 case wxT('{'):
383 bracket = Bracket_Curly;
384 n++; // skip the bracket
385 break;
386
387 default:
388 bracket = Bracket_None;
389 }
390 }
391
392 m = n + 1;
393
394 while ( m < str.length() && (wxIsalnum(str[m]) || str[m] == wxT('_')) )
395 m++;
396
397 wxString strVarName(str.c_str() + n + 1, m - n - 1);
398
399#ifdef __WXWINCE__
400 const bool expanded = false;
401#else
402 // NB: use wxGetEnv instead of wxGetenv as otherwise variables
403 // set through wxSetEnv may not be read correctly!
404 bool expanded = false;
405 wxString tmp;
406 if (wxGetEnv(strVarName, &tmp))
407 {
408 strResult += tmp;
409 expanded = true;
410 }
411 else
412#endif
413 {
414 // variable doesn't exist => don't change anything
415 #ifdef __WXMSW__
416 if ( bracket != Bracket_Windows )
417 #endif
418 if ( bracket != Bracket_None )
419 strResult << str[n - 1];
420 strResult << str[n] << strVarName;
421 }
422
423 // check the closing bracket
424 if ( bracket != Bracket_None ) {
425 if ( m == str.length() || str[m] != (wxChar)bracket ) {
426 // under MSW it's common to have '%' characters in the registry
427 // and it's annoying to have warnings about them each time, so
428 // ignroe them silently if they are not used for env vars
429 //
430 // under Unix, OTOH, this warning could be useful for the user to
431 // understand why isn't the variable expanded as intended
432 #ifndef __WXMSW__
433 wxLogWarning(_("Environment variables expansion failed: missing '%c' at position %u in '%s'."),
434 (char)bracket, (unsigned int) (m + 1), str.c_str());
435 #endif // __WXMSW__
436 }
437 else {
438 // skip closing bracket unless the variables wasn't expanded
439 if ( !expanded )
440 strResult << (wxChar)bracket;
441 m++;
442 }
443 }
444
445 n = m - 1; // skip variable name
446 }
447 break;
448
449 case wxT('\\'):
450 // backslash can be used to suppress special meaning of % and $
451 if ( n != str.length() - 1 &&
452 (str[n + 1] == wxT('%') || str[n + 1] == wxT('$')) ) {
453 strResult += str[++n];
454
455 break;
456 }
457 //else: fall through
458
459 default:
460 strResult += str[n];
461 }
462 }
463
464 return strResult;
465}
466
467// this function is used to properly interpret '..' in path
468void wxSplitPath(wxArrayString& aParts, const wxString& path)
469{
470 aParts.clear();
471
472 wxString strCurrent;
473 wxString::const_iterator pc = path.begin();
474 for ( ;; ) {
475 if ( pc == path.end() || *pc == wxCONFIG_PATH_SEPARATOR ) {
476 if ( strCurrent == wxT(".") ) {
477 // ignore
478 }
479 else if ( strCurrent == wxT("..") ) {
480 // go up one level
481 if ( aParts.size() == 0 )
482 wxLogWarning(_("'%s' has extra '..', ignored."), path);
483 else
484 aParts.erase(aParts.end() - 1);
485
486 strCurrent.Empty();
487 }
488 else if ( !strCurrent.empty() ) {
489 aParts.push_back(strCurrent);
490 strCurrent.Empty();
491 }
492 //else:
493 // could log an error here, but we prefer to ignore extra '/'
494
495 if ( pc == path.end() )
496 break;
497 }
498 else
499 strCurrent += *pc;
500
501 ++pc;
502 }
503}