Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/doc/src/libraries/core/PathConfig.cc @ 7335

Last change on this file since 7335 was 7335, checked in by rgrieder, 14 years ago

Added separate page for a commandline argument reference.
It's not too useful, but better than nothing.

  • Property svn:eol-style set to native
File size: 10.9 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 *      Reto Grieder
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29#include "PathConfig.h"
30
31#include <cassert>
32#include <cstdlib>
33#include <cstdio>
34#include <vector>
35#include <boost/version.hpp>
36#include <boost/filesystem.hpp>
37
38#ifdef ORXONOX_PLATFORM_WINDOWS
39#  ifndef WIN32_LEAN_AND_MEAN
40#    define WIN32_LEAN_AND_MEAN
41#  endif
42#  include <windows.h>
43#  undef min
44#  undef max
45#elif defined(ORXONOX_PLATFORM_APPLE)
46#  include <sys/param.h>
47#  include <mach-o/dyld.h>
48#else /* Linux */
49#  include <sys/types.h>
50#  include <unistd.h>
51#endif
52
53#include "SpecialConfig.h"
54#include "util/Debug.h"
55#include "util/Exception.h"
56#include "CommandLineParser.h"
57
58// Boost 1.36 has some issues with deprecated functions that have been omitted
59#if (BOOST_VERSION == 103600)
60#  define BOOST_LEAF_FUNCTION filename
61#else
62#  define BOOST_LEAF_FUNCTION leaf
63#endif
64
65namespace orxonox
66{
67    namespace bf = boost::filesystem;
68
69    //! Static pointer to the singleton
70    PathConfig* PathConfig::singletonPtr_s  = 0;
71
72    //! @cmdarg
73    SetCommandLineArgument(externalDataPath, "").information("Path to the external data files");
74    //! @cmdarg
75    SetCommandLineOnlyArgument(writingPathSuffix, "").information("Additional subfolder for config and log files");
76
77    PathConfig::PathConfig()
78        : rootPath_(*(new bf::path()))
79        , executablePath_(*(new bf::path()))
80        , modulePath_(*(new bf::path()))
81        , dataPath_(*(new bf::path()))
82        , externalDataPath_(*(new bf::path()))
83        , configPath_(*(new bf::path()))
84        , logPath_(*(new bf::path()))
85        , bDevRun_(false)
86    {
87        //////////////////////////
88        // FIND EXECUTABLE PATH //
89        //////////////////////////
90
91#ifdef ORXONOX_PLATFORM_WINDOWS
92        // get executable module
93        TCHAR buffer[1024];
94        if (GetModuleFileName(NULL, buffer, 1024) == 0)
95            ThrowException(General, "Could not retrieve executable path.");
96
97#elif defined(ORXONOX_PLATFORM_APPLE)
98        char buffer[1024];
99        unsigned long path_len = 1023;
100        if (_NSGetExecutablePath(buffer, &path_len))
101            ThrowException(General, "Could not retrieve executable path.");
102
103#else /* Linux */
104        /* written by Nicolai Haehnle <prefect_@gmx.net> */
105
106        /* Get our PID and build the name of the link in /proc */
107        char linkname[64]; /* /proc/<pid>/exe */
108        if (snprintf(linkname, sizeof(linkname), "/proc/%i/exe", getpid()) < 0)
109        {
110            /* This should only happen on large word systems. I'm not sure
111               what the proper response is here.
112               Since it really is an assert-like condition, aborting the
113               program seems to be in order. */
114            assert(false);
115        }
116
117        /* Now read the symbolic link */
118        char buffer[1024];
119        int ret;
120        ret = readlink(linkname, buffer, 1024);
121        /* In case of an error, leave the handling up to the caller */
122        if (ret == -1)
123            ThrowException(General, "Could not retrieve executable path.");
124
125        /* Ensure proper NUL termination */
126        buffer[ret] = 0;
127#endif
128
129        executablePath_ = bf::path(buffer);
130#ifndef ORXONOX_PLATFORM_APPLE
131        executablePath_ = executablePath_.branch_path(); // remove executable name
132#endif
133
134        /////////////////////
135        // SET MODULE PATH //
136        /////////////////////
137
138        if (bf::exists(executablePath_ / "orxonox_dev_build.keep_me"))
139        {
140            COUT(1) << "Running from the build tree." << std::endl;
141            PathConfig::bDevRun_ = true;
142            modulePath_ = specialConfig::moduleDevDirectory;
143        }
144        else
145        {
146
147#ifdef INSTALL_COPYABLE // --> relative paths
148
149            // Also set the root path
150            bf::path relativeExecutablePath(specialConfig::defaultRuntimePath);
151            rootPath_ = executablePath_;
152            while (!bf::equivalent(rootPath_ / relativeExecutablePath, executablePath_) && !rootPath_.empty())
153                rootPath_ = rootPath_.branch_path();
154            if (rootPath_.empty())
155                ThrowException(General, "Could not derive a root directory. Might the binary installation directory contain '..' when taken relative to the installation prefix path?");
156
157            // Module path is fixed as well
158            modulePath_ = rootPath_ / specialConfig::defaultModulePath;
159
160#else
161
162            // There is no root path, so don't set it at all
163            // Module path is fixed as well
164            modulePath_ = specialConfig::moduleInstallDirectory;
165
166#endif
167        }
168    }
169
170    PathConfig::~PathConfig()
171    {
172        delete &rootPath_;
173        delete &executablePath_;
174        delete &modulePath_;
175        delete &dataPath_;
176        delete &externalDataPath_;
177        delete &configPath_;
178        delete &logPath_;
179    }
180
181    void PathConfig::setConfigurablePaths()
182    {
183        if (bDevRun_)
184        {
185            dataPath_         = specialConfig::dataDevDirectory;
186            configPath_       = specialConfig::configDevDirectory;
187            logPath_          = specialConfig::logDevDirectory;
188
189            // Check for data path override by the command line
190            if (!CommandLineParser::getArgument("externalDataPath")->hasDefaultValue())
191                externalDataPath_ = CommandLineParser::getValue("externalDataPath").getString();
192            else
193                externalDataPath_ = specialConfig::externalDataDevDirectory;
194        }
195        else
196        {
197
198#ifdef INSTALL_COPYABLE // --> relative paths
199
200            // Using paths relative to the install prefix, complete them
201            dataPath_   = rootPath_ / specialConfig::defaultDataPath;
202            configPath_ = rootPath_ / specialConfig::defaultConfigPath;
203            logPath_    = rootPath_ / specialConfig::defaultLogPath;
204
205#else
206
207            dataPath_  = specialConfig::dataInstallDirectory;
208
209            // Get user directory
210#  ifdef ORXONOX_PLATFORM_UNIX /* Apple? */
211            char* userDataPathPtr(getenv("HOME"));
212#  else
213            char* userDataPathPtr(getenv("APPDATA"));
214#  endif
215            if (userDataPathPtr == NULL)
216                ThrowException(General, "Could not retrieve user data path.");
217            bf::path userDataPath(userDataPathPtr);
218            userDataPath /= ".orxonox";
219
220            configPath_ = userDataPath / specialConfig::defaultConfigPath;
221            logPath_    = userDataPath / specialConfig::defaultLogPath;
222
223#endif
224
225        }
226
227        // Option to put all the config and log files in a separate folder
228        if (!CommandLineParser::getArgument("writingPathSuffix")->hasDefaultValue())
229        {
230            const std::string& directory(CommandLineParser::getValue("writingPathSuffix").getString());
231            configPath_ = configPath_ / directory;
232            logPath_    = logPath_    / directory;
233        }
234
235        // Create directories to avoid problems when opening files in non existent folders.
236        std::vector<std::pair<bf::path, std::string> > directories;
237        directories.push_back(std::make_pair(bf::path(configPath_), "config"));
238        directories.push_back(std::make_pair(bf::path(logPath_), "log"));
239
240        for (std::vector<std::pair<bf::path, std::string> >::iterator it = directories.begin();
241            it != directories.end(); ++it)
242        {
243            if (bf::exists(it->first) && !bf::is_directory(it->first))
244            {
245                ThrowException(General, std::string("The ") + it->second + " directory has been preoccupied by a file! \
246                                         Please remove " + it->first.string());
247            }
248            if (bf::create_directories(it->first)) // function may not return true at all (bug?)
249            {
250                COUT(4) << "Created " << it->second << " directory" << std::endl;
251            }
252        }
253    }
254
255    std::vector<std::string> PathConfig::getModulePaths()
256    {
257        std::vector<std::string> modulePaths;
258
259        // We search for helper files with the following extension
260        const std::string& moduleextension = specialConfig::moduleExtension;
261        size_t moduleextensionlength = moduleextension.size();
262
263        // Add that path to the PATH variable in case a module depends on another one
264        std::string pathVariable(getenv("PATH"));
265        putenv(const_cast<char*>(("PATH=" + pathVariable + ';' + modulePath_.string()).c_str()));
266
267        // Make sure the path exists, otherwise don't load modules
268        if (!boost::filesystem::exists(modulePath_))
269            return modulePaths;
270
271        boost::filesystem::directory_iterator file(modulePath_);
272        boost::filesystem::directory_iterator end;
273
274        // Iterate through all files
275        while (file != end)
276        {
277            const std::string& filename = file->BOOST_LEAF_FUNCTION();
278
279            // Check if the file ends with the exension in question
280            if (filename.size() > moduleextensionlength)
281            {
282                if (filename.substr(filename.size() - moduleextensionlength) == moduleextension)
283                {
284                    // We've found a helper file
285                    const std::string& library = filename.substr(0, filename.size() - moduleextensionlength);
286                    modulePaths.push_back((modulePath_ / library).file_string());
287                }
288            }
289            ++file;
290        }
291
292        return modulePaths;
293    }
294
295    /*static*/ std::string PathConfig::getRootPathString()
296    {
297        return getInstance().rootPath_.string() + '/';
298    }
299
300    /*static*/ std::string PathConfig::getExecutablePathString()
301    {
302        return getInstance().executablePath_.string() + '/';
303    }
304
305    /*static*/ std::string PathConfig::getDataPathString()
306    {
307        return getInstance().dataPath_.string() + '/';
308    }
309
310    /*static*/ std::string PathConfig::getExternalDataPathString()
311    {
312        return getInstance().externalDataPath_.string() + '/';
313    }
314
315    /*static*/ std::string PathConfig::getConfigPathString()
316    {
317        return getInstance().configPath_.string() + '/';
318    }
319
320    /*static*/ std::string PathConfig::getLogPathString()
321    {
322        return getInstance().logPath_.string() + '/';
323    }
324
325    /*static*/ std::string PathConfig::getModulePathString()
326    {
327        return getInstance().modulePath_.string() + '/';
328    }
329}
Note: See TracBrowser for help on using the repository browser.