3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 Random portability stuff
23 See comments in porting.h
28 #if defined(__FreeBSD__)
29 #include <sys/types.h>
30 #include <sys/sysctl.h>
36 #include <sys/utsname.h>
40 #include <sys/pstat.h>
42 #if !defined(_WIN32) && !defined(__APPLE__) && \
43 !defined(__ANDROID__) && !defined(SERVER)
48 #include <X11/Xutil.h>
55 #include "util/string.h"
63 Signal handler (grabs Ctrl-C on POSIX systems)
66 bool g_killed = false;
68 bool * signal_handler_killstatus(void)
73 #if !defined(_WIN32) // POSIX
76 void sigint_handler(int sig)
79 dstream << "INFO: sigint_handler(): "
80 << "Ctrl-C pressed, shutting down." << std::endl;
82 // Comment out for less clutter when testing scripts
83 /*dstream << "INFO: sigint_handler(): "
84 << "Printing debug stacks" << std::endl;
85 debug_stacks_print();*/
89 (void)signal(SIGINT, SIG_DFL);
93 void signal_handler_init(void)
95 (void)signal(SIGINT, sigint_handler);
101 BOOL WINAPI event_handler(DWORD sig)
105 case CTRL_CLOSE_EVENT:
106 case CTRL_LOGOFF_EVENT:
107 case CTRL_SHUTDOWN_EVENT:
109 dstream << "INFO: event_handler(): "
110 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
111 " shutting down." << std::endl;
114 (void)signal(SIGINT, SIG_DFL);
117 case CTRL_BREAK_EVENT:
124 void signal_handler_init(void)
126 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
136 // Default to RUN_IN_PLACE style relative paths
137 std::string path_share = "..";
138 std::string path_user = "..";
139 std::string path_locale = path_share + DIR_DELIM + "locale";
142 std::string getDataPath(const char *subpath)
144 return path_share + DIR_DELIM + subpath;
147 void pathRemoveFile(char *path, char delim)
149 // Remove filename and path delimiter
151 for(i = strlen(path)-1; i>=0; i--)
159 bool detectMSVCBuildDir(const std::string &path)
161 const char *ends[] = {
167 return (removeStringEnd(path, ends) != "");
170 std::string get_sysinfo()
174 std::ostringstream oss;
176 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
177 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
179 tmp = osvi.szCSDVersion;
180 std::replace(tmp.begin(), tmp.end(), ' ', '_');
182 oss << "Windows/" << osvi.dwMajorVersion << "."
183 << osvi.dwMinorVersion;
184 if (osvi.szCSDVersion[0])
191 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
192 oss << "x86_64"; // 32-bit app on 64-bit OS
199 struct utsname osinfo;
201 return std::string(osinfo.sysname) + "/"
202 + osinfo.release + " " + osinfo.machine;
207 bool getCurrentWorkingDir(char *buf, size_t len)
210 DWORD ret = GetCurrentDirectory(len, buf);
211 return (ret != 0) && (ret <= len);
213 return getcwd(buf, len);
218 bool getExecPathFromProcfs(char *buf, size_t buflen)
224 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
225 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
226 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
239 bool getCurrentExecPath(char *buf, size_t len)
241 DWORD written = GetModuleFileNameA(NULL, buf, len);
242 if (written == 0 || written == len)
250 #elif defined(linux) || defined(__linux) || defined(__linux__)
252 bool getCurrentExecPath(char *buf, size_t len)
254 if (!getExecPathFromProcfs(buf, len))
261 //// Mac OS X, Darwin
262 #elif defined(__APPLE__)
264 bool getCurrentExecPath(char *buf, size_t len)
266 uint32_t lenb = (uint32_t)len;
267 if (_NSGetExecutablePath(buf, &lenb) == -1)
274 //// FreeBSD, NetBSD, DragonFlyBSD
275 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
277 bool getCurrentExecPath(char *buf, size_t len)
279 // Try getting path from procfs first, since valgrind
280 // doesn't work with the latter
281 if (getExecPathFromProcfs(buf, len))
288 mib[2] = KERN_PROC_PATHNAME;
291 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
299 #elif defined(__sun) || defined(sun)
301 bool getCurrentExecPath(char *buf, size_t len)
303 const char *exec = getexecname();
307 if (strlcpy(buf, exec, len) >= len)
315 #elif defined(__hpux)
317 bool getCurrentExecPath(char *buf, size_t len)
319 struct pst_status psts;
321 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
324 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
333 bool getCurrentExecPath(char *buf, size_t len)
344 bool setSystemPaths()
348 // Find path of executable and set path_share relative to it
349 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
350 "Failed to get current executable path");
351 pathRemoveFile(buf, '\\');
354 path_share = std::string(buf) + "\\..";
356 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
357 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
358 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
360 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
366 #elif defined(linux) || defined(__linux)
368 bool setSystemPaths()
372 if (!getCurrentExecPath(buf, sizeof(buf))) {
374 errorstream << "Unable to read bindir "<< std::endl;
376 FATAL_ERROR("Unable to read bindir");
381 pathRemoveFile(buf, '/');
382 std::string bindir(buf);
384 // Find share directory from these.
385 // It is identified by containing the subdirectory "builtin".
386 std::list<std::string> trylist;
387 std::string static_sharedir = STATIC_SHAREDIR;
388 if (static_sharedir != "" && static_sharedir != ".")
389 trylist.push_back(static_sharedir);
391 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
392 DIR_DELIM + PROJECT_NAME);
393 trylist.push_back(bindir + DIR_DELIM "..");
396 trylist.push_back(path_user);
399 for (std::list<std::string>::const_iterator
400 i = trylist.begin(); i != trylist.end(); i++) {
401 const std::string &trypath = *i;
402 if (!fs::PathExists(trypath) ||
403 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
404 warningstream << "system-wide share not found at \""
405 << trypath << "\""<< std::endl;
409 // Warn if was not the first alternative
410 if (i != trylist.begin()) {
411 warningstream << "system-wide share found at \""
412 << trypath << "\"" << std::endl;
415 path_share = trypath;
420 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
429 #elif defined(__APPLE__)
431 bool setSystemPaths()
433 CFBundleRef main_bundle = CFBundleGetMainBundle();
434 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
436 if (CFURLGetFileSystemRepresentation(resources_url,
437 TRUE, (UInt8 *)path, PATH_MAX)) {
438 path_share = std::string(path);
440 warningstream << "Could not determine bundle resource path" << std::endl;
442 CFRelease(resources_url);
444 path_user = std::string(getenv("HOME"))
445 + "/Library/Application Support/"
453 bool setSystemPaths()
455 path_share = STATIC_SHAREDIR;
456 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
457 + lowercase(PROJECT_NAME);
465 void initializePaths()
470 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
473 getCurrentExecPath(buf, sizeof(buf)) ||
474 getExecPathFromProcfs(buf, sizeof(buf));
477 pathRemoveFile(buf, DIR_DELIM_CHAR);
478 std::string execpath(buf);
480 path_share = execpath + DIR_DELIM "..";
481 path_user = execpath + DIR_DELIM "..";
483 if (detectMSVCBuildDir(execpath)) {
484 path_share += DIR_DELIM "..";
485 path_user += DIR_DELIM "..";
488 errorstream << "Failed to get paths by executable location, "
489 "trying cwd" << std::endl;
491 if (!getCurrentWorkingDir(buf, sizeof(buf)))
492 FATAL_ERROR("Ran out of methods to get paths");
494 size_t cwdlen = strlen(buf);
495 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
500 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
501 pathRemoveFile(buf, DIR_DELIM_CHAR);
503 std::string execpath(buf);
505 path_share = execpath;
506 path_user = execpath;
509 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
511 if (!setSystemPaths())
512 errorstream << "Failed to get one or more system-wide path" << std::endl;
516 infostream << "Detected share path: " << path_share << std::endl;
517 infostream << "Detected user path: " << path_user << std::endl;
519 bool found_localedir = false;
520 #ifdef STATIC_LOCALEDIR
521 if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
522 found_localedir = true;
523 path_locale = STATIC_LOCALEDIR;
524 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
526 path_locale = getDataPath("locale");
527 if (fs::PathExists(path_locale)) {
528 found_localedir = true;
529 infostream << "Using in-place locale directory " << path_locale
530 << " even though a static one was provided "
531 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
535 path_locale = getDataPath("locale");
536 if (fs::PathExists(path_locale)) {
537 found_localedir = true;
540 if (!found_localedir) {
541 errorstream << "Couldn't find a locale directory!" << std::endl;
548 void setXorgClassHint(const video::SExposedVideoData &video_data,
549 const std::string &name)
552 if (video_data.OpenGLLinux.X11Display == NULL)
555 XClassHint *classhint = XAllocClassHint();
556 classhint->res_name = (char *)name.c_str();
557 classhint->res_class = (char *)name.c_str();
559 XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
560 video_data.OpenGLLinux.X11Window, classhint);
567 //// Video/Display Information (Client-only)
572 static irr::IrrlichtDevice *device;
574 void initIrrlicht(irr::IrrlichtDevice *device_)
579 v2u32 getWindowSize()
581 return device->getVideoDriver()->getScreenSize();
585 std::vector<core::vector3d<u32> > getSupportedVideoModes()
587 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
588 sanity_check(nulldevice != NULL);
590 std::vector<core::vector3d<u32> > mlist;
591 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
593 u32 num_modes = modelist->getVideoModeCount();
594 for (u32 i = 0; i != num_modes; i++) {
595 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
596 s32 mode_depth = modelist->getVideoModeDepth(i);
597 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
605 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
607 std::vector<irr::video::E_DRIVER_TYPE> drivers;
609 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
610 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
611 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
617 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
619 static const char *driver_ids[] = {
630 return driver_ids[type];
634 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
636 static const char *driver_names[] = {
647 return driver_names[type];
653 static float calcDisplayDensity()
655 const char *current_display = getenv("DISPLAY");
657 if (current_display != NULL) {
658 Display *x11display = XOpenDisplay(current_display);
660 if (x11display != NULL) {
662 float dpi_height = floor(DisplayHeight(x11display, 0) /
663 (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
664 float dpi_width = floor(DisplayWidth(x11display, 0) /
665 (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
667 XCloseDisplay(x11display);
669 return std::max(dpi_height,dpi_width) / 96.0;
673 /* return manually specified dpi */
674 return g_settings->getFloat("screen_dpi")/96.0;
678 float getDisplayDensity()
680 static float cached_display_density = calcDisplayDensity();
681 return cached_display_density;
686 float getDisplayDensity()
688 return g_settings->getFloat("screen_dpi")/96.0;
692 v2u32 getDisplaySize()
694 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
696 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
697 nulldevice -> drop();
701 # endif // __ANDROID__
704 } //namespace porting