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