]> git.saurik.com Git - wxWidgets.git/blob - src/common/config.cpp
changed wxFFileOutput/InputStream ctor 'mode' argument to wxString
[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 // 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
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
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(__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 // ----------------------------------------------------------------------------
77 IMPLEMENT_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.
81 wxConfigBase::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
92 wxConfigBase::~wxConfigBase()
93 {
94 // required here for Darwin
95 }
96
97 wxConfigBase *wxConfigBase::Set(wxConfigBase *pConfig)
98 {
99 wxConfigBase *pOld = ms_pConfig;
100 ms_pConfig = pConfig;
101 return pOld;
102 }
103
104 wxConfigBase *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
157 IMPLEMENT_READ_FOR_TYPE(String, wxString, const wxString&, ExpandEnvVars)
158 IMPLEMENT_READ_FOR_TYPE(Long, long, long, long)
159 IMPLEMENT_READ_FOR_TYPE(Int, int, int, int)
160 IMPLEMENT_READ_FOR_TYPE(Double, double, double, double)
161 IMPLEMENT_READ_FOR_TYPE(Bool, bool, bool, bool)
162
163 #undef IMPLEMENT_READ_FOR_TYPE
164
165 // the DoReadXXX() for the other types have implementation in the base class
166 // but can be overridden in the derived ones
167 bool wxConfigBase::DoReadInt(const wxString& key, int *pi) const
168 {
169 wxCHECK_MSG( pi, false, _T("wxConfig::Read(): NULL parameter") );
170
171 long l;
172 if ( !DoReadLong(key, &l) )
173 return false;
174
175 wxASSERT_MSG( l < INT_MAX, _T("overflow in wxConfig::DoReadInt") );
176
177 *pi = (int)l;
178
179 return true;
180 }
181
182 bool wxConfigBase::DoReadBool(const wxString& key, bool* val) const
183 {
184 wxCHECK_MSG( val, false, _T("wxConfig::Read(): NULL parameter") );
185
186 long l;
187 if ( !DoReadLong(key, &l) )
188 return false;
189
190 wxASSERT_MSG( l == 0 || l == 1, _T("bad bool value in wxConfig::DoReadInt") );
191
192 *val = l != 0;
193
194 return true;
195 }
196
197 bool wxConfigBase::DoReadDouble(const wxString& key, double* val) const
198 {
199 wxString str;
200 if ( Read(key, &str) )
201 {
202 return str.ToDouble(val);
203 }
204
205 return false;
206 }
207
208 // string reading helper
209 wxString wxConfigBase::ExpandEnvVars(const wxString& str) const
210 {
211 wxString tmp; // Required for BC++
212 if (IsExpandingEnvVars())
213 tmp = wxExpandEnvVars(str);
214 else
215 tmp = str;
216 return tmp;
217 }
218
219 // ----------------------------------------------------------------------------
220 // wxConfigBase writing
221 // ----------------------------------------------------------------------------
222
223 bool wxConfigBase::DoWriteDouble(const wxString& key, double val)
224 {
225 return DoWriteString(key, wxString::Format(_T("%g"), val));
226 }
227
228 bool wxConfigBase::DoWriteInt(const wxString& key, int value)
229 {
230 return DoWriteLong(key, (long)value);
231 }
232
233 bool wxConfigBase::DoWriteBool(const wxString& key, bool value)
234 {
235 return DoWriteLong(key, value ? 1l : 0l);
236 }
237
238 // ----------------------------------------------------------------------------
239 // wxConfigPathChanger
240 // ----------------------------------------------------------------------------
241
242 wxConfigPathChanger::wxConfigPathChanger(const wxConfigBase *pContainer,
243 const wxString& strEntry)
244 {
245 m_bChanged = false;
246 m_pContainer = (wxConfigBase *)pContainer;
247
248 // the path is everything which precedes the last slash
249 wxString strPath = strEntry.BeforeLast(wxCONFIG_PATH_SEPARATOR);
250
251 // except in the special case of "/keyname" when there is nothing before "/"
252 if ( strPath.empty() &&
253 ((!strEntry.empty()) && strEntry[0] == wxCONFIG_PATH_SEPARATOR) )
254 {
255 strPath = wxCONFIG_PATH_SEPARATOR;
256 }
257
258 if ( !strPath.empty() )
259 {
260 if ( m_pContainer->GetPath() != strPath )
261 {
262 // we do change the path so restore it later
263 m_bChanged = true;
264
265 /* JACS: work around a memory bug that causes an assert
266 when using wxRegConfig, related to reference-counting.
267 Can be reproduced by removing .wc_str() below and
268 adding the following code to the config sample OnInit under
269 Windows:
270
271 pConfig->SetPath(wxT("MySettings"));
272 pConfig->SetPath(wxT(".."));
273 int value;
274 pConfig->Read(_T("MainWindowX"), & value);
275 */
276 m_strOldPath = m_pContainer->GetPath().wc_str();
277 if ( *m_strOldPath.c_str() != wxCONFIG_PATH_SEPARATOR )
278 m_strOldPath += wxCONFIG_PATH_SEPARATOR;
279 m_pContainer->SetPath(strPath);
280 }
281
282 // in any case, use the just the name, not full path
283 m_strName = strEntry.AfterLast(wxCONFIG_PATH_SEPARATOR);
284 }
285 else {
286 // it's a name only, without path - nothing to do
287 m_strName = strEntry;
288 }
289 }
290
291 void wxConfigPathChanger::UpdateIfDeleted()
292 {
293 // we don't have to do anything at all if we didn't change the path
294 if ( !m_bChanged )
295 return;
296
297 // find the deepest still existing parent path of the original path
298 while ( !m_pContainer->HasGroup(m_strOldPath) )
299 {
300 m_strOldPath = m_strOldPath.BeforeLast(wxCONFIG_PATH_SEPARATOR);
301 if ( m_strOldPath.empty() )
302 m_strOldPath = wxCONFIG_PATH_SEPARATOR;
303 }
304 }
305
306 wxConfigPathChanger::~wxConfigPathChanger()
307 {
308 // only restore path if it was changed
309 if ( m_bChanged ) {
310 m_pContainer->SetPath(m_strOldPath);
311 }
312 }
313
314 // this is a wxConfig method but it's mainly used with wxConfigPathChanger
315 /* static */
316 wxString wxConfigBase::RemoveTrailingSeparator(const wxString& key)
317 {
318 wxString path(key);
319
320 // don't remove the only separator from a root group path!
321 while ( path.length() > 1 )
322 {
323 if ( *path.rbegin() != wxCONFIG_PATH_SEPARATOR )
324 break;
325
326 path.erase(path.end() - 1);
327 }
328
329 return path;
330 }
331
332 #endif // wxUSE_CONFIG
333
334 // ----------------------------------------------------------------------------
335 // static & global functions
336 // ----------------------------------------------------------------------------
337
338 // understands both Unix and Windows (but only under Windows) environment
339 // variables expansion: i.e. $var, $(var) and ${var} are always understood
340 // and in addition under Windows %var% is also.
341
342 // don't change the values the enum elements: they must be equal
343 // to the matching [closing] delimiter.
344 enum Bracket
345 {
346 Bracket_None,
347 Bracket_Normal = ')',
348 Bracket_Curly = '}',
349 #ifdef __WXMSW__
350 Bracket_Windows = '%', // yeah, Windows people are a bit strange ;-)
351 #endif
352 Bracket_Max
353 };
354
355 wxString wxExpandEnvVars(const wxString& str)
356 {
357 wxString strResult;
358 strResult.Alloc(str.length());
359
360 size_t m;
361 for ( size_t n = 0; n < str.length(); n++ ) {
362 switch ( str[n].GetValue() ) {
363 #ifdef __WXMSW__
364 case wxT('%'):
365 #endif //WINDOWS
366 case wxT('$'):
367 {
368 Bracket bracket;
369 #ifdef __WXMSW__
370 if ( str[n] == wxT('%') )
371 bracket = Bracket_Windows;
372 else
373 #endif //WINDOWS
374 if ( n == str.length() - 1 ) {
375 bracket = Bracket_None;
376 }
377 else {
378 switch ( str[n + 1].GetValue() ) {
379 case wxT('('):
380 bracket = Bracket_Normal;
381 n++; // skip the bracket
382 break;
383
384 case wxT('{'):
385 bracket = Bracket_Curly;
386 n++; // skip the bracket
387 break;
388
389 default:
390 bracket = Bracket_None;
391 }
392 }
393
394 m = n + 1;
395
396 while ( m < str.length() && (wxIsalnum(str[m]) || str[m] == wxT('_')) )
397 m++;
398
399 wxString strVarName(str.c_str() + n + 1, m - n - 1);
400
401 #ifdef __WXWINCE__
402 const bool expanded = false;
403 #else
404 // NB: use wxGetEnv instead of wxGetenv as otherwise variables
405 // set through wxSetEnv may not be read correctly!
406 bool expanded = false;
407 wxString tmp;
408 if (wxGetEnv(strVarName, &tmp))
409 {
410 strResult += tmp;
411 expanded = true;
412 }
413 else
414 #endif
415 {
416 // variable doesn't exist => don't change anything
417 #ifdef __WXMSW__
418 if ( bracket != Bracket_Windows )
419 #endif
420 if ( bracket != Bracket_None )
421 strResult << str[n - 1];
422 strResult << str[n] << strVarName;
423 }
424
425 // check the closing bracket
426 if ( bracket != Bracket_None ) {
427 if ( m == str.length() || str[m] != (wxChar)bracket ) {
428 // under MSW it's common to have '%' characters in the registry
429 // and it's annoying to have warnings about them each time, so
430 // ignroe them silently if they are not used for env vars
431 //
432 // under Unix, OTOH, this warning could be useful for the user to
433 // understand why isn't the variable expanded as intended
434 #ifndef __WXMSW__
435 wxLogWarning(_("Environment variables expansion failed: missing '%c' at position %u in '%s'."),
436 (char)bracket, (unsigned int) (m + 1), str.c_str());
437 #endif // __WXMSW__
438 }
439 else {
440 // skip closing bracket unless the variables wasn't expanded
441 if ( !expanded )
442 strResult << (wxChar)bracket;
443 m++;
444 }
445 }
446
447 n = m - 1; // skip variable name
448 }
449 break;
450
451 case wxT('\\'):
452 // backslash can be used to suppress special meaning of % and $
453 if ( n != str.length() - 1 &&
454 (str[n + 1] == wxT('%') || str[n + 1] == wxT('$')) ) {
455 strResult += str[++n];
456
457 break;
458 }
459 //else: fall through
460
461 default:
462 strResult += str[n];
463 }
464 }
465
466 return strResult;
467 }
468
469 // this function is used to properly interpret '..' in path
470 void wxSplitPath(wxArrayString& aParts, const wxString& path)
471 {
472 aParts.clear();
473
474 wxString strCurrent;
475 wxString::const_iterator pc = path.begin();
476 for ( ;; ) {
477 if ( pc == path.end() || *pc == wxCONFIG_PATH_SEPARATOR ) {
478 if ( strCurrent == wxT(".") ) {
479 // ignore
480 }
481 else if ( strCurrent == wxT("..") ) {
482 // go up one level
483 if ( aParts.size() == 0 )
484 wxLogWarning(_("'%s' has extra '..', ignored."), path);
485 else
486 aParts.erase(aParts.end() - 1);
487
488 strCurrent.Empty();
489 }
490 else if ( !strCurrent.empty() ) {
491 aParts.push_back(strCurrent);
492 strCurrent.Empty();
493 }
494 //else:
495 // could log an error here, but we prefer to ignore extra '/'
496
497 if ( pc == path.end() )
498 break;
499 }
500 else
501 strCurrent += *pc;
502
503 ++pc;
504 }
505 }