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