Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/console/src/core/ConfigFileManager.cc @ 1434

Last change on this file since 1434 was 1434, checked in by landauf, 17 years ago

autocompletion is almost done

File size: 20.7 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Fabian 'x3n' Landau
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29#include "ConfigFileManager.h"
30#include "ConfigValueContainer.h"
31#include "ConsoleCommand.h"
32#include "Identifier.h"
33#include "util/Convert.h"
34#include "util/String.h"
35
36#define CONFIG_FILE_MAX_LINELENGHT 1024
37
38namespace orxonox
39{
40    SetConsoleCommandShortcutExtern(config).setArgumentCompleter(0, autocompletion::configvalueclasses()).setArgumentCompleter(1, autocompletion::configvalues()).setArgumentCompleter(2, autocompletion::configvalue());
41    SetConsoleCommandShortcutExtern(tconfig);
42    SetConsoleCommandShortcutExtern(reloadConfig);
43    SetConsoleCommandShortcutExtern(cleanConfig);
44    SetConsoleCommandShortcutExtern(loadSettings);
45    SetConsoleCommandShortcutExtern(loadKeybindings);
46
47    bool config(const std::string& classname, const std::string& varname, const std::string& value)
48    {
49std::cout << "10a_1\n";
50        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
51        if (identifier != Identifier::getLowercaseIdentifierMapEnd())
52        {
53std::cout << "10a_2\n";
54            std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
55            if (variable != (*identifier).second->getLowercaseConfigValueMapEnd())
56            {
57std::cout << "10a_3\n";
58                return (*variable).second->tset(value);
59            }
60        }
61        return false;
62    }
63
64    bool tconfig(const std::string& classname, const std::string& varname, const std::string& value)
65    {
66std::cout << "10b_1\n";
67        std::map<std::string, Identifier*>::const_iterator identifier = Identifier::getLowercaseIdentifierMap().find(getLowercase(classname));
68        if (identifier != Identifier::getLowercaseIdentifierMapEnd())
69        {
70std::cout << "10b_2\n";
71            std::map<std::string, ConfigValueContainer*>::const_iterator variable = (*identifier).second->getLowercaseConfigValueMap().find(getLowercase(varname));
72            if (variable != (*identifier).second->getLowercaseConfigValueMapEnd())
73            {
74std::cout << "10b_3\n";
75                return (*variable).second->tset(value);
76            }
77        }
78        return false;
79    }
80
81    void reloadConfig()
82    {
83        ConfigFileManager::getSingleton()->load();
84    }
85
86    void cleanConfig()
87    {
88        ConfigFileManager::getSingleton()->clean(false);
89    }
90
91    void loadSettings(const std::string& filename)
92    {
93        ConfigFileManager::getSingleton()->setFile(CFT_Settings, filename, false);
94    }
95
96    void loadKeybindings(const std::string& filename)
97    {
98        ConfigFileManager::getSingleton()->setFile(CFT_Keybindings, filename);
99    }
100
101
102    //////////////////////////
103    // ConfigFileEntryValue //
104    //////////////////////////
105
106    void ConfigFileEntryValue::setValue(const std::string& value)
107    {
108        if (!this->bString_)
109            this->value_ = value;
110        else
111            this->value_ = "\"" + addSlashes(stripEnclosingQuotes(value)) + "\"";
112    }
113
114    std::string ConfigFileEntryValue::getValue() const
115    {
116        if (!this->bString_)
117            return this->value_;
118        else
119            return removeSlashes(stripEnclosingQuotes(this->value_));
120    }
121
122    std::string ConfigFileEntryValue::getFileEntry() const
123    {
124        if (this->additionalComment_ == "" || this->additionalComment_.size() == 0)
125            return (this->name_ + "=" + this->value_);
126        else
127            return (this->name_ + "=" + this->value_ + " " + this->additionalComment_);
128    }
129
130
131    ///////////////////////////////
132    // ConfigFileEntryVectorValue //
133    ///////////////////////////////
134    std::string ConfigFileEntryVectorValue::getFileEntry() const
135    {
136        if (this->additionalComment_ == "" || this->additionalComment_.size() == 0)
137            return (this->name_ + "[" + getConvertedValue<unsigned int, std::string>(this->index_, "0") + "]" + "=" + this->value_);
138        else
139            return (this->name_ + "[" + getConvertedValue<unsigned int, std::string>(this->index_, "0") + "]=" + this->value_ + " " + this->additionalComment_);
140    }
141
142
143    ///////////////////////
144    // ConfigFileSection //
145    ///////////////////////
146    ConfigFileSection::~ConfigFileSection()
147    {
148        for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); )
149            delete (*(it++));
150    }
151
152    void ConfigFileSection::deleteVectorEntries(const std::string& name, unsigned int startindex)
153    {
154        for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); )
155        {
156            if (((*it)->getName() == name) && ((*it)->getIndex() >= startindex))
157            {
158                delete (*it);
159                this->entries_.erase(it++);
160            }
161            else
162            {
163                ++it;
164            }
165        }
166    }
167
168    unsigned int ConfigFileSection::getVectorSize(const std::string& name)
169    {
170        unsigned int size = 0;
171        for (std::list<ConfigFileEntry*>::const_iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
172            if ((*it)->getName() == name)
173                if ((*it)->getIndex() > size)
174                    size = (*it)->getIndex();
175        return (size + 1);
176    }
177
178    std::string ConfigFileSection::getFileEntry() const
179    {
180        if (this->additionalComment_ == "" || this->additionalComment_.size() == 0)
181            return ("[" + this->name_ + "]");
182        else
183            return ("[" + this->name_ + "] " + this->additionalComment_);
184    }
185
186    std::list<ConfigFileEntry*>::iterator ConfigFileSection::getEntryIterator(const std::string& name, const std::string& fallback, bool bString)
187    {
188        for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
189        {
190            if ((*it)->getName() == name)
191            {
192                (*it)->setString(bString);
193                return it;
194            }
195        }
196
197        this->bUpdated_ = true;
198
199        return this->entries_.insert(this->entries_.end(), (ConfigFileEntry*)(new ConfigFileEntryValue(name, fallback, bString)));
200    }
201
202    std::list<ConfigFileEntry*>::iterator ConfigFileSection::getEntryIterator(const std::string& name, unsigned int index, const std::string& fallback, bool bString)
203    {
204        for (std::list<ConfigFileEntry*>::iterator it = this->entries_.begin(); it != this->entries_.end(); ++it)
205        {
206            if (((*it)->getName() == name) && ((*it)->getIndex() == index))
207            {
208                (*it)->setString(bString);
209                return it;
210            }
211        }
212
213        this->bUpdated_ = true;
214
215        if (index == 0)
216            return this->entries_.insert(this->entries_.end(), (ConfigFileEntry*)(new ConfigFileEntryVectorValue(name, index, fallback, bString)));
217        else
218            return this->entries_.insert(++this->getEntryIterator(name, index - 1, "", bString), (ConfigFileEntry*)(new ConfigFileEntryVectorValue(name, index, fallback, bString)));
219    }
220
221
222    ////////////////
223    // ConfigFile //
224    ////////////////
225    ConfigFile::~ConfigFile()
226    {
227        for (std::list<ConfigFileSection*>::iterator it = this->sections_.begin(); it != this->sections_.end(); )
228            delete (*(it++));
229    }
230
231    void ConfigFile::load(bool bCreateIfNotExisting)
232    {
233        if (bCreateIfNotExisting)
234        {
235            // This creates the default config file if it's not existing
236            std::ofstream createFile;
237            createFile.open(this->filename_.c_str(), std::fstream::app);
238            createFile.close();
239        }
240
241        // Open the file
242        std::ifstream file;
243        file.open(this->filename_.c_str(), std::fstream::in);
244
245        if (!file.is_open())
246        {
247            COUT(1) << "An error occurred in ConfigFileManager.cc:" << std::endl;
248            COUT(1) << "Error: Couldn't open config-file \"" << this->filename_ << "\"." << std::endl;
249            return;
250        }
251
252        char linearray[CONFIG_FILE_MAX_LINELENGHT];
253
254        ConfigFileSection* newsection = 0;
255
256        while (file.good() && !file.eof())
257        {
258            file.getline(linearray, CONFIG_FILE_MAX_LINELENGHT);
259
260            std::string line = std::string(linearray);
261
262            std::string temp = getStripped(line);
263            if (!isEmpty(temp) && !isComment(temp))
264            {
265                unsigned int   pos1 = temp.find('[');
266                if (pos1 == 0) pos1 = line.find('['); else pos1 = std::string::npos;
267                unsigned int   pos2 = line.find(']');
268
269                if (pos1 != std::string::npos && pos2 != std::string::npos && pos2 > pos1 + 1)
270                {
271                    // New section
272                    std::string comment = line.substr(pos2 + 1);
273                    if (isComment(comment))
274                        newsection = new ConfigFileSection(line.substr(pos1 + 1, pos2 - pos1 - 1), comment);
275                    else
276                        newsection = new ConfigFileSection(line.substr(pos1 + 1, pos2 - pos1 - 1));
277                    this->sections_.insert(this->sections_.end(), newsection);
278                    continue;
279                }
280            }
281
282            if (newsection != 0)
283            {
284                if (isComment(line))
285                {
286                    // New comment
287                    newsection->getEntries().insert(newsection->getEntries().end(), new ConfigFileEntryComment(removeTrailingWhitespaces(line)));
288                    continue;
289                }
290                else
291                {
292                    unsigned int pos1 = line.find('=');
293
294                    if (pos1 != std::string::npos && pos1 > 0)
295                    {
296                        // New entry
297                        unsigned int pos2 = line.find('[');
298                        unsigned int pos3 = line.find(']');
299                        unsigned int commentposition = getNextCommentPosition(line, pos1 + 1);
300                        while (isBetweenQuotes(line, commentposition))
301                        {
302                            commentposition = getNextCommentPosition(line, commentposition + 1);
303                        }
304                        std::string value = "", comment = "";
305                        if (commentposition == std::string::npos)
306                        {
307                            value = removeTrailingWhitespaces(line.substr(pos1 + 1));
308                        }
309                        else
310                        {
311                            value = removeTrailingWhitespaces(line.substr(pos1 + 1, commentposition - pos1 - 1));
312                            comment = removeTrailingWhitespaces(line.substr(commentposition));
313                        }
314
315                        if (pos2 != std::string::npos && pos3 != std::string::npos && pos3 > pos2 + 1)
316                        {
317                            // There might be an array index
318                            unsigned int index = 0;
319                            if (ConvertValue(&index, line.substr(pos2 + 1, pos3 - pos2 - 1)))
320                            {
321                                // New array
322                                std::list<ConfigFileEntry*>::iterator it = newsection->getEntryIterator(getStripped(line.substr(0, pos2)), index, value, false);
323                                (*it)->setValue(value);
324                                (*it)->setComment(comment);
325                                continue;
326                            }
327                        }
328
329                        // New value
330                        newsection->getEntries().insert(newsection->getEntries().end(), new ConfigFileEntryValue(getStripped(line.substr(0, pos1)), value, false, comment));
331                        continue;
332                    }
333                }
334            }
335        }
336
337        file.close();
338
339        COUT(3) << "Loaded config file \"" << this->filename_ << "\"." << std::endl;
340
341        // Save the file in case something changed (like stripped whitespaces)
342        this->save();
343    }
344
345    void ConfigFile::save() const
346    {
347        std::ofstream file;
348        file.open(this->filename_.c_str(), std::fstream::out);
349        file.setf(std::ios::fixed, std::ios::floatfield);
350        file.precision(6);
351
352        if (!file.is_open())
353        {
354            COUT(1) << "An error occurred in ConfigFileManager.cc:" << std::endl;
355            COUT(1) << "Error: Couldn't open config-file \"" << this->filename_ << "\"." << std::endl;
356            return;
357        }
358
359        for (std::list<ConfigFileSection*>::const_iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
360        {
361            file << (*it)->getFileEntry() << std::endl;
362
363            for (std::list<ConfigFileEntry*>::const_iterator it_entries = (*it)->getEntriesBegin(); it_entries != (*it)->getEntriesEnd(); ++it_entries)
364            {
365                file << (*it_entries)->getFileEntry() << std::endl;
366            }
367
368            file << std::endl;
369        }
370
371        file.close();
372
373        COUT(4) << "Saved config file \"" << this->filename_ << "\"." << std::endl;
374    }
375
376    void ConfigFile::clean(bool bCleanComments)
377    {
378        for (std::list<ConfigFileSection*>::iterator it1 = this->sections_.begin(); it1 != this->sections_.end(); )
379        {
380            std::map<std::string, Identifier*>::const_iterator it2 = Identifier::getIdentifierMap().find((*it1)->getName());
381            if (it2 != Identifier::getIdentifierMapEnd() && (*it2).second->hasConfigValues())
382            {
383                // The section exists, delete comment
384                if (bCleanComments)
385                    (*it1)->setComment("");
386                for (std::list<ConfigFileEntry*>::iterator it3 = (*it1)->entries_.begin(); it3 != (*it1)->entries_.end(); )
387                {
388                    std::map<std::string, ConfigValueContainer*>::const_iterator it4 = (*it2).second->getConfigValueMap().find((*it3)->getName());
389                    if (it4 != (*it2).second->getConfigValueMapEnd())
390                    {
391                        // The config-value exists, delete comment
392                        if (bCleanComments)
393                            (*it3)->setComment("");
394                        ++it3;
395                    }
396                    else
397                    {
398                        // The config-value doesn't exist
399                        delete (*it3);
400                        (*it1)->entries_.erase(it3++);
401                    }
402                }
403                ++it1;
404            }
405            else
406            {
407                // The section doesn't exist
408                delete (*it1);
409                this->sections_.erase(it1++);
410            }
411        }
412
413        // Save the file
414        this->save();
415    }
416
417    ConfigFileSection* ConfigFile::getSection(const std::string& section)
418    {
419        for (std::list<ConfigFileSection*>::iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
420            if ((*it)->getName() == section)
421                return (*it);
422
423        this->bUpdated_ = true;
424
425        return (*this->sections_.insert(this->sections_.end(), new ConfigFileSection(section)));
426    }
427
428    void ConfigFile::saveIfUpdated()
429    {
430        bool sectionsUpdated = false;
431
432        for (std::list<ConfigFileSection*>::iterator it = this->sections_.begin(); it != this->sections_.end(); ++it)
433        {
434            if ((*it)->bUpdated_)
435            {
436                sectionsUpdated = true;
437                (*it)->bUpdated_ = false;
438            }
439        }
440
441        if (this->bUpdated_ || sectionsUpdated)
442        {
443            this->bUpdated_ = false;
444            this->save();
445        }
446    }
447
448
449    ///////////////////////
450    // ConfigFileManager //
451    ///////////////////////
452    ConfigFileManager::ConfigFileManager()
453    {
454        this->setFile(CFT_Settings, DEFAULT_CONFIG_FILE);
455    }
456
457    ConfigFileManager::~ConfigFileManager()
458    {
459        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); )
460            delete (*(it++)).second;
461    }
462
463    ConfigFileManager* ConfigFileManager::getSingleton()
464    {
465        static ConfigFileManager instance;
466        return (&instance);
467    }
468
469    void ConfigFileManager::setFile(ConfigFileType type, const std::string& filename, bool bCreateIfNotExisting)
470    {
471        std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.find(type);
472        if (it != this->configFiles_.end())
473            if ((*it).second != 0)
474                delete (*it).second;
475
476        this->configFiles_[type] = new ConfigFile(this->getFilePath(filename));
477        this->load(type, bCreateIfNotExisting);
478    }
479
480    void ConfigFileManager::load(bool bCreateIfNotExisting)
481    {
482        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
483            (*it).second->load(bCreateIfNotExisting);
484
485        this->updateConfigValues();
486    }
487
488    void ConfigFileManager::save()
489    {
490        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
491            (*it).second->save();
492    }
493
494    void ConfigFileManager::clean(bool bCleanComments)
495    {
496        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
497            this->clean((*it).first, bCleanComments);
498    }
499
500    void ConfigFileManager::load(ConfigFileType type, bool bCreateIfNotExisting)
501    {
502        this->getFile(type)->load(bCreateIfNotExisting);
503        this->updateConfigValues(type);
504    }
505
506    void ConfigFileManager::save(ConfigFileType type)
507    {
508        this->getFile(type)->save();
509    }
510
511    void ConfigFileManager::clean(ConfigFileType type, bool bCleanComments)
512    {
513        this->getFile(type)->clean(bCleanComments);
514    }
515
516    void ConfigFileManager::updateConfigValues() const
517    {
518        for(std::map<ConfigFileType, ConfigFile*>::const_iterator it = this->configFiles_.begin(); it != this->configFiles_.end(); ++it)
519            this->updateConfigValues((*it).first);
520    }
521
522    void ConfigFileManager::updateConfigValues(ConfigFileType type) const
523    {
524        if (type == CFT_Settings)
525        {
526            for (std::map<std::string, Identifier*>::const_iterator it = Identifier::getIdentifierMapBegin(); it != Identifier::getIdentifierMapEnd(); ++it)
527            {
528                if ((*it).second->hasConfigValues() /* && (*it).second != ClassManager<KeyBinder>::getIdentifier()*/)
529                {
530                    for (std::map<std::string, ConfigValueContainer*>::const_iterator it2 = (*it).second->getConfigValueMapBegin(); it2 != (*it).second->getConfigValueMapEnd(); ++it2)
531                        (*it2).second->update();
532
533                    (*it).second->updateConfigValues();
534                }
535            }
536        }
537        else if (type == CFT_Keybindings)
538        {
539            // todo
540        }
541    }
542
543    ConfigFile* ConfigFileManager::getFile(ConfigFileType type)
544    {
545        std::map<ConfigFileType, ConfigFile*>::iterator it = this->configFiles_.find(type);
546        if (it != this->configFiles_.end())
547            return (*it).second;
548
549        if (type == CFT_Settings)
550            return this->configFiles_[type] = new ConfigFile(DEFAULT_CONFIG_FILE);
551        else
552            return this->configFiles_[type] = new ConfigFile("");
553    }
554
555    std::string ConfigFileManager::getFilePath(const std::string& name) const
556    {
557        return name;
558    }
559}
Note: See TracBrowser for help on using the repository browser.