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";
142 std::string path_cache = path_user + DIR_DELIM + "cache";
145 std::string getDataPath(const char *subpath)
147 return path_share + DIR_DELIM + subpath;
150 void pathRemoveFile(char *path, char delim)
152 // Remove filename and path delimiter
154 for(i = strlen(path)-1; i>=0; i--)
162 bool detectMSVCBuildDir(const std::string &path)
164 const char *ends[] = {
167 "bin\\RelWithDebInfo",
172 return (removeStringEnd(path, ends) != "");
175 std::string get_sysinfo()
179 std::ostringstream oss;
181 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
182 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
184 tmp = osvi.szCSDVersion;
185 std::replace(tmp.begin(), tmp.end(), ' ', '_');
187 oss << "Windows/" << osvi.dwMajorVersion << "."
188 << osvi.dwMinorVersion;
189 if (osvi.szCSDVersion[0])
196 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
197 oss << "x86_64"; // 32-bit app on 64-bit OS
204 struct utsname osinfo;
206 return std::string(osinfo.sysname) + "/"
207 + osinfo.release + " " + osinfo.machine;
212 bool getCurrentWorkingDir(char *buf, size_t len)
215 DWORD ret = GetCurrentDirectory(len, buf);
216 return (ret != 0) && (ret <= len);
218 return getcwd(buf, len);
223 bool getExecPathFromProcfs(char *buf, size_t buflen)
229 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
230 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
231 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
244 bool getCurrentExecPath(char *buf, size_t len)
246 DWORD written = GetModuleFileNameA(NULL, buf, len);
247 if (written == 0 || written == len)
255 #elif defined(linux) || defined(__linux) || defined(__linux__)
257 bool getCurrentExecPath(char *buf, size_t len)
259 if (!getExecPathFromProcfs(buf, len))
266 //// Mac OS X, Darwin
267 #elif defined(__APPLE__)
269 bool getCurrentExecPath(char *buf, size_t len)
271 uint32_t lenb = (uint32_t)len;
272 if (_NSGetExecutablePath(buf, &lenb) == -1)
279 //// FreeBSD, NetBSD, DragonFlyBSD
280 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
282 bool getCurrentExecPath(char *buf, size_t len)
284 // Try getting path from procfs first, since valgrind
285 // doesn't work with the latter
286 if (getExecPathFromProcfs(buf, len))
293 mib[2] = KERN_PROC_PATHNAME;
296 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
304 #elif defined(__sun) || defined(sun)
306 bool getCurrentExecPath(char *buf, size_t len)
308 const char *exec = getexecname();
312 if (strlcpy(buf, exec, len) >= len)
320 #elif defined(__hpux)
322 bool getCurrentExecPath(char *buf, size_t len)
324 struct pst_status psts;
326 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
329 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
338 bool getCurrentExecPath(char *buf, size_t len)
349 bool setSystemPaths()
353 // Find path of executable and set path_share relative to it
354 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
355 "Failed to get current executable path");
356 pathRemoveFile(buf, '\\');
359 path_share = std::string(buf) + "\\..";
361 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
362 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
363 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
365 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
371 #elif defined(linux) || defined(__linux)
373 bool setSystemPaths()
377 if (!getCurrentExecPath(buf, sizeof(buf))) {
379 errorstream << "Unable to read bindir "<< std::endl;
381 FATAL_ERROR("Unable to read bindir");
386 pathRemoveFile(buf, '/');
387 std::string bindir(buf);
389 // Find share directory from these.
390 // It is identified by containing the subdirectory "builtin".
391 std::list<std::string> trylist;
392 std::string static_sharedir = STATIC_SHAREDIR;
393 if (static_sharedir != "" && static_sharedir != ".")
394 trylist.push_back(static_sharedir);
396 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
397 DIR_DELIM + PROJECT_NAME);
398 trylist.push_back(bindir + DIR_DELIM "..");
401 trylist.push_back(path_user);
404 for (std::list<std::string>::const_iterator
405 i = trylist.begin(); i != trylist.end(); i++) {
406 const std::string &trypath = *i;
407 if (!fs::PathExists(trypath) ||
408 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
409 warningstream << "system-wide share not found at \""
410 << trypath << "\""<< std::endl;
414 // Warn if was not the first alternative
415 if (i != trylist.begin()) {
416 warningstream << "system-wide share found at \""
417 << trypath << "\"" << std::endl;
420 path_share = trypath;
425 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
434 #elif defined(__APPLE__)
436 bool setSystemPaths()
438 CFBundleRef main_bundle = CFBundleGetMainBundle();
439 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
441 if (CFURLGetFileSystemRepresentation(resources_url,
442 TRUE, (UInt8 *)path, PATH_MAX)) {
443 path_share = std::string(path);
445 warningstream << "Could not determine bundle resource path" << std::endl;
447 CFRelease(resources_url);
449 path_user = std::string(getenv("HOME"))
450 + "/Library/Application Support/"
458 bool setSystemPaths()
460 path_share = STATIC_SHAREDIR;
461 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
462 + lowercase(PROJECT_NAME);
469 void migrateCachePath()
471 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
473 // Delete tmp folder if it exists (it only ever contained
474 // a temporary ogg file, which is no longer used).
475 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
476 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
478 // Bail if migration impossible
479 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
480 || fs::PathExists(path_cache)) {
483 if (!fs::Rename(local_cache_path, path_cache)) {
484 errorstream << "Failed to migrate local cache path "
485 "to system path!" << std::endl;
489 void initializePaths()
494 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
497 getCurrentExecPath(buf, sizeof(buf)) ||
498 getExecPathFromProcfs(buf, sizeof(buf));
501 pathRemoveFile(buf, DIR_DELIM_CHAR);
502 std::string execpath(buf);
504 path_share = execpath + DIR_DELIM "..";
505 path_user = execpath + DIR_DELIM "..";
507 if (detectMSVCBuildDir(execpath)) {
508 path_share += DIR_DELIM "..";
509 path_user += DIR_DELIM "..";
512 errorstream << "Failed to get paths by executable location, "
513 "trying cwd" << std::endl;
515 if (!getCurrentWorkingDir(buf, sizeof(buf)))
516 FATAL_ERROR("Ran out of methods to get paths");
518 size_t cwdlen = strlen(buf);
519 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
524 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
525 pathRemoveFile(buf, DIR_DELIM_CHAR);
527 std::string execpath(buf);
529 path_share = execpath;
530 path_user = execpath;
532 path_cache = path_user + DIR_DELIM + "cache";
534 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
536 if (!setSystemPaths())
537 errorstream << "Failed to get one or more system-wide path" << std::endl;
539 // Initialize path_cache
540 // First try $XDG_CACHE_HOME/PROJECT_NAME
541 const char *cache_dir = getenv("XDG_CACHE_HOME");
542 const char *home_dir = getenv("HOME");
544 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
545 } else if (home_dir) {
546 // Then try $HOME/.cache/PROJECT_NAME
547 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
548 + DIR_DELIM + PROJECT_NAME;
550 // If neither works, use $PATH_USER/cache
551 path_cache = path_user + DIR_DELIM + "cache";
553 // Migrate cache folder to new location if possible
557 infostream << "Detected share path: " << path_share << std::endl;
558 infostream << "Detected user path: " << path_user << std::endl;
559 infostream << "Detected cache path: " << path_cache << std::endl;
562 bool found_localedir = false;
563 # ifdef STATIC_LOCALEDIR
564 if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
565 found_localedir = true;
566 path_locale = STATIC_LOCALEDIR;
567 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
569 path_locale = getDataPath("locale");
570 if (fs::PathExists(path_locale)) {
571 found_localedir = true;
572 infostream << "Using in-place locale directory " << path_locale
573 << " even though a static one was provided "
574 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
578 path_locale = getDataPath("locale");
579 if (fs::PathExists(path_locale)) {
580 found_localedir = true;
583 if (!found_localedir) {
584 warningstream << "Couldn't find a locale directory!" << std::endl;
586 #endif // USE_GETTEXT
591 void setXorgClassHint(const video::SExposedVideoData &video_data,
592 const std::string &name)
595 if (video_data.OpenGLLinux.X11Display == NULL)
598 XClassHint *classhint = XAllocClassHint();
599 classhint->res_name = (char *)name.c_str();
600 classhint->res_class = (char *)name.c_str();
602 XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
603 video_data.OpenGLLinux.X11Window, classhint);
610 //// Video/Display Information (Client-only)
615 static irr::IrrlichtDevice *device;
617 void initIrrlicht(irr::IrrlichtDevice *device_)
622 v2u32 getWindowSize()
624 return device->getVideoDriver()->getScreenSize();
628 std::vector<core::vector3d<u32> > getSupportedVideoModes()
630 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
631 sanity_check(nulldevice != NULL);
633 std::vector<core::vector3d<u32> > mlist;
634 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
636 u32 num_modes = modelist->getVideoModeCount();
637 for (u32 i = 0; i != num_modes; i++) {
638 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
639 s32 mode_depth = modelist->getVideoModeDepth(i);
640 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
648 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
650 std::vector<irr::video::E_DRIVER_TYPE> drivers;
652 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
653 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
654 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
660 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
662 static const char *driver_ids[] = {
673 return driver_ids[type];
677 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
679 static const char *driver_names[] = {
690 return driver_names[type];
696 static float calcDisplayDensity()
698 const char *current_display = getenv("DISPLAY");
700 if (current_display != NULL) {
701 Display *x11display = XOpenDisplay(current_display);
703 if (x11display != NULL) {
705 float dpi_height = floor(DisplayHeight(x11display, 0) /
706 (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
707 float dpi_width = floor(DisplayWidth(x11display, 0) /
708 (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
710 XCloseDisplay(x11display);
712 return std::max(dpi_height,dpi_width) / 96.0;
716 /* return manually specified dpi */
717 return g_settings->getFloat("screen_dpi")/96.0;
721 float getDisplayDensity()
723 static float cached_display_density = calcDisplayDensity();
724 return cached_display_density;
729 float getDisplayDensity()
731 return g_settings->getFloat("screen_dpi")/96.0;
735 v2u32 getDisplaySize()
737 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
739 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
740 nulldevice -> drop();
744 # endif // __ANDROID__
749 //// OS-specific Secure Random
754 bool secure_rand_fill_buf(void *buf, size_t len)
758 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
761 CryptGenRandom(wctx, len, (BYTE *)buf);
762 CryptReleaseContext(wctx, 0);
768 bool secure_rand_fill_buf(void *buf, size_t len)
770 // N.B. This function checks *only* for /dev/urandom, because on most
771 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
772 // is exceptionally uncommon for there to be a situation where /dev/random
773 // exists but /dev/urandom does not. This guesswork is necessary since
774 // random devices are not covered by any POSIX standard...
775 FILE *fp = fopen("/dev/urandom", "rb");
779 bool success = fread(buf, len, 1, fp) == 1;
787 } //namespace porting