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