Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/environment/src/libraries/core/PathConfig.cc @ 8206

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

Removed unnecessary changes in mac_osx branch.

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