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