Debian Codegraph @

code/apis/ProfileManager.cpp

raw ◀ ▶
1 Debian patch touch this file
1 /*
2 Copyright (C) 2009-2010 wxLauncher Team
3
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 */
18
19 #include <algorithm>
20 #include <vector>
21
22 #include <wx/wx.h>
23 #include <wx/fileconf.h>
24 #include <wx/stdpaths.h>
25 #include <wx/filename.h>
26 #include <wx/wfstream.h>
27 #include <wx/dir.h>
28
29 #include "generated/configure_launcher.h"
30 #include "apis/EventHandlers.h"
31 #include "apis/ProfileManager.h"
32 #include "apis/PlatformProfileManager.h"
33 #include "apis/FlagListManager.h"
34 #include "wxLauncherApp.h"
35 #include "global/ProfileKeys.h"
36
37 #include "global/MemoryDebugging.h"
38
39 ProMan* ProMan::proman = NULL;
40 bool ProMan::isInitialized = false;
41 ProMan::Flags ProMan::flags;
42
43 const wxString& ProMan::DEFAULT_PROFILE_NAME = _T("Default");
44 #define GLOBAL_INI_FILE_NAME _T("global.ini")
45
46 ///////////// Events
47
48 /** EVT_PROFILE_EVENT */
49 LAUNCHER_DEFINE_EVENT_TYPE(EVT_PROFILE_CHANGE);
50 LAUNCHER_DEFINE_EVENT_TYPE(EVT_CURRENT_PROFILE_CHANGED);
51
52 void ProMan::GenerateChangeEvent() {
53 wxCommandEvent event(EVT_PROFILE_CHANGE, wxID_NONE);
54 wxLogDebug(wxT_2("Generating profile change event"));
55 EventHandlers::iterator iter = this->eventHandlers.begin();
56 while (iter != this->eventHandlers.end()) {
57 wxEvtHandler* current = *iter;
58 current->AddPendingEvent(event);
59 wxLogDebug(wxT_2(" Sent Profile Change event to %p"), current);
60 iter++;
61 }
62 }
63
64 void ProMan::GenerateCurrentProfileChangedEvent() {
65 wxCommandEvent event(EVT_CURRENT_PROFILE_CHANGED, wxID_NONE);
66 wxLogDebug(wxT_2("Generating current profile changed event"));
67 EventHandlers::iterator iter = this->eventHandlers.begin();
68 while (iter != this->eventHandlers.end()) {
69 wxEvtHandler* current = *iter;
70 current->AddPendingEvent(event);
71 wxLogDebug(wxT_2(" Sent current profile changed event to %p"), current);
72 iter++;
73 }
74 }
75
76 void ProMan::AddEventHandler(wxEvtHandler *handler) {
77 wxASSERT_MSG(eventHandlers.IndexOf(handler) == wxNOT_FOUND,
78 wxString::Format(
79 wxT_2("ProMan::AddEventHandler(): Handler at %p already registered."),
80 handler));
81 this->eventHandlers.Append(handler);
82 }
83
84 void ProMan::RemoveEventHandler(wxEvtHandler *handler) {
85 wxASSERT_MSG(eventHandlers.IndexOf(handler) != wxNOT_FOUND,
86 wxString::Format(
87 wxT_2("ProMan::RemoveEventHandler(): Handler at %p not registered."),
88 handler));
89 this->eventHandlers.DeleteObject(handler);
90 }
91
92 NewsData::NewsData(const wxString& theNews, const wxDateTime& lastDownloadNews)
93 : theNews(theNews), lastDownloadNews(lastDownloadNews) {
94 wxASSERT(!theNews.IsEmpty());
95 wxASSERT(lastDownloadNews.IsValid());
96 }
97
98 /** Load a profile from a fully quaified path. Returns NULL on failure
99 or a pointer to a wxFileConfig that you must delete when done. */
100 wxFileConfig* LoadProfileFromFile(const wxFileName &file)
101 {
102 wxFFileInputStream globalProfileInput(file.GetFullPath(),
103 (file.FileExists())?wxT_2("rb"):wxT_2("w+b"));
104 return new wxFileConfig(globalProfileInput);
105 }
106
107 /** Sets up the profile manager. Must be called on program startup so that
108 it can intercept global wxWidgets configuation functions.
109 \return true when setup was successful, false if proman is not
110 ready and the program should not continue. */
111 bool ProMan::Initialize(Flags flags) {
112 wxConfigBase::DontCreateOnDemand();
113
114 ProMan::proman = new ProMan();
115 ProMan::flags = flags;
116
117 wxFileName file;
118 file.Assign(GetProfileStorageFolder(), GLOBAL_INI_FILE_NAME);
119
120 if ( !file.IsOk() ) {
121 wxLogError(_(" '%s' is not valid!"), file.GetFullPath().c_str());
122 return false;
123 }
124
125 wxLogInfo(_(" My profiles file is: %s"), file.GetFullPath().c_str());
126 if ( !wxFileName::DirExists(file.GetPath())
127 && !wxFileName::Mkdir(file.GetPath(), 0700, wxPATH_MKDIR_FULL ) ) {
128 wxLogError(_(" Unable to make profile folder."));
129 return false;
130 }
131
132 ProMan::proman->globalProfile = LoadProfileFromFile(file);
133 ProMan::proman->LoadNewsMapFromGlobalProfile();
134
135 // fetch all profiles.
136 wxArrayString foundProfiles;
137 wxDir::GetAllFiles(GetProfileStorageFolder(), &foundProfiles, wxT_2("pro?????.ini"));
138
•139 wxLogInfo(wxT_2(" Found %u profile(s)."), static_cast<unsigned>(foundProfiles.Count()));
140 for( size_t i = 0; i < foundProfiles.Count(); i++) {
141 wxLogDebug(wxT_2(" Opening %s"), foundProfiles[i].c_str());
142 wxFFileInputStream instream(foundProfiles[i]);
143 wxFileConfig *config = new wxFileConfig(instream);
144
145 wxString name;
146 config->Read(PRO_CFG_MAIN_NAME, &name, wxString::Format(wxT_2("Profile %05ld"), i));
147
148 ProMan::proman->profiles[name] = config;
149 wxLogDebug(wxT_2(" Opened profile named: %s"), name.c_str());
150 }
151
152 wxString currentProfile;
153 ProMan::proman->globalProfile->Read(
154 GBL_CFG_MAIN_LASTPROFILE, &currentProfile, ProMan::DEFAULT_PROFILE_NAME);
155
156 wxLogDebug(wxT_2(" Searching for profile: %s"), currentProfile.c_str());
157 if ( ProMan::proman->profiles.find(currentProfile)
158 == ProMan::proman->profiles.end() ) {
159 // lastprofile does not exist
160 wxLogDebug(wxT_2(" lastprofile '%s' does not exist!"), currentProfile.c_str());
161 if ( ProMan::proman->profiles.find(ProMan::DEFAULT_PROFILE_NAME)
162 == ProMan::proman->profiles.end() ) {
163 // default profile also does not exist.
164 // Means this is likely the first run this system
165 // Create a default profile
166 wxLogInfo(wxT_2(" Default profile does not exist! Creating..."));
167 ProMan::proman->CreateNewProfile(ProMan::DEFAULT_PROFILE_NAME);
168 // FIXME figure out how PullProfile is corrupting default profile (esp. on Windows)
169 // wxLogInfo(wxT_2(" Priming profile..."));
170 // PullProfile(ProMan::proman->profiles[ProMan::DEFAULT_PROFILE_NAME]);
171 }
172 wxLogInfo(wxT_2(" Resetting lastprofile to Default."));
173 // Do not ignore updating last profile here because this is fixing bad data
174 ProMan::proman->globalProfile->Write(GBL_CFG_MAIN_LASTPROFILE, ProMan::DEFAULT_PROFILE_NAME);
175 wxFFileOutputStream globalProfileOutput(file.GetFullPath());
176 ProMan::proman->globalProfile->Save(globalProfileOutput);
177 currentProfile = ProMan::DEFAULT_PROFILE_NAME;
178 }
179
180 wxLogDebug(wxT_2(" Making '%s' the application profile"), currentProfile.c_str());
181 if ( !ProMan::proman->SwitchTo(currentProfile) ) {
182 wxLogError(_("Unable to set current profile to '%s'"), currentProfile.c_str());
183 return false;
184 }
185
186 ProMan::isInitialized = true;
187 wxLogDebug(wxT_2(" Profile Manager is set up"));
188 return true;
189 }
190
191 /** clean up the memory that the manager is using. */
192 bool ProMan::DeInitialize() {
193 if ( ProMan::isInitialized ) {
194 ProMan::isInitialized = false;
195
196 ProMan::proman->SaveProfilesBeforeExiting();
197
198 delete ProMan::proman;
199 ProMan::proman = NULL;
200
201 // Set the wxWidgets default FileConfig to null
202 // so that it doesn't try to delete it again when
203 // we shutdown
204 wxFileConfig::Set((wxConfigBase*)NULL);
205
206 return true;
207 } else {
208 return false;
209 }
210 }
211
212
213 ProMan* ProMan::GetProfileManager() {
214 if ( ProMan::isInitialized ) {
215 return ProMan::proman;
216 } else {
217 return NULL;
218 }
219 }
220
221 /** Private constructor. Just makes instance variables safe. Call Initialize()
222 to setup class, then call GetProfileManager() to get a pointer to the instance.
223 */
224 ProMan::ProMan() {
225 this->globalProfile = NULL;
226 this->isAutoSaving = true;
227 this->currentProfile = NULL;
228
229 this->privateCopyFilename = wxFileName::CreateTempFileName(wxT_2("wxLtest"));
230 wxFFileInputStream instream(this->privateCopyFilename);
231 this->privateCopy = new wxFileConfig(instream);
232 }
233
234 /** Destructor. */
235 ProMan::~ProMan() {
236 // don't leak the wxFileConfigs
237 ProfileMap::iterator iter = this->profiles.begin();
238 while ( iter != this->profiles.end() ) {
239 delete iter->second;
240 iter++;
241 }
242
243 delete this->privateCopy;
244 privateCopy = NULL;
245 ::wxRemoveFile(this->privateCopyFilename);
246 }
247
248 /** Saves changes to profiles according to autosave profiles checkbox. */
249 void ProMan::SaveProfilesBeforeExiting() {
250 if ( this->globalProfile != NULL ) {
251 wxLogInfo(wxT_2("saving global profile before exiting."));
252 SaveNewsMapToGlobalProfile();
253
254 wxFileName file;
255 file.Assign(GetProfileStorageFolder(), GLOBAL_INI_FILE_NAME);
256 wxFFileOutputStream globalProfileOutput(file.GetFullPath());
257 this->globalProfile->Save(globalProfileOutput);
258
259 delete this->globalProfile;
260 } else {
261 wxLogWarning(_("global profile is null, cannot save it"));
262 }
263
264 if (this->HasUnsavedChanges()) {
265 if (this->isAutoSaving) {
266 wxLogInfo(_("autosaving profile %s before exiting"),
267 this->GetCurrentName().c_str());
268 this->SaveCurrentProfile();
269 } else {
270 int response = wxMessageBox(
271 GetSaveDialogMessageText(ProMan::ON_EXIT, this->GetCurrentName()),
272 GetSaveDialogCaptionText(ProMan::ON_EXIT, this->GetCurrentName()),
273 wxYES_NO);
274 if ( response == wxYES ) {
275 wxLogInfo(wxT_2("saving profile %s before exiting"),
276 this->GetCurrentName().c_str());
277 this->SaveCurrentProfile();
278 } else {
279 wxLogWarning(wxT_2("exiting without saving changes to profile %s"),
280 this->GetCurrentName().c_str());
281 }
282 }
283 } else {
284 wxLogInfo(wxT_2("Current profile %s has no unsaved changes. Exiting."),
285 this->GetCurrentName().c_str());
286 }
287 }
288
289 void ProMan::LoadNewsMapFromGlobalProfile() {
290 wxASSERT(newsMap.empty());
291
292 globalProfile->SetPath(GBL_CFG_NET_FOLDER);
293
294 // inspired by CopyConfig()
295 wxString groupName;
296 long groupIndex;
297 bool groupKeepGoing;
298
299 wxString theNews;
300 wxString lastDownloadNewsStr;
301 wxDateTime lastDownloadNews;
302
303 groupKeepGoing = globalProfile->GetFirstGroup(groupName, groupIndex);
304
305 while (groupKeepGoing) {
306 globalProfile->SetPath(groupName);
307
308 if (globalProfile->Read(GBL_CFG_NET_THE_NEWS, &theNews) &&
309 (globalProfile->Read(GBL_CFG_NET_NEWS_LAST_TIME, &lastDownloadNewsStr))) {
310 if ((!theNews.IsEmpty()) &&
311 (NULL != lastDownloadNews.ParseFormat(
312 lastDownloadNewsStr, NEWS_LAST_TIME_FORMAT))) {
313 newsMap[groupName] = NewsData(theNews, lastDownloadNews);
314
315 wxLogDebug(wxT_2("Created news map entry for source %s"),
316 groupName.c_str());
317 }
318 }
319
320 globalProfile->SetPath(wxT_2(".."));
321
322 groupKeepGoing = globalProfile->GetNextGroup(groupName, groupIndex);
323 }
324
325 globalProfile->SetPath(wxT_2("/"));
326 }
327
328 void ProMan::SaveNewsMapToGlobalProfile() {
329 globalProfile->SetPath(GBL_CFG_NET_FOLDER);
330
331 for (NewsMap::const_iterator it = newsMap.begin(), end = newsMap.end();
332 it != end; ++it) {
333 const wxString& newsSource = it->first;
334 const NewsData& newsData = it->second;
335
336 globalProfile->SetPath(newsSource);
337 globalProfile->Write(GBL_CFG_NET_THE_NEWS, newsData.theNews);
338 globalProfile->Write(GBL_CFG_NET_NEWS_LAST_TIME,
339 newsData.lastDownloadNews.Format(NEWS_LAST_TIME_FORMAT));
340 globalProfile->SetPath(wxT_2(".."));
341 }
342
343 globalProfile->SetPath(wxT_2("/"));
344 }
345
346 /** Resets the private copy so that it contains a copy
347 of the current profile's contents. */
348 void ProMan::ResetPrivateCopy() {
349 wxCHECK_RET(this->currentProfile != NULL, wxT_2("ResetPrivateCopy called with null current profile!"));
350 ClearConfig(*(this->privateCopy));
351 CopyConfig(*(this->currentProfile), *(this->privateCopy));
352 }
353
354 /** Creates a new profile including the directory for it to go in, the entry
355 in the profiles map. Returns true if creation was successful. */
356 bool ProMan::CreateNewProfile(wxString newName) {
357 wxFileName profile;
358 profile.Assign(
359 GetProfileStorageFolder(),
360 this->GenerateNewProfileFileName());
361
362 wxLogInfo(wxT_2("New profile will be written to %s"), profile.GetFullPath().c_str());
363
364 wxASSERT_MSG( profile.IsOk(), wxT_2("Profile filename is invalid"));
365
366 if ( !wxFileName::DirExists(profile.GetPath())
367 && !wxFileName::Mkdir( profile.GetPath(), wxPATH_MKDIR_FULL) ) {
368 wxLogWarning(_(" Unable to create profile folder: %s"), profile.GetPath().c_str());
369 return false;
370 }
371
372 wxFFileInputStream configInput(profile.GetFullPath(), wxT_2("w+b"));
373 wxFileConfig* config = new wxFileConfig(configInput);
374 config->Write(PRO_CFG_MAIN_NAME, newName);
375 config->Write(PRO_CFG_MAIN_FILENAME, profile.GetFullName());
376 wxFFileOutputStream configOutput(profile.GetFullPath());
377 config->Save(configOutput);
378
379 this->profiles[newName] = config;
380 return true;
381 }
382
383 /** Generates a filename for a new profile, where the name is of the form
384 pro#####.ini with ##### being the least 5-digit number not yet taken. */
385 wxString ProMan::GenerateNewProfileFileName() {
386 wxArrayString profileFiles;
387 wxDir::GetAllFiles(GetProfileStorageFolder(), &profileFiles, wxT_2("pro*.ini"), wxDIR_FILES);
388
389 long l;
390
391 std::vector<long> proNums;
392
393 for (int i = 0, n = profileFiles.GetCount(); i < n; ++i) {
394 profileFiles[i] = profileFiles[i].AfterLast(wxT_2('o')).BeforeLast(wxT_2('.'));
395 profileFiles[i].ToLong(&l);
396 proNums.push_back(l);
397 }
398
399 // just in case they're not already in sorted order
400 sort(proNums.begin(), proNums.end());
401
402 proNums.insert(proNums.begin(), -1); // dummy value that allows for easily checking first element
403
404 long proIndex = 0;
405
406 int i;
407 const int n = proNums.size();
408
409 for (i = 1; i < n; ++i) {
410 if (proNums[i] - proNums[i-1] > 1) { // if there's a gap in the numbering, try to fill it
411 proIndex = proNums[i-1] + 1;
412 break;
413 }
414 }
415
416 if (i == n) { // there are no gaps, so increment from the last element
417 proIndex = proNums[n-1] + 1;
418 }
419
420 wxLogDebug(wxT_2("new profile number: %ld"), proIndex);
421
422 wxASSERT(proIndex <= 99999); // the maximum possible index given a 5-digit number
423
424 return wxString::Format(wxT_2("pro%05ld.ini"), proIndex);
425 }
426
427 // global profile access functions
428
429 /** Tests whether the key strName is in the global profile. */
430 bool ProMan::GlobalExists(wxString& strName) const {
431 if (this->globalProfile == NULL) {
432 wxLogWarning(wxT_2("attempt to check existence of key %s in null global profile"),
433 strName.c_str());
434 return false;
435 } else {
436 return this->globalProfile->Exists(strName);
437 }
438 }
439
440 /** Tests whether the key strName is in the global profile */
441 bool ProMan::GlobalExists(const wxChar* strName) const {
442 if (this->globalProfile == NULL) {
443 wxLogWarning(wxT_2("attempt to check existence of key %s in null global profile"),
444 strName);
445 return false;
446 } else {
447 return this->globalProfile->Exists(strName);
448 }
449 }
450
451 /** Reads a bool from the global profile. Returns true on success. */
452 bool ProMan::GlobalRead(const wxString& key, bool* b) const {
453 if (this->globalProfile == NULL) {
454 wxLogWarning(
455 wxT_2("attempt to read bool for key %s from null global profile"),
456 key.c_str());
457 return false;
458 } else {
459 return this->globalProfile->Read(key, b);
460 }
461 }
462
463 /** Reads a bool from the global profile,
464 using the default value if the key is not present.
465 If the entry is not present in the global profile and writeBackIfAbsent is set to true,
466 then the default value is written back to the global profile.
467 Returns true on success. */
468 bool ProMan::GlobalRead(const wxString& key, bool* b, bool defaultVal, bool writeBackIfAbsent) {
469 if (this->globalProfile == NULL) {
470 wxLogWarning(
471 wxT_2("attempt to read bool for key %s with default value %s from null global profile"),
472 key.c_str(), defaultVal ? wxT_2("true") : wxT_2("false"));
473 return false;
474 } else {
475 bool readSuccess = this->globalProfile->Read(key, b, defaultVal);
476 if (!readSuccess && writeBackIfAbsent) {
477 wxLogDebug(wxT_2("entry %s in global profile is absent. writing default value %s to it."),
478 key.c_str(), defaultVal ? wxT_2("true") : wxT_2("false"));
479 this->globalProfile->Write(key, defaultVal);
480 }
481 return readSuccess;
482 }
483 }
484
485 /** Reads a string from the global profile. Returns true on success. */
486 bool ProMan::GlobalRead(const wxString& key, wxString* str) const {
487 if (this->globalProfile == NULL) {
488 wxLogWarning(
489 wxT_2("attempt to read string for key %s with from null global profile"),
490 key.c_str());
491 return false;
492 } else {
493 return this->globalProfile->Read(key, str);
494 }
495 }
496
497 /** Reads a string from the global profile,
498 using the default value if the key is not present.
499 If the entry is not present in the global profile and writeBackIfAbsent is set to true,
500 then the default value is written back to the global profile.
501 Returns true on success. */
502 bool ProMan::GlobalRead(const wxString& key, wxString* str, const wxString& defaultVal, bool writeBackIfAbsent) {
503 if (this->globalProfile == NULL) {
504 wxLogWarning(
505 wxT_2("attempt to read string for key %s with default value %s from null global profile"),
506 key.c_str(), defaultVal.c_str());
507 return false;
508 } else {
509 bool readSuccess = this->globalProfile->Read(key, str, defaultVal);
510 if (!readSuccess && writeBackIfAbsent) {
511 wxLogDebug(wxT_2("entry %s in global profile is absent. writing default value %s to it."),
512 key.c_str(), defaultVal.c_str());
513 this->globalProfile->Write(key, defaultVal);
514 }
515 return readSuccess;
516 }
517 }
518
519 /** Reads a long from the global profile,
520 using the default value if the key is not present.
521 If the entry is not present in the global profile and writeBackIfAbsent is set to true,
522 then the default value is written back to the global profile.
523 Returns true on success. */
524 bool ProMan::GlobalRead(const wxString& key, long* l, long defaultVal, bool writeBackIfAbsent) {
525 if (this->globalProfile == NULL) {
526 wxLogWarning(
527 wxT_2("attempt to read long for key %s with default value %ld from null global profile"),
528 key.c_str(), defaultVal);
529 return false;
530 } else {
531 bool readSuccess = this->globalProfile->Read(key, l, defaultVal);
532 if (!readSuccess && writeBackIfAbsent) {
533 wxLogDebug(wxT_2("entry %s in global profile is absent. writing default value %ld to it."),
534 key.c_str(), defaultVal);
535 this->globalProfile->Write(key, defaultVal);
536 }
537 return readSuccess;
538 }
539 }
540
541 /** Writes a string for the given key to the global profile.
542 Returns true on success. */
543 bool ProMan::GlobalWrite(const wxString& key, const wxString& value) {
544 if (this->globalProfile == NULL) {
545 wxLogWarning(wxT_2("attempt to write %s to %s in null global profile"),
546 value.c_str(), key.c_str());
547 return false;
548 } else {
549 return this->globalProfile->Write(key, value);
550 }
551 }
552
553 /** Writes a string for the given key to the global profile.
554 Returns true on success. */
555 bool ProMan::GlobalWrite(const wxString& key, const wxChar* value) {
556 if (this->globalProfile == NULL) {
557 wxLogWarning(wxT_2("attempt to write %s to %s in null global profile"),
558 value, key.c_str());
559 return false;
560 } else {
561 return this->globalProfile->Write(key, value);
562 }
563 }
564
565 /** Writes a long for the given key to the global profile.
566 Returns true on success. */
567 bool ProMan::GlobalWrite(const wxString& key, long value) {
568 if (this->globalProfile == NULL) {
569 wxLogWarning(wxT_2("attempt to write %ld to %s in null global profile"),
570 value, key.c_str());
571 return false;
572 } else {
573 return this->globalProfile->Write(key, value);
574 }
575 }
576
577 /** Writes a bool for the given key to the global profile.
578 Returns true on success. */
579 bool ProMan::GlobalWrite(const wxString& key, bool value) {
580 if (this->globalProfile == NULL) {
581 wxLogWarning(wxT_2("attempt to write %s to %s in null global profile"),
582 value ? wxT_2("true") : wxT_2("false"), key.c_str());
583 return false;
584 } else {
585 return this->globalProfile->Write(key, value);
586 }
587 }
588
589 // current profile access functions
590
591 /** Tests whether the key strName is in the current profile. */
592 bool ProMan::ProfileExists(const wxString& strName) const {
593 if (this->currentProfile == NULL) {
594 wxLogWarning(wxT_2("attempt to check existence of key %s in null current profile"),
595 strName.c_str());
596 return false;
597 } else {
598 return this->currentProfile->Exists(strName);
599 }
600 }
601
602 /** Tests whether the key strName is in the current profile. */
603 bool ProMan::ProfileExists(const wxChar* strName) const {
604 if (this->currentProfile == NULL) {
605 wxLogWarning(wxT_2("attempt to check existence of key %s in null current profile"),
606 strName);
607 return false;
608 } else {
609 return this->currentProfile->Exists(strName);
610 }
611 }
612
613 /** Reads a bool from the current profile. Returns true on success. */
614 bool ProMan::ProfileRead(const wxString& key, bool* b) const {
615 if (this->currentProfile == NULL) {
616 wxLogWarning(
617 wxT_2("attempt to read bool for key %s from null current profile"),
618 key.c_str());
619 return false;
620 } else {
621 return this->currentProfile->Read(key, b);
622 }
623 }
624
625 /** Reads a bool from the current profile,
626 using the default value if the key is not present.
627 If the entry is not present in the current profile and writeBackIfAbsent is set to true,
628 then the default value is written back to the current profile.
629 Returns true on success. */
630 bool ProMan::ProfileRead(const wxString& key, bool* b, bool defaultVal, bool writeBackIfAbsent) {
631 if (this->currentProfile == NULL) {
632 wxLogWarning(
633 wxT_2("attempt to read bool for key %s with default value %s from null current profile"),
634 key.c_str(), defaultVal ? wxT_2("true") : wxT_2("false"));
635 return false;
636 } else {
637 bool readSuccess = this->currentProfile->Read(key, b, defaultVal);
638 if (!readSuccess && writeBackIfAbsent) {
639 wxLogDebug(wxT_2("entry %s in current profile is absent. writing default value %s to it."),
640 key.c_str(), defaultVal ? wxT_2("true") : wxT_2("false"));
641 this->currentProfile->Write(key, defaultVal);
642 }
643 return readSuccess;
644 }
645 }
646
647 /** Reads a string from the current profile. Returns true on success. */
648 bool ProMan::ProfileRead(const wxString& key, wxString* str) const {
649 if (this->currentProfile == NULL) {
650 wxLogWarning(
651 wxT_2("attempt to read string for key %s with from null current profile"),
652 key.c_str());
653 return false;
654 } else {
655 return this->currentProfile->Read(key, str);
656 }
657 }
658
659 /** Reads a string from the current profile,
660 using the default value if the key is not present.
661 If the entry is not present in the current profile and writeBackIfAbsent is set to true,
662 then the default value is written back to the current profile.
663 Returns true on success. */
664 bool ProMan::ProfileRead(const wxString& key, wxString* str, const wxString& defaultVal, bool writeBackIfAbsent) {
665 if (this->currentProfile == NULL) {
666 wxLogWarning(
667 wxT_2("attempt to read string for key %s with default value %s from null current profile"),
668 key.c_str(), defaultVal.c_str());
669 return false;
670 } else {
671 bool readSuccess = this->currentProfile->Read(key, str, defaultVal);
672 if (!readSuccess && writeBackIfAbsent) {
673 wxLogDebug(wxT_2("entry %s in current profile is absent. writing default value %s to it."),
674 key.c_str(), defaultVal.c_str());
675 this->currentProfile->Write(key, defaultVal);
676 }
677 return readSuccess;
678 }
679 }
680
681 /** Reads a long from the current profile. Returns true on success. */
682 bool ProMan::ProfileRead(const wxString& key, long* l) const {
683 if (this->currentProfile == NULL) {
684 wxLogWarning(
685 wxT_2("attempt to read long for key %s from null current profile"),
686 key.c_str());
687 return false;
688 } else {
689 return this->currentProfile->Read(key, l);
690 }
691 }
692
693 /** Reads a long from the current profile,
694 using the default value if the key is not present.
695 If the entry is not present in the current profile and writeBackIfAbsent is set to true,
696 then the default value is written back to the current profile.
697 Returns true on success. */
698 bool ProMan::ProfileRead(const wxString& key, long* l, long defaultVal, bool writeBackIfAbsent) {
699 if (this->currentProfile == NULL) {
700 wxLogWarning(
701 wxT_2("attempt to read long for key %s with default value %ld from null current profile"),
702 key.c_str(), defaultVal);
703 return false;
704 } else {
705 bool readSuccess = this->currentProfile->Read(key, l, defaultVal);
706 if (!readSuccess && writeBackIfAbsent) {
707 wxLogDebug(wxT_2("entry %s in current profile is absent. writing default value %ld to it."),
708 key.c_str(), defaultVal);
709 this->currentProfile->Write(key, defaultVal);
710 }
711 return readSuccess;
712 }
713 }
714
715 /** Writes a string for the given key to the current profile.
716 Returns true on success. */
717 bool ProMan::ProfileWrite(const wxString& key, const wxString& value) {
718 if (this->currentProfile == NULL) {
719 wxLogWarning(wxT_2("attempt to write %s to %s in null current profile"),
720 value.c_str(), key.c_str());
721 return false;
722 } else {
723 if (!this->currentProfile->Exists(key)) {
724 wxLogDebug(wxT_2("adding entry %s with value %s to current profile"),
725 key.c_str(), value.c_str());
726 } else {
727 wxString oldValue;
728 if (this->currentProfile->Read(key, &oldValue) && (value != oldValue)) {
729 wxLogDebug(wxT_2("replacing old value %s with value %s for current profile entry %s"),
730 oldValue.c_str(), value.c_str(), key.c_str());
731 }
732 }
733 return this->currentProfile->Write(key, value);
734 }
735 }
736
737 /** Writes a string for the given key to the current profile.
738 Returns true on success. */
739 bool ProMan::ProfileWrite(const wxString& key, const wxChar* value) {
740 if (this->currentProfile == NULL) {
741 wxLogWarning(wxT_2("attempt to write %s to %s in null current profile"),
742 value, key.c_str());
743 return false;
744 } else {
745 if (!this->currentProfile->Exists(key)) {
746 wxLogDebug(wxT_2("adding entry %s with value %s to current profile"),
747 key.c_str(), value);
748 } else {
749 wxString oldValue;
750 if (this->currentProfile->Read(key, &oldValue) && (value != oldValue)) {
751 wxLogDebug(wxT_2("replacing old value %s with value %s for current profile entry %s"),
752 oldValue.c_str(), value, key.c_str());
753 }
754 }
755 return this->currentProfile->Write(key, value);
756 }
757 }
758
759 /** Writes a long for the given key to the current profile.
760 Returns true on success. */
761 bool ProMan::ProfileWrite(const wxString& key, long value) {
762 if (this->currentProfile == NULL) {
763 wxLogWarning(wxT_2("attempt to write %ld to %s in null current profile"),
764 value, key.c_str());
765 return false;
766 } else {
767 if (!this->currentProfile->Exists(key)) {
768 wxLogDebug(wxT_2("adding entry %s with value %ld to current profile"),
769 key.c_str(), value);
770 } else {
771 long oldValue;
772 if (this->currentProfile->Read(key, &oldValue) && (value != oldValue)) {
773 wxLogDebug(wxT_2("replacing old value %ld with value %ld for current profile entry %s"),
774 oldValue, value, key.c_str());
775 }
776 }
777 return this->currentProfile->Write(key, value);
778 }
779 }
780
781 /** Writes a bool for the given key to the current profile.
782 Returns true on success. */
783 bool ProMan::ProfileWrite(const wxString& key, bool value) {
784 if (this->currentProfile == NULL) {
785 wxLogWarning(wxT_2("attempt to write %s to %s in null current profile"),
786 value ? wxT_2("true") : wxT_2("false"), key.c_str());
787 return false;
788 } else {
789 if (!this->currentProfile->Exists(key)) {
790 wxLogDebug(wxT_2("adding entry %s with value %s to current profile"),
791 key.c_str(), value ? wxT_2("true") : wxT_2("false"));
792 } else {
793 bool oldValue;
794 if (this->currentProfile->Read(key, &oldValue) && (value != oldValue)) {
795 wxLogDebug(wxT_2("replacing old value %s with value %s for current profile entry %s"),
796 oldValue ? wxT_2("true") : wxT_2("false"),
797 value ? wxT_2("true") : wxT_2("false"),
798 key.c_str());
799 }
800 }
801
802 return this->currentProfile->Write(key, value);
803 }
804 }
805
806 /** Deletes an entry from the current profile,
807 deleting the group if the entry was the only one in the group
808 and the second parameter is true. */
809 bool ProMan::ProfileDeleteEntry(const wxString& key, bool bDeleteGroupIfEmpty) {
810 if (this->currentProfile == NULL) {
811 wxLogWarning(wxT_2("attempt to delete entry %s in null current profile"),
812 key.c_str());
813 return false;
814 } else {
815 if (this-currentProfile->Exists(key)) {
816 wxLogDebug(wxT_2("deleting key %s in profile"),
817 key.c_str());
818 }
819 return this->currentProfile->DeleteEntry(key, bDeleteGroupIfEmpty);
820 }
821 }
822
823 const NewsData* ProMan::NewsRead(const wxString& newsSource) const {
824 wxCHECK_MSG(!newsSource.IsEmpty(), NULL, wxT_2("NewsRead: newsSource is empty!"));
825
826 NewsMap::const_iterator it = newsMap.find(newsSource);
827
828 if (it == newsMap.end()) {
829 return NULL;
830 } else {
831 return &(it->second);
832 }
833 }
834
835 void ProMan::NewsWrite(const wxString& newsSource, const NewsData& data) {
836 wxCHECK_RET(!newsSource.IsEmpty(), wxT_2("NewsWrite: newsSource is empty!"));
837 wxCHECK_RET(data.IsValid(), wxT_2("NewsWrite: data is not valid!"));
838
839 newsMap[newsSource] = data;
840 }
841
842 /** Returns the text to use in the "save changes?" dialog's caption (window title) */
843 const wxString ProMan::GetSaveDialogCaptionText(ProMan::SaveDialogContext context,
844 const wxString& profileName) {
845 // currently, the same text is used on all platforms, although it doesn't have to be that way
846 // NOTE: don't attempt to collapse the cases by removing break statements! it's asking for trouble
847 switch (context) {
848 case ON_PROFILE_SWITCH:
849 #if PROFILE_DEBUGGING
850 wxLogDebug(wxT_2("contents of private copy at save prompt on profile switch:"));
851 LogConfigContents(*ProMan::proman->privateCopy);
852 wxLogDebug(wxT_2("contents of current profile at save prompt on profile switch:"));
853 LogConfigContents(*ProMan::proman->currentProfile);
854 #endif
855 return _("Save changes to current profile?");
856 break;
857
858 case ON_PROFILE_CREATE:
859 #if PROFILE_DEBUGGING
860 wxLogDebug(wxT_2("contents of private copy at save prompt on profile create:"));
861 LogConfigContents(*ProMan::proman->privateCopy);
862 wxLogDebug(wxT_2("contents of current profile at save prompt on profile create:"));
863 LogConfigContents(*ProMan::proman->currentProfile);
864 #endif
865 return _("Save changes to current profile?");
866 break;
867
868 case ON_EXIT:
869 #if PROFILE_DEBUGGING
870 wxLogDebug(wxT_2("contents of private copy at save prompt on exit:"));
871 LogConfigContents(*ProMan::proman->privateCopy);
872 wxLogDebug(wxT_2("contents of current profile at save prompt on exit:"));
873 LogConfigContents(*ProMan::proman->currentProfile);
874 #endif
875 return _("Save changes to current profile?");
876 break;
877
878 default:
879 wxCHECK_MSG(false, wxEmptyString, wxT_2("ProMan::GetSaveDialogCaptionText: provided context is invalid"));
880 break;
881 }
882 }
883
884 /** Returns the text to use in the "save changes?" dialog's message (text area) */
885 const wxString ProMan::GetSaveDialogMessageText(ProMan::SaveDialogContext context,
886 const wxString& profileName) {
887 switch (context) {
888 case ON_PROFILE_SWITCH:
889 return wxString::Format(_("Save changes to profile '%s' before switching profiles?"),
890 profileName.c_str());
891 break;
892
893 case ON_PROFILE_CREATE:
894 return wxString::Format(_("Save changes to profile '%s' before creating a new profile?"),
895 profileName.c_str());
896 break;
897
898 case ON_EXIT:
899 #if IS_WIN32
900 return wxString::Format(_("Save changes to profile '%s' before exiting?"),
901 profileName.c_str());
902 #else
903 return wxString::Format(_("Save changes to profile '%s' before quitting?"),
904 profileName.c_str());
905 #endif
906 break;
907
908 default:
909 wxCHECK_MSG(false, wxEmptyString, wxT_2("ProMan::GetSaveDialogMessageText: provided context is invalid"));
910 break;
911 }
912 }
913
914 /** Returns true if the named profile exists, false otherwise. */
915 bool ProMan::DoesProfileExist(wxString name) {
916 /* Item exists if the returned value from find() does not equal
917 the value of .end(). As per the HashMap docs. */
918 return (this->profiles.find(name) != this->profiles.end());
919 }
920
921 /** Returns an wxArrayString of all of the profile names. */
922 wxArrayString ProMan::GetAllProfileNames() {
923 wxArrayString out;
924
925 ProfileMap::iterator iter = this->profiles.begin();
926 do {
927 out.Add(iter->first);
928 iter++;
929 } while (iter != this->profiles.end());
930
931 return out;
932 }
933
934 void SaveProfileToDisk(wxFileConfig* toSave, const wxString& name)
935 {
936 wxString profileFilename;
937 if ( !toSave->Read(PRO_CFG_MAIN_FILENAME, &profileFilename) ) {
938 wxLogError(wxT_2("Profile '%s' does not have a file name. Cannot save it."),
939 name.c_str());
940 // FIXME maybe make a new file and save the current profile there
941 } else {
942 wxFileName file;
943 file.Assign(GetProfileStorageFolder(), profileFilename);
944 wxASSERT( file.IsOk() );
945 wxFFileOutputStream configOutput(file.GetFullPath());
946 toSave->Save(configOutput);
947 wxLogDebug(wxT_2("Profile '%s' saved to '%s'"),
948 name.c_str(), file.GetFullPath().c_str());
949 }
950 }
951
952 /** Saves the current profile to disk, regardless of whether it has unsaved changes.
953 Does not affect the global profile or any other profile. */
954 void ProMan::SaveCurrentProfile(bool quiet) {
955 wxConfigBase* configbase = wxFileConfig::Get(false);
956 if ( configbase == NULL ) {
957 wxLogError(wxT_2("There is no global file config."));
958 return;
959 }
960 wxFileConfig* config = dynamic_cast<wxFileConfig*>(configbase);
961 if ( config != NULL ) {
962 SaveProfileToDisk(config, this->currentProfileName.c_str());
963 this->ResetPrivateCopy();
964 if (!quiet) {
965 wxLogStatus(_("Profile '%s' saved"), this->currentProfileName.c_str());
966 }
967 wxLogDebug(wxT_2("Current config%s saved."),
968 quiet ? wxT_2(" quietly") : wxT_2(""));
969 } else {
970 wxLogError(wxT_2("Configbase is not a wxFileConfig."));
971 }
972 }
973
974 /** Reverts any unsaved changes to the current profile. */
975 void ProMan::RevertCurrentProfile() {
976 ClearConfig(*(this->currentProfile));
977 CopyConfig(*(this->privateCopy), *(this->currentProfile));
978 }
979
980 bool ProMan::HasUnsavedChanges() {
981 return !AreConfigsEqual(*(this->currentProfile), *(this->privateCopy));
982 }
983
984 wxString ProMan::GetCurrentName() {
985 return this->currentProfileName;
986 }
987
988 /** Implements the literal switch to another profile.
989 Does not cause prompts and may destroy data if autosave is not on.
990 */
991 bool ProMan::SwitchTo(wxString name) {
992 if ( this->profiles.find(name) == this->profiles.end() ) {
993 return false;
994 } else {
995 if (this->currentProfile != NULL && this->HasUnsavedChanges()) {
996 if (this->isAutoSaving) {
997 wxLogDebug(wxT_2("Auto saving current profile %s before switching profiles"),
998 this->currentProfileName.c_str());
999 this->SaveCurrentProfile();
1000 } else {
1001 wxLogDebug(wxT_2("Reverting unsaved changes to current profile %s before switching"),
1002 this->currentProfileName.c_str());
1003 this->RevertCurrentProfile();
1004 }
1005 }
1006 this->currentProfileName = name;
1007 this->currentProfile = this->profiles.find(name)->second;
1008 wxFileConfig::Set(this->currentProfile);
1009 if ( !(ProMan::flags & NoUpdateLastProfile) )
1010 this->globalProfile->Write(GBL_CFG_MAIN_LASTPROFILE, name);
1011 this->ResetPrivateCopy();
1012 // TestConfigFunctions(*this->currentProfile); // remove after testing on all platforms
1013 this->GenerateCurrentProfileChangedEvent();
1014 return true;
1015 }
1016 }
1017
1018 /** Creates a profile from a fullyqualified path. */
1019 bool ProMan::CreateProfile(const wxString& newProfileName, const wxFileName& sourceFile)
1020 {
1021 wxLogDebug(wxT_2("Importing profile in '%s' as '%s'"),
1022 sourceFile.GetFullPath().c_str(), newProfileName.c_str());
1023 wxFileConfig *sourceConfig = LoadProfileFromFile(sourceFile);
1024
1025 return this->CreateProfile(newProfileName, sourceConfig);
1026 }
1027
1028 /** Creates a profile named newProfileName from the contents of sourceConfig.
1029 If sourceConfig is NULL then the newProfile is created blank. */
1030 bool ProMan::CreateProfile(const wxString& newProfileName, const wxFileConfig *sourceConfig)
1031 {
1032 if (this->DoesProfileExist(newProfileName)) {
1033 wxLogWarning(_("New profile '%s' already exists!"), newProfileName.c_str());
1034 return false;
1035 }
1036
1037 if (!this->CreateNewProfile(newProfileName)) {
1038 wxLogWarning(wxT_2("New profile creation failed."));
1039 return false;
1040 }
1041
1042 if (sourceConfig != NULL)
1043 {
1044 /* We just created this profile it had better exist */
1045 wxFileConfig* newProfileConfig = this->profiles[newProfileName];
1046 wxCHECK_MSG(newProfileConfig != NULL, false, wxT_2("Create returned true but did not create profile"));
1047
1048 #if PROFILE_DEBUGGING
1049 wxLogDebug(wxT_2("contents of new profile '%s' before clone:"), newProfileName.c_str());
1050 LogConfigContents(*newProfileConfig);
1051 #endif
1052
1053 CopyConfig(*sourceConfig, *newProfileConfig, false);
1054 SaveProfileToDisk(newProfileConfig, newProfileName);
1055
1056 #if PROFILE_DEBUGGING
1057 wxLogDebug(wxT_2("contents of new profile '%s' after clone:"), newProfileName.c_str());
1058 LogConfigContents(*newProfileConfig);
1059 wxLogDebug(wxT_2("contents of cloned from profile '%s' after clone:"), cloneFromProfileName.c_str());
1060 LogConfigContents(*cloneFromProfileConfig);
1061 #endif
1062
1063 }
1064
1065 this->GenerateChangeEvent();
1066 return true;
1067 }
1068
1069 /** Creates a profile by name. If the second argument is non-empty and is the name
1070 of an existing profile, its settings/flags will be copied over to the new profile.
1071 Returns true on success. */
1072 bool ProMan::CreateProfile(const wxString& newProfileName, const wxString& cloneFromProfileName) {
1073 wxFileConfig *cloneSource = NULL;
1074
1075 if (cloneFromProfileName.IsEmpty())
1076 {
1077 wxLogDebug(wxT_2("Creating blank profile '%s'"), newProfileName.c_str());
1078 }
1079 else
1080 {
1081 wxLogDebug(wxT_2("Cloning original profile (%s) to '%s'"),
1082 cloneFromProfileName.c_str(), newProfileName.c_str());
1083 if (!this->DoesProfileExist(cloneFromProfileName))
1084 {
1085 wxLogWarning(_("Profile to clone from '%s' does not exist!"), cloneFromProfileName.c_str());
1086 return false;
1087 }
1088 cloneSource = this->profiles[cloneFromProfileName];
1089 wxCHECK_MSG( cloneSource != NULL, false,
1090 wxString::Format(wxT_2("Cannot find profile '%s' from which to clone"),
1091 cloneFromProfileName.c_str()) );
1092 }
1093
1094 return this->CreateProfile(newProfileName, cloneSource);
1095 }
1096
1097 bool ProMan::DeleteProfile(wxString name) {
1098 wxLogDebug(wxT_2("Deleting profile: %s"), name.c_str());
1099 if ( name == ProMan::DEFAULT_PROFILE_NAME ) {
1100 wxLogWarning(_("Cannot delete 'Default' profile."));
1101 return false;
1102 }
1103 if ( name == this->currentProfileName ) {
1104 wxLogInfo(
1105 _("Deleting current profile. Switching to '%s' profile"),
1106 ProMan::DEFAULT_PROFILE_NAME.c_str());
1107 this->SwitchTo(ProMan::DEFAULT_PROFILE_NAME);
1108 }
1109 if ( this->DoesProfileExist(name) ) {
1110 wxLogDebug(wxT_2(" Profile exists"));
1111 wxFileConfig* config = this->profiles[name];
1112
1113 wxString filename;
1114 if ( !config->Read(PRO_CFG_MAIN_FILENAME, &filename) ) {
1115 wxLogWarning(wxT_2("Unable to get filename to delete %s"), name.c_str());
1116 return false;
1117 }
1118
1119 wxFileName file;
1120 file.Assign(GetProfileStorageFolder(), filename);
1121
1122 if ( file.FileExists() ) {
1123 wxLogDebug(wxT_2(" Backing file exists"));
1124 if ( wxRemoveFile(file.GetFullPath()) ) {
1125 this->profiles.erase(this->profiles.find(name));
1126 delete config;
1127
1128 wxLogMessage(_("Profile '%s' deleted."), name.c_str());
1129 this->GenerateChangeEvent();
1130 return true;
1131 } else {
1132 wxLogWarning(_("Unable to delete file for profile '%s'"), name.c_str());
1133 }
1134 } else {
1135 wxLogWarning(_("Backing file (%s) for profile '%s' does not exist"), file.GetFullPath().c_str(), name.c_str());
1136 }
1137 } else {
1138 wxLogWarning(_("Profile %s does not exist. Cannot delete."), name.c_str());
1139 }
1140 return false;
1141 }
1142
1143 // the config manipulation functions are adapted from CopyEntriesRecursive and CopyEntry
1144 // from http://audacity.googlecode.com/svn/audacity-src/trunk/src/Prefs.cpp SVN r11245
1145 /** copies the contents of one wxConfigBase to another wxConfigBase.
1146 The wxWindows group is not copied, if it exists. If includeMainGroup is true, then
1147 the contents of the "main" group (profile-specific information, such as name and filename)
1148 are copied as well, otherwise they are not copied. */
1149 void ProMan::CopyConfig(const wxConfigBase& in_src,
1150 wxConfigBase& dest,
1151 const bool includeMainGroup,
1152 const wxString path) {
1153 wxString entryName;
1154 long entryIndex;
1155 bool entryKeepGoing;
1156
1157 /* BUGNOTE - This is possibly not safe, but because the following code
1158 uses non const functions and restores what it does mutate this
1159 should be safe. */
1160 wxConfigBase& src = const_cast<wxConfigBase&>(in_src);
1161
1162 entryKeepGoing = src.GetFirstEntry(entryName, entryIndex);
1163 while (entryKeepGoing) {
1164 CopyConfigEntry(src, dest, path, entryName);
1165 entryKeepGoing = src.GetNextEntry(entryName, entryIndex);
1166 }
1167
1168 wxString groupName;
1169 long groupIndex;
1170 bool groupKeepGoing;
1171
1172 groupKeepGoing = src.GetFirstGroup(groupName, groupIndex);
1173 while (groupKeepGoing) {
1174 if (groupName != _T("wxWindows") && (includeMainGroup || groupName != _T("main"))) {
1175 wxString subPath = path + groupName + _T("/");
1176 src.SetPath(subPath);
1177 CopyConfig(src, dest, includeMainGroup, subPath);
1178 src.SetPath(path);
1179 }
1180 groupKeepGoing = src.GetNextGroup(groupName, groupIndex);
1181 }
1182 }
1183
1184 // assumed that cfg1's path is already at path
1185 // and that cfg1 has an entry at /path/entry
1186 /** Helper function for CopyConfig(). Copies a single config entry. */
1187 void ProMan::CopyConfigEntry(const wxConfigBase& src,
1188 wxConfigBase& dest,
1189 const wxString path,
1190 const wxString entry) {
1191 switch(src.GetEntryType(entry)) {
1192 case wxConfigBase::Type_Unknown:
1193 case wxConfigBase::Type_String: {
1194 wxString value = src.Read(entry, wxEmptyString);
1195 dest.Write(path + entry, value);
1196 break;
1197 }
1198 case wxConfigBase::Type_Boolean: {
1199 bool value = false;
1200 src.Read(entry, &value, value);
1201 dest.Write(path + entry, value);
1202 break;
1203 }
1204 case wxConfigBase::Type_Integer: {
1205 long value = false;
1206 src.Read(entry, &value, value);
1207 dest.Write(path + entry, value);
1208 break;
1209 }
1210 case wxConfigBase::Type_Float: {
1211 double value = false;
1212 src.Read(entry, &value, value);
1213 dest.Write(path + entry, value);
1214 break;
1215 }
1216 }
1217 }
1218
1219 /** Clears the contents of the provided config. */
1220 void ProMan::ClearConfig(wxConfigBase& cfg) {
1221 wxString entryName;
1222 long entryIndex;
1223 bool entryKeepGoing;
1224
1225 wxArrayString entries, groups;
1226
1227 entryKeepGoing = cfg.GetFirstEntry(entryName, entryIndex);
1228 while (entryKeepGoing) {
1229 entries.Add(entryName);
1230 entryKeepGoing = cfg.GetNextEntry(entryName, entryIndex);
1231 }
1232
1233 wxString groupName;
1234 long groupIndex;
1235 bool groupKeepGoing;
1236
1237 groupKeepGoing = cfg.GetFirstGroup(groupName, groupIndex);
1238 while (groupKeepGoing) {
1239 groups.Add(groupName);
1240 groupKeepGoing = cfg.GetNextGroup(groupName, groupIndex);
1241 }
1242
1243 for (int i = 0, n = entries.GetCount(); i < n; ++i) {
1244 cfg.DeleteEntry(entries.Item(i));
1245 }
1246
1247 for (int i = 0, n = groups.GetCount(); i < n; ++i) {
1248 cfg.DeleteGroup(groups.Item(i));
1249 }
1250 }
1251
1252 /** Tests whether two configs are equal, where two configs are defined as
1253 equal if they have the same entries and groups with the same values,
1254 except that the wxWindows group is ignored, if it exists. */
1255 bool ProMan::AreConfigsEqual(wxConfigBase& cfg1, wxConfigBase& cfg2) {
1256 return IsConfigSubset(cfg1, cfg2) && IsConfigSubset(cfg2, cfg1);
1257 }
1258
1259 /** Tests whether the first config is a subset of the second, where subset
1260 means that the first config's entries and groups appear in the second config
1261 in the same structure and with the same values, with the exception
1262 that the wxWindows group is ignored if it exists.*/
1263 bool ProMan::IsConfigSubset(wxConfigBase& cfg1,
1264 wxConfigBase& cfg2,
1265 const wxString path) {
1266 wxString entryName;
1267 long entryIndex;
1268 bool entryKeepGoing;
1269
1270 entryKeepGoing = cfg1.GetFirstEntry(entryName, entryIndex);
1271 while (entryKeepGoing) {
1272 if (!AreEntriesEqual(cfg1, cfg2, path, entryName)) {
1273 return false;
1274 }
1275 entryKeepGoing = cfg1.GetNextEntry(entryName, entryIndex);
1276 }
1277
1278 wxString groupName;
1279 long groupIndex;
1280 bool groupKeepGoing;
1281
1282 groupKeepGoing = cfg1.GetFirstGroup(groupName, groupIndex);
1283 while (groupKeepGoing) {
1284 if (groupName != _T("wxWindows")) {
1285 wxString subPath = path + groupName + _T("/");
1286 cfg1.SetPath(subPath);
1287 if (!IsConfigSubset(cfg1, cfg2, subPath)) {
1288 cfg1.SetPath(path); // fix the path before returning
1289 return false;
1290 }
1291 cfg1.SetPath(path);
1292 }
1293 groupKeepGoing = cfg1.GetNextGroup(groupName, groupIndex);
1294 }
1295 return true;
1296 }
1297
1298 // assumed that cfg1's path is already at path
1299 /** Helper function for AreConfigsEqual().
1300 Tests whether an entry exists in two configs and if so,
1301 whether the value stored at the entry in each is equal.*/
1302 bool ProMan::AreEntriesEqual(const wxConfigBase& cfg1,
1303 const wxConfigBase& cfg2,
1304 const wxString path,
1305 const wxString entry) {
1306 switch(cfg1.GetEntryType(entry)) {
1307 case wxConfigBase::Type_Unknown:
1308 case wxConfigBase::Type_String: {
1309 wxString value1, value2;
1310 if ((!cfg1.Read(entry, &value1)) || (!cfg2.Read(path + entry, &value2))) {
1311 return false;
1312 } else {
1313 return value1 == value2;
1314 }
1315 break;
1316 }
1317 case wxConfigBase::Type_Boolean: {
1318 bool value1, value2;
1319 if ((!cfg1.Read(entry, &value1)) || (!cfg2.Read(path + entry, &value2))) {
1320 return false;
1321 } else {
1322 return value1 == value2;
1323 }
1324 break;
1325 }
1326 case wxConfigBase::Type_Integer: {
1327 long value1, value2;
1328 if ((!cfg1.Read(entry, &value1)) || (!cfg2.Read(path + entry, &value2))) {
1329 return false;
1330 } else {
1331 return value1 == value2;
1332 }
1333 break;
1334 }
1335 case wxConfigBase::Type_Float: {
1336 double value1, value2;
1337 if ((!cfg1.Read(entry, &value1)) || (!cfg2.Read(path + entry, &value2))) {
1338 return false;
1339 } else {
1340 return value1 == value2;
1341 }
1342 break;
1343 }
1344 default:
1345 wxLogWarning(_T("unknown entry type %d"), cfg1.GetEntryType(entry));
1346 return false;
1347 break;
1348 }
1349 wxCHECK_MSG(false, false, _T("escaped switch statement in ProMan::AreEntriesEqual"));
1350 }
1351
1352 /** Debugging function that prints contents of provided config to log. */
1353 void ProMan::LogConfigContents(wxConfigBase& cfg, const wxString path, const bool includeWxWindows) {
1354 wxString entryName;
1355 long entryIndex;
1356 bool entryKeepGoing;
1357
1358 entryKeepGoing = cfg.GetFirstEntry(entryName, entryIndex);
1359 while (entryKeepGoing) {
1360 wxLogDebug(_T(" %s%s = %s"),
1361 path.c_str(), entryName.c_str(), cfg.Read(entryName, _T("ENTRY_NOT_FOUND")).c_str());
1362 entryKeepGoing = cfg.GetNextEntry(entryName, entryIndex);
1363 }
1364
1365 wxString groupName;
1366 long groupIndex;
1367 bool groupKeepGoing;
1368
1369 groupKeepGoing = cfg.GetFirstGroup(groupName, groupIndex);
1370 while (groupKeepGoing) {
1371 if (includeWxWindows) {
1372 wxString subPath = path + groupName + _T("/");
1373 cfg.SetPath(subPath);
1374 LogConfigContents(cfg, subPath);
1375 cfg.SetPath(path);
1376 } else if (groupName != _T("wxWindows")) {
1377 wxString subPath = path + groupName + _T("/");
1378 cfg.SetPath(subPath);
1379 LogConfigContents(cfg, subPath);
1380 cfg.SetPath(path);
1381 }
1382 groupKeepGoing = cfg.GetNextGroup(groupName, groupIndex);
1383 }
1384 }
1385
1386 /** Start of a test case for config manipulation functions */
1387 void ProMan::TestConfigFunctions(wxConfigBase& src) {
1388 wxLogDebug(_T("contents of source config:"));
1389 LogConfigContents(src);
1390
1391 wxString tempFileName = wxFileName::CreateTempFileName(_T("wxLtest"));
1392 wxLogDebug(_T("created temp file '%s'"), tempFileName.c_str());
1393 wxFFileInputStream instream(tempFileName);
1394 wxFileConfig* dest = new wxFileConfig(instream);
1395
1396 wxLogDebug(_T("initial contents of dest config:"));
1397 LogConfigContents(*dest);
1398
1399 wxLogDebug(_T("is src a subset of dest? %s"), IsConfigSubset(src, *dest) ? _T("true") : _T("false"));
1400 wxLogDebug(_T("is dest a subset of src? %s"), IsConfigSubset(*dest, src) ? _T("true") : _T("false"));
1401 wxLogDebug(_T("are configs src and dest equal? %s"), AreConfigsEqual(*dest, src) ? _T("true") : _T("false"));
1402
1403 wxLogDebug(_T("copying source config to dest config"));
1404 CopyConfig(src, *dest);
1405
1406 wxLogDebug(_T("contents of dest config after copying:"));
1407 LogConfigContents(*dest);
1408
1409 wxLogDebug(_T("is src a subset of dest? %s"), IsConfigSubset(src, *dest) ? _T("true") : _T("false"));
1410 wxLogDebug(_T("is dest a subset of src? %s"), IsConfigSubset(*dest, src) ? _T("true") : _T("false"));
1411 wxLogDebug(_T("are configs src and dest equal? %s"), AreConfigsEqual(*dest, src) ? _T("true") : _T("false"));
1412
1413 wxLogDebug(_T("deleting entry %s from dest"),
1414 PRO_CFG_LIGHTING_PRESET.c_str());
1415 dest->DeleteEntry(PRO_CFG_LIGHTING_PRESET, true);
1416
1417 wxLogDebug(_T("contents of dest config after entry deletion:"));
1418 LogConfigContents(*dest);
1419
1420 wxLogDebug(_T("is src a subset of dest? %s"), IsConfigSubset(src, *dest) ? _T("true") : _T("false"));
1421 wxLogDebug(_T("is dest a subset of src? %s"), IsConfigSubset(*dest, src) ? _T("true") : _T("false"));
1422 wxLogDebug(_T("are configs src and dest equal? %s"), AreConfigsEqual(*dest, src) ? _T("true") : _T("false"));
1423
1424 wxLogDebug(_T("clearing dest config"));
1425 wxLogDebug(_T("before clearing, dest has %ld entries and %ld groups"),
1426 dest->GetNumberOfEntries(true), dest->GetNumberOfGroups(true));
1427
1428 ClearConfig(*dest);
1429
1430 wxLogDebug(_T("contents of dest config after clearing:"));
1431 LogConfigContents(*dest);
1432
•1433 wxLogDebug(_T("after clearing, dest has %u entries and %u groups"),
1434 static_cast<unsigned>(dest->GetNumberOfEntries(true)), static_cast<unsigned>(dest->GetNumberOfGroups(true)));
1435
1436 wxLogDebug(_T("recopying src to dest"));
1437
1438 CopyConfig(src, *dest);
1439
1440 wxLogDebug(_T("contents of dest config after second copying:"));
1441 LogConfigContents(*dest);
1442
1443 wxLogDebug(_T("is src a subset of dest? %s"), IsConfigSubset(src, *dest) ? _T("true") : _T("false"));
1444 wxLogDebug(_T("is dest a subset of src? %s"), IsConfigSubset(*dest, src) ? _T("true") : _T("false"));
1445 wxLogDebug(_T("are configs src and dest equal? %s"), AreConfigsEqual(*dest, src) ? _T("true") : _T("false"));
1446
1447 const wxString FAKE_ENTRY = _T("/foo/bar");
1448 const wxString FAKE_VALUE = _T("blah");
1449
1450 wxLogDebug(_T("adding entry %s to dest"), FAKE_ENTRY.c_str());
1451 dest->Write(FAKE_ENTRY, FAKE_VALUE);
1452
1453 wxLogDebug(_T("contents of dest config after entry addition:"));
1454 LogConfigContents(*dest);
1455
1456 wxLogDebug(_T("is src a subset of dest? %s"), IsConfigSubset(src, *dest) ? _T("true") : _T("false"));
1457 wxLogDebug(_T("is dest a subset of src? %s"), IsConfigSubset(*dest, src) ? _T("true") : _T("false"));
1458 wxLogDebug(_T("are configs src and dest equal? %s"), AreConfigsEqual(*dest, src) ? _T("true") : _T("false"));
1459
1460 delete dest;
1461
1462 wxLogDebug(_T("config test complete."));
1463 }
1464
1465 /** Applies the current profile to the registry where
1466 Freespace 2 can read it. */
1467 ProMan::RegistryCodes ProMan::PushCurrentProfile() {
1468 if (this->currentProfile == NULL) {
1469 wxLogError(_T("PushCurrentProfile: attempt to push null current profile"));
1470 return ProMan::UnknownError;
1471 } else {
1472 return ProMan::PushProfile(this->currentProfile);
1473 }
1474 }
1475
1476 /** Applies the passed wxFileConfig profile to the registry where
1477 Freespace 2 can read it. */
1478 ProMan::RegistryCodes ProMan::PushProfile(wxFileConfig *cfg) {
1479 wxCHECK_MSG(cfg != NULL, ProMan::UnknownError, _T("ProMan::PushProfile given null wxFileConfig!"));
1480 #if IS_WIN32
1481 // check if binary supports configfile
1482 if (FlagListManager::GetFlagListManager()->GetBuildCaps() & FlagListManager::BUILD_CAPS_SDL) {
1483 return FilePushProfile(cfg);
1484 } else {
1485 return RegistryPushProfile(cfg);
1486 }
1487 #elif IS_LINUX || IS_APPLE
1488 return FilePushProfile(cfg);
1489 #else
1490 #error "One of IS_WIN32, IS_LINUX, IS_APPLE must evaluate to true"
1491 #endif
1492 }
1493
1494 /** Takes the settings in the registry and puts them into the wxFileConfig */
1495 ProMan::RegistryCodes ProMan::PullProfile(wxFileConfig *cfg) {
1496 wxCHECK_MSG(cfg != NULL, ProMan::UnknownError, _T("ProMan::PullProfile given null wxFileConfig!"));
1497 #if IS_WIN32
1498 // First try the config file
1499 ProMan::RegistryCodes code = FilePullProfile(cfg);
1500
1501 if (code == ProMan::InputFileDoesNotExist) {
1502 // No config file, use the registry
1503 return RegistryPullProfile(cfg);
1504 }
1505
1506 return code;
1507 #elif IS_LINUX || IS_APPLE
1508 return FilePullProfile(cfg);
1509 #else
1510 #error "One of IS_WIN32, IS_LINUX, IS_APPLE must evaluate to true"
1511 #endif
1512 }