Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/core2/src/orxonox/core/ConfigFileManager.cc @ 1023

Last change on this file since 1023 was 1023, checked in by landauf, 16 years ago

fixed bug, removed some debug output

File size: 15.2 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *
4 *
5 *   License notice:
6 *
7 *   This program is free software; you can redistribute it and/or
8 *   modify it under the terms of the GNU General Public License
9 *   as published by the Free Software Foundation; either version 2
10 *   of the License, or (at your option) any later version.
11 *
12 *   This program is distributed in the hope that it will be useful,
13 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 *   GNU General Public License for more details.
16 *
17 *   You should have received a copy of the GNU General Public License
18 *   along with this program; if not, write to the Free Software
19 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 *
21 *   Author:
22 *      Fabian 'x3n' Landau
23 *   Co-authors:
24 *      ...
25 *
26 */
27
28#include "ConfigFileManager.h"
29#include "ConsoleCommand.h"
30#include "Identifier.h"
31#include "util/Convert.h"
32#include "util/String.h"
33
34#define CONFIG_FILE_MAX_LINELENGHT 1024
35
36namespace orxonox
37{
38    ConsoleCommandShortcutExtern(reloadConfig, AccessLevel::None);
39    ConsoleCommandShortcutExtern(saveConfig, AccessLevel::None);
40    ConsoleCommandShortcutExtern(cleanConfig, AccessLevel::None);
41    ConsoleCommandShortcutExtern(loadSettings, AccessLevel::None);
42    ConsoleCommandShortcutExtern(loadKeybindings, AccessLevel::None);
43
44    void reloadConfig()
45    {
46        ConfigFileManager::getSingleton()->load();
47    }
48
49    void saveConfig()
50    {
51        ConfigFileManager::getSingleton()->save();
52    }
53
54    void cleanConfig()
55    {
56        ConfigFileManager::getSingleton()->clean();
57    }
58
59    void loadSettings(const std::string& filename)
60    {
61        ConfigFileManager::getSingleton()->setFile(CFT_Settings, filename);
62    }
63
64    void loadKeybindings(const std::string& filename)
65    {
66        ConfigFileManager::getSingleton()->setFile(CFT_Keybindings, filename);
67    }
68
69
70    //////////////////////////
71    // ConfigFileEntryValue //
72    //////////////////////////
73    std::string ConfigFileEntryValue::getFileEntry() const
74    {
75        if (this->additionalComment_ == "" || this->additionalComment_.size() == 0)
76            return (this->name_ + "=" + this->value_);
77        else
78            return (this->name_ + "=" + this->value_ + " " + this->additionalComment_);
79    }
80
81
82    ///////////////////////////////
83    // ConfigFileEntryArrayValue //
84    ///////////////////////////////
85    std::string ConfigFileEntryArrayValue::getFileEntry() const
86    {
87        if (this->additionalComment_ == "" || this->additionalComment_.size() == 0)
88            return (this->name_ + "[" + getConvertedValue<unsigned int, std::string>(this->index_, 0) + "]" + "=" + this->value_);
89        else
90            return (this->name_ + "[" + getConvertedValue<unsigned int, std::string>(this->index_, 0) + "]=" + this->value_ + " " + this->additionalComment_);
91    }
92
93
94    ///////////////////////
95    // ConfigFileSection //
96    ///////////////////////
97    ConfigFileSection::~ConfigFileSection()
98    {
99        for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); )
100            delete (*(it++));
101    }
102
103    std::string ConfigFileSection::getFileEntry() const
104    {
105        if (this->additionalComment_ == "" || this->additionalComment_.size() == 0)
106            return (this->name_);
107        else
108            return (this->name_ + " " + this->additionalComment_);
109    }
110
111    std::list<ConfigFileEntry*>::iterator ConfigFileSection::getEntryIterator(const std::string& name, const std::string& fallback)
112    {
113        for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
114            if ((*it)->getName() == name)
115                return it;
116
117        this->bUpdated_ = true;
118
119        return this->entries_.insert(this->entries_.end(), (ConfigFileEntry*)(new ConfigFileEntryValue(name, fallback)));
120    }
121
122    std::list<ConfigFileEntry*>::iterator ConfigFileSection::getEntryIterator(const std::string& name, unsigned int index, const std::string& fallback)
123    {
124        for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
125            if (((*it)->getName() == name) && ((*it)->getIndex() == index))
126                return it;
127
128        this->bUpdated_ = true;
129
130        if (index == 0)
131            return this->entries_.insert(this->entries_.end(), (ConfigFileEntry*)(new ConfigFileEntryArrayValue(name, index, fallback)));
132        else
133            return this->entries_.insert(this->getEntryIterator(name, index - 1), (ConfigFileEntry*)(new ConfigFileEntryArrayValue(name, index, fallback)));
134    }
135
136
137    ////////////////
138    // ConfigFile //
139    ////////////////
140    ConfigFile::~ConfigFile()
141    {
142        for (std::list<ConfigFileSection*>::iterator it = this->sections_.begin(); it != this->sections_.end(); )
143            delete (*(it++));
144    }
145
146    void ConfigFile::load()
147    {
148        // This creates the file if it's not existing
149        std::ofstream createFile;
150        createFile.open(this->filename_.c_str(), std::fstream::app);
151        createFile.close();
152
153        // Open the file
154        std::ifstream file;
155        file.open(this->filename_.c_str(), std::fstream::in);
156
157        if (!file.is_open())
158        {
159            COUT(1) << "An error occurred in ConfigFileManager.cc:" << std::endl;
160            COUT(1) << "Error: Couldn't open config-file \"" << this->filename_ << "\"." << std::endl;
161            return;
162        }
163
164        char linearray[CONFIG_FILE_MAX_LINELENGHT];
165
166        ConfigFileSection* newsection = 0;
167
168        while (file.good() && !file.eof())
169        {
170            file.getline(linearray, CONFIG_FILE_MAX_LINELENGHT);
171
172            std::string line = std::string(linearray);
173
174            std::string temp = getStripped(line);
175            if (!isEmpty(temp) && !isComment(temp))
176            {
177                unsigned int pos1 = line.find('[');
178                unsigned int pos2 = line.find(']');
179
180                if (pos1 != std::string::npos && pos2 != std::string::npos && pos2 > pos1 + 1)
181                {
182                    // New section
183                    std::string comment = temp.substr(pos2 + 1);
184                    if (isComment(comment))
185                        newsection = new ConfigFileSection(line.substr(pos1, pos2 - pos1 + 1), comment);
186                    else
187                        newsection = new ConfigFileSection(line.substr(pos1, pos2 - pos1 + 1));
188                    this->sections_.insert(this->sections_.end(), newsection);
189                    continue;
190                }
191            }
192
193            if (newsection != 0)
194            {
195                if (isComment(line))
196                {
197                    // New comment
198                    newsection->getEntries().insert(newsection->getEntries().end(), new ConfigFileEntryComment(removeTrailingWhitespaces(line)));
199                    continue;
200                }
201                else
202                {
203                    unsigned int pos1 = line.find('=');
204
205                    if (pos1 != std::string::npos && pos1 > 0)
206                    {
207                        // New entry
208                        unsigned int pos2 = line.find('[');
209                        unsigned int pos3 = line.find(']');
210
211                        std::string value = removeTrailingWhitespaces(line.substr(pos1 + 1));
212                        std::string comment = "";
213
214                        std::string betweenQuotes = getStringBetweenQuotes(value);
215                        if (value.size() > 0 && value[0] == '"' && betweenQuotes != "" && betweenQuotes.size() > 0)
216                        {
217                            value = betweenQuotes;
218                            if (line.size() > pos1 + 1 + betweenQuotes.size() + 2)
219                                comment = removeTrailingWhitespaces(getComment(line.substr(pos1 + 1 + betweenQuotes.size() + 2)));
220                        }
221                        else
222                        {
223                            unsigned int pos4 = getCommentPosition(line);
224                            value = removeTrailingWhitespaces(line.substr(pos1 + 1, pos4 - pos1 - 1));
225                            if (pos4 != std::string::npos)
226                                comment = removeTrailingWhitespaces(line.substr(pos4));
227                        }
228
229                        if (pos2 != std::string::npos && pos3 != std::string::npos && pos3 > pos2 + 1)
230                        {
231                            // There might be an array index
232                            unsigned int index = 0;
233                            if (ConvertValue(&index, line.substr(pos2 + 1, pos3 - pos2 - 1)))
234                            {
235                                // New array
236                                newsection->getEntries().insert(newsection->getEntries().end(), new ConfigFileEntryArrayValue(getStripped(line.substr(0, pos2)), index, value, comment));
237                                continue;
238                            }
239                        }
240
241                        // New value
242                        newsection->getEntries().insert(newsection->getEntries().end(), new ConfigFileEntryValue(getStripped(line.substr(0, pos1)), value, comment));
243                        continue;
244                    }
245                }
246            }
247        }
248
249        file.close();
250
251        COUT(3) << "Loaded config file \"" << this->filename_ << "\"." << std::endl;
252
253        // Save the file in case something changed (like stripped whitespaces)
254        this->save();
255    }
256
257    void ConfigFile::save() const
258    {
259        std::ofstream file;
260        file.open(this->filename_.c_str(), std::fstream::out);
261        file.setf(std::ios::fixed, std::ios::floatfield);
262        file.precision(6);
263
264        if (!file.is_open())
265        {
266            COUT(1) << "An error occurred in ConfigFileManager.cc:" << std::endl;
267            COUT(1) << "Error: Couldn't open config-file \"" << this->filename_ << "\"." << std::endl;
268            return;
269        }
270
271        for (std::list<ConfigFileSection*>::const_iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
272        {
273            file << (*it)->getFileEntry() << std::endl;
274
275            for (std::list<ConfigFileEntry*>::const_iterator it_entries = (*it)->getEntriesBegin(); it_entries != (*it)->getEntriesEnd(); ++it_entries)
276            {
277                file << (*it_entries)->getFileEntry() << std::endl;
278            }
279
280            file << std::endl;
281        }
282
283        file.close();
284
285        COUT(4) << "Saved config file \"" << this->filename_ << "\"." << std::endl;
286    }
287
288    void ConfigFile::clean()
289    {
290    }
291
292    ConfigFileSection* ConfigFile::getSection(const std::string& section)
293    {
294        for (std::list<ConfigFileSection*>::iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
295            if ((*it)->getName() == section)
296                return (*it);
297
298        this->bUpdated_ = true;
299
300        return (*this->sections_.insert(this->sections_.begin(), new ConfigFileSection(section)));
301    }
302
303    void ConfigFile::saveIfUpdated()
304    {
305        bool sectionsUpdated = false;
306
307        for (std::list<ConfigFileSection*>::iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
308        {
309            if ((*it)->bUpdated_)
310            {
311                sectionsUpdated = true;
312                (*it)->bUpdated_ = false;
313            }
314        }
315
316        if (this->bUpdated_ || sectionsUpdated)
317        {
318            this->bUpdated_ = false;
319            this->save();
320        }
321    }
322
323
324    ///////////////////////
325    // ConfigFileManager //
326    ///////////////////////
327    ConfigFileManager::ConfigFileManager()
328    {
329        this->setFile(CFT_Settings, DEFAULT_CONFIG_FILE);
330    }
331
332    ConfigFileManager::~ConfigFileManager()
333    {
334        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); )
335            delete (*(it++)).second;
336    }
337
338    ConfigFileManager* ConfigFileManager::getSingleton()
339    {
340        static ConfigFileManager instance;
341        return (&instance);
342    }
343
344    void ConfigFileManager::setFile(ConfigFileType type, const std::string& filename)
345    {
346        std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.find(type);
347        if (it != this->configFiles_.end())
348            if ((*it).second != 0)
349                delete (*it).second;
350
351        this->configFiles_[type] = new ConfigFile(this->getFilePath(filename));
352        this->load(type);
353    }
354
355    void ConfigFileManager::load()
356    {
357        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
358            (*it).second->load();
359
360        this->updateConfigValues();
361    }
362
363    void ConfigFileManager::save()
364    {
365        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
366            (*it).second->save();
367    }
368
369    void ConfigFileManager::clean()
370    {
371        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
372            this->clean((*it).first);
373    }
374
375    void ConfigFileManager::load(ConfigFileType type)
376    {
377        this->getFile(type)->load();
378        this->updateConfigValues(type);
379    }
380
381    void ConfigFileManager::save(ConfigFileType type)
382    {
383        this->getFile(type)->save();
384    }
385
386    void ConfigFileManager::clean(ConfigFileType type)
387    {
388        this->getFile(type)->clean();
389        this->getFile(type)->save();
390    }
391
392    void ConfigFileManager::updateConfigValues() const
393    {
394        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
395            this->updateConfigValues((*it).first);
396    }
397
398    void ConfigFileManager::updateConfigValues(ConfigFileType type) const
399    {
400        if (type == CFT_Settings)
401        {
402            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getIdentifierMapBegin(); it != Identifier::getIdentifierMapEnd(); ++it)
403                if ((*it).second->hasConfigValues() /* && (*it).second != ClassManager<KeyBinder>::getIdentifier()*/)
404                    (*it).second->updateConfigValues();
405        }
406        else if (type == CFT_Keybindings)
407        {
408            // todo
409        }
410    }
411
412    ConfigFile* ConfigFileManager::getFile(ConfigFileType type)
413    {
414        std::map<ConfigFileType, ConfigFile*>::iterator it = this->configFiles_.find(type);
415        if (it != this->configFiles_.end())
416            return (*it).second;
417
418        if (type == CFT_Settings)
419            return this->configFiles_[type] = new ConfigFile(DEFAULT_CONFIG_FILE);
420        else
421            return this->configFiles_[type] = new ConfigFile("");
422    }
423
424    std::string ConfigFileManager::getFilePath(const std::string& name) const
425    {
426        return name;
427    }
428}
Note: See TracBrowser for help on using the repository browser.