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>
38 #include <sys/utsname.h>
42 #include <sys/pstat.h>
44 #if !defined(_WIN32) && !defined(__APPLE__) && \
45 !defined(__ANDROID__) && !defined(SERVER)
50 #include <X11/Xutil.h>
57 #include "util/string.h"
65 Signal handler (grabs Ctrl-C on POSIX systems)
68 bool g_killed = false;
70 bool * signal_handler_killstatus(void)
75 #if !defined(_WIN32) // POSIX
78 void sigint_handler(int sig)
81 dstream << "INFO: sigint_handler(): "
82 << "Ctrl-C pressed, shutting down." << std::endl;
84 // Comment out for less clutter when testing scripts
85 /*dstream << "INFO: sigint_handler(): "
86 << "Printing debug stacks" << std::endl;
87 debug_stacks_print();*/
91 (void)signal(SIGINT, SIG_DFL);
95 void signal_handler_init(void)
97 (void)signal(SIGINT, sigint_handler);
103 BOOL WINAPI event_handler(DWORD sig)
107 case CTRL_CLOSE_EVENT:
108 case CTRL_LOGOFF_EVENT:
109 case CTRL_SHUTDOWN_EVENT:
111 dstream << "INFO: event_handler(): "
112 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
113 " shutting down." << std::endl;
116 (void)signal(SIGINT, SIG_DFL);
119 case CTRL_BREAK_EVENT:
126 void signal_handler_init(void)
128 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
138 // Default to RUN_IN_PLACE style relative paths
139 std::string path_share = "..";
140 std::string path_user = "..";
141 std::string path_locale = path_share + DIR_DELIM + "locale";
144 std::string getDataPath(const char *subpath)
146 return path_share + DIR_DELIM + subpath;
149 void pathRemoveFile(char *path, char delim)
151 // Remove filename and path delimiter
153 for(i = strlen(path)-1; i>=0; i--)
161 bool detectMSVCBuildDir(const std::string &path)
163 const char *ends[] = {
169 return (removeStringEnd(path, ends) != "");
172 std::string get_sysinfo()
176 std::ostringstream oss;
178 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
179 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
181 tmp = osvi.szCSDVersion;
182 std::replace(tmp.begin(), tmp.end(), ' ', '_');
184 oss << "Windows/" << osvi.dwMajorVersion << "."
185 << osvi.dwMinorVersion;
186 if (osvi.szCSDVersion[0])
193 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
194 oss << "x86_64"; // 32-bit app on 64-bit OS
201 struct utsname osinfo;
203 return std::string(osinfo.sysname) + "/"
204 + osinfo.release + " " + osinfo.machine;
209 bool getCurrentWorkingDir(char *buf, size_t len)
212 DWORD ret = GetCurrentDirectory(len, buf);
213 return (ret != 0) && (ret <= len);
215 return getcwd(buf, len);
220 bool getExecPathFromProcfs(char *buf, size_t buflen)
226 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
227 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
228 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
241 bool getCurrentExecPath(char *buf, size_t len)
243 DWORD written = GetModuleFileNameA(NULL, buf, len);
244 if (written == 0 || written == len)
252 #elif defined(linux) || defined(__linux) || defined(__linux__)
254 bool getCurrentExecPath(char *buf, size_t len)
256 if (!getExecPathFromProcfs(buf, len))
263 //// Mac OS X, Darwin
264 #elif defined(__APPLE__)
266 bool getCurrentExecPath(char *buf, size_t len)
268 uint32_t lenb = (uint32_t)len;
269 if (_NSGetExecutablePath(buf, &lenb) == -1)
276 //// FreeBSD, NetBSD, DragonFlyBSD
277 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
279 bool getCurrentExecPath(char *buf, size_t len)
281 // Try getting path from procfs first, since valgrind
282 // doesn't work with the latter
283 if (getExecPathFromProcfs(buf, len))
290 mib[2] = KERN_PROC_PATHNAME;
293 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
301 #elif defined(__sun) || defined(sun)
303 bool getCurrentExecPath(char *buf, size_t len)
305 const char *exec = getexecname();
309 if (strlcpy(buf, exec, len) >= len)
317 #elif defined(__hpux)
319 bool getCurrentExecPath(char *buf, size_t len)
321 struct pst_status psts;
323 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
326 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
335 bool getCurrentExecPath(char *buf, size_t len)
346 bool setSystemPaths()
350 // Find path of executable and set path_share relative to it
351 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
352 "Failed to get current executable path");
353 pathRemoveFile(buf, '\\');
356 path_share = std::string(buf) + "\\..";
358 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
359 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
360 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
362 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
368 #elif defined(linux) || defined(__linux)
370 bool setSystemPaths()
374 if (!getCurrentExecPath(buf, sizeof(buf))) {
376 errorstream << "Unable to read bindir "<< std::endl;
378 FATAL_ERROR("Unable to read bindir");
383 pathRemoveFile(buf, '/');
384 std::string bindir(buf);
386 // Find share directory from these.
387 // It is identified by containing the subdirectory "builtin".
388 std::list<std::string> trylist;
389 std::string static_sharedir = STATIC_SHAREDIR;
390 if (static_sharedir != "" && static_sharedir != ".")
391 trylist.push_back(static_sharedir);
393 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
394 DIR_DELIM + PROJECT_NAME);
395 trylist.push_back(bindir + DIR_DELIM "..");
398 trylist.push_back(path_user);
401 for (std::list<std::string>::const_iterator
402 i = trylist.begin(); i != trylist.end(); i++) {
403 const std::string &trypath = *i;
404 if (!fs::PathExists(trypath) ||
405 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
406 warningstream << "system-wide share not found at \""
407 << trypath << "\""<< std::endl;
411 // Warn if was not the first alternative
412 if (i != trylist.begin()) {
413 warningstream << "system-wide share found at \""
414 << trypath << "\"" << std::endl;
417 path_share = trypath;
422 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
431 #elif defined(__APPLE__)
433 bool setSystemPaths()
435 CFBundleRef main_bundle = CFBundleGetMainBundle();
436 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
438 if (CFURLGetFileSystemRepresentation(resources_url,
439 TRUE, (UInt8 *)path, PATH_MAX)) {
440 path_share = std::string(path);
442 warningstream << "Could not determine bundle resource path" << std::endl;
444 CFRelease(resources_url);
446 path_user = std::string(getenv("HOME"))
447 + "/Library/Application Support/"
455 bool setSystemPaths()
457 path_share = STATIC_SHAREDIR;
458 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
459 + lowercase(PROJECT_NAME);
467 void initializePaths()
472 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
475 getCurrentExecPath(buf, sizeof(buf)) ||
476 getExecPathFromProcfs(buf, sizeof(buf));
479 pathRemoveFile(buf, DIR_DELIM_CHAR);
480 std::string execpath(buf);
482 path_share = execpath + DIR_DELIM "..";
483 path_user = execpath + DIR_DELIM "..";
485 if (detectMSVCBuildDir(execpath)) {
486 path_share += DIR_DELIM "..";
487 path_user += DIR_DELIM "..";
490 errorstream << "Failed to get paths by executable location, "
491 "trying cwd" << std::endl;
493 if (!getCurrentWorkingDir(buf, sizeof(buf)))
494 FATAL_ERROR("Ran out of methods to get paths");
496 size_t cwdlen = strlen(buf);
497 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
502 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
503 pathRemoveFile(buf, DIR_DELIM_CHAR);
505 std::string execpath(buf);
507 path_share = execpath;
508 path_user = execpath;
511 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
513 if (!setSystemPaths())
514 errorstream << "Failed to get one or more system-wide path" << std::endl;
518 infostream << "Detected share path: " << path_share << std::endl;
519 infostream << "Detected user path: " << path_user << std::endl;
521 bool found_localedir = false;
522 #ifdef STATIC_LOCALEDIR
523 if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
524 found_localedir = true;
525 path_locale = STATIC_LOCALEDIR;
526 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
528 path_locale = getDataPath("locale");
529 if (fs::PathExists(path_locale)) {
530 found_localedir = true;
531 infostream << "Using in-place locale directory " << path_locale
532 << " even though a static one was provided "
533 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
537 path_locale = getDataPath("locale");
538 if (fs::PathExists(path_locale)) {
539 found_localedir = true;
542 if (!found_localedir) {
543 errorstream << "Couldn't find a locale directory!" << std::endl;
550 void setXorgClassHint(const video::SExposedVideoData &video_data,
551 const std::string &name)
554 if (video_data.OpenGLLinux.X11Display == NULL)
557 XClassHint *classhint = XAllocClassHint();
558 classhint->res_name = (char *)name.c_str();
559 classhint->res_class = (char *)name.c_str();
561 XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
562 video_data.OpenGLLinux.X11Window, classhint);
569 //// Video/Display Information (Client-only)
574 static irr::IrrlichtDevice *device;
576 void initIrrlicht(irr::IrrlichtDevice *device_)
581 v2u32 getWindowSize()
583 return device->getVideoDriver()->getScreenSize();
587 std::vector<core::vector3d<u32> > getSupportedVideoModes()
589 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
590 sanity_check(nulldevice != NULL);
592 std::vector<core::vector3d<u32> > mlist;
593 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
595 u32 num_modes = modelist->getVideoModeCount();
596 for (u32 i = 0; i != num_modes; i++) {
597 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
598 s32 mode_depth = modelist->getVideoModeDepth(i);
599 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
607 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
609 std::vector<irr::video::E_DRIVER_TYPE> drivers;
611 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
612 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
613 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
619 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
621 static const char *driver_ids[] = {
632 return driver_ids[type];
636 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
638 static const char *driver_names[] = {
649 return driver_names[type];
655 static float calcDisplayDensity()
657 const char *current_display = getenv("DISPLAY");
659 if (current_display != NULL) {
660 Display *x11display = XOpenDisplay(current_display);
662 if (x11display != NULL) {
664 float dpi_height = floor(DisplayHeight(x11display, 0) /
665 (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
666 float dpi_width = floor(DisplayWidth(x11display, 0) /
667 (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
669 XCloseDisplay(x11display);
671 return std::max(dpi_height,dpi_width) / 96.0;
675 /* return manually specified dpi */
676 return g_settings->getFloat("screen_dpi")/96.0;
680 float getDisplayDensity()
682 static float cached_display_density = calcDisplayDensity();
683 return cached_display_density;
688 float getDisplayDensity()
690 return g_settings->getFloat("screen_dpi")/96.0;
694 v2u32 getDisplaySize()
696 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
698 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
699 nulldevice -> drop();
703 # endif // __ANDROID__
708 //// OS-specific Secure Random
713 bool secure_rand_fill_buf(void *buf, size_t len)
717 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
720 CryptGenRandom(wctx, len, (BYTE *)buf);
721 CryptReleaseContext(wctx, 0);
727 bool secure_rand_fill_buf(void *buf, size_t len)
729 // N.B. This function checks *only* for /dev/urandom, because on most
730 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
731 // is exceptionally uncommon for there to be a situation where /dev/random
732 // exists but /dev/urandom does not. This guesswork is necessary since
733 // random devices are not covered by any POSIX standard...
734 FILE *fp = fopen("/dev/urandom", "rb");
738 bool success = fread(buf, len, 1, fp) == 1;
746 } //namespace porting