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