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[] = {
170 return (removeStringEnd(path, ends) != "");
173 std::string get_sysinfo()
177 std::ostringstream oss;
179 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
180 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
182 tmp = osvi.szCSDVersion;
183 std::replace(tmp.begin(), tmp.end(), ' ', '_');
185 oss << "Windows/" << osvi.dwMajorVersion << "."
186 << osvi.dwMinorVersion;
187 if (osvi.szCSDVersion[0])
194 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
195 oss << "x86_64"; // 32-bit app on 64-bit OS
202 struct utsname osinfo;
204 return std::string(osinfo.sysname) + "/"
205 + osinfo.release + " " + osinfo.machine;
210 bool getCurrentWorkingDir(char *buf, size_t len)
213 DWORD ret = GetCurrentDirectory(len, buf);
214 return (ret != 0) && (ret <= len);
216 return getcwd(buf, len);
221 bool getExecPathFromProcfs(char *buf, size_t buflen)
227 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
228 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
229 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
242 bool getCurrentExecPath(char *buf, size_t len)
244 DWORD written = GetModuleFileNameA(NULL, buf, len);
245 if (written == 0 || written == len)
253 #elif defined(linux) || defined(__linux) || defined(__linux__)
255 bool getCurrentExecPath(char *buf, size_t len)
257 if (!getExecPathFromProcfs(buf, len))
264 //// Mac OS X, Darwin
265 #elif defined(__APPLE__)
267 bool getCurrentExecPath(char *buf, size_t len)
269 uint32_t lenb = (uint32_t)len;
270 if (_NSGetExecutablePath(buf, &lenb) == -1)
277 //// FreeBSD, NetBSD, DragonFlyBSD
278 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
280 bool getCurrentExecPath(char *buf, size_t len)
282 // Try getting path from procfs first, since valgrind
283 // doesn't work with the latter
284 if (getExecPathFromProcfs(buf, len))
291 mib[2] = KERN_PROC_PATHNAME;
294 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
302 #elif defined(__sun) || defined(sun)
304 bool getCurrentExecPath(char *buf, size_t len)
306 const char *exec = getexecname();
310 if (strlcpy(buf, exec, len) >= len)
318 #elif defined(__hpux)
320 bool getCurrentExecPath(char *buf, size_t len)
322 struct pst_status psts;
324 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
327 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
336 bool getCurrentExecPath(char *buf, size_t len)
347 bool setSystemPaths()
351 // Find path of executable and set path_share relative to it
352 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
353 "Failed to get current executable path");
354 pathRemoveFile(buf, '\\');
357 path_share = std::string(buf) + "\\..";
359 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
360 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
361 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
363 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
369 #elif defined(linux) || defined(__linux)
371 bool setSystemPaths()
375 if (!getCurrentExecPath(buf, sizeof(buf))) {
377 errorstream << "Unable to read bindir "<< std::endl;
379 FATAL_ERROR("Unable to read bindir");
384 pathRemoveFile(buf, '/');
385 std::string bindir(buf);
387 // Find share directory from these.
388 // It is identified by containing the subdirectory "builtin".
389 std::list<std::string> trylist;
390 std::string static_sharedir = STATIC_SHAREDIR;
391 if (static_sharedir != "" && static_sharedir != ".")
392 trylist.push_back(static_sharedir);
394 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
395 DIR_DELIM + PROJECT_NAME);
396 trylist.push_back(bindir + DIR_DELIM "..");
399 trylist.push_back(path_user);
402 for (std::list<std::string>::const_iterator
403 i = trylist.begin(); i != trylist.end(); i++) {
404 const std::string &trypath = *i;
405 if (!fs::PathExists(trypath) ||
406 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
407 warningstream << "system-wide share not found at \""
408 << trypath << "\""<< std::endl;
412 // Warn if was not the first alternative
413 if (i != trylist.begin()) {
414 warningstream << "system-wide share found at \""
415 << trypath << "\"" << std::endl;
418 path_share = trypath;
423 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
432 #elif defined(__APPLE__)
434 bool setSystemPaths()
436 CFBundleRef main_bundle = CFBundleGetMainBundle();
437 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
439 if (CFURLGetFileSystemRepresentation(resources_url,
440 TRUE, (UInt8 *)path, PATH_MAX)) {
441 path_share = std::string(path);
443 warningstream << "Could not determine bundle resource path" << std::endl;
445 CFRelease(resources_url);
447 path_user = std::string(getenv("HOME"))
448 + "/Library/Application Support/"
456 bool setSystemPaths()
458 path_share = STATIC_SHAREDIR;
459 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
460 + lowercase(PROJECT_NAME);
467 void migrateCachePath()
469 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
471 // Delete tmp folder if it exists (it only ever contained
472 // a temporary ogg file, which is no longer used).
473 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
474 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
476 // Bail if migration impossible
477 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
478 || fs::PathExists(path_cache)) {
481 if (!fs::Rename(local_cache_path, path_cache)) {
482 errorstream << "Failed to migrate local cache path "
483 "to system path!" << std::endl;
487 void initializePaths()
492 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
495 getCurrentExecPath(buf, sizeof(buf)) ||
496 getExecPathFromProcfs(buf, sizeof(buf));
499 pathRemoveFile(buf, DIR_DELIM_CHAR);
500 std::string execpath(buf);
502 path_share = execpath + DIR_DELIM "..";
503 path_user = execpath + DIR_DELIM "..";
505 if (detectMSVCBuildDir(execpath)) {
506 path_share += DIR_DELIM "..";
507 path_user += DIR_DELIM "..";
510 errorstream << "Failed to get paths by executable location, "
511 "trying cwd" << std::endl;
513 if (!getCurrentWorkingDir(buf, sizeof(buf)))
514 FATAL_ERROR("Ran out of methods to get paths");
516 size_t cwdlen = strlen(buf);
517 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
522 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
523 pathRemoveFile(buf, DIR_DELIM_CHAR);
525 std::string execpath(buf);
527 path_share = execpath;
528 path_user = execpath;
531 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
533 if (!setSystemPaths())
534 errorstream << "Failed to get one or more system-wide path" << std::endl;
536 // Initialize path_cache
537 // First try $XDG_CACHE_HOME/PROJECT_NAME
538 const char *cache_dir = getenv("XDG_CACHE_HOME");
540 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
542 // Then try $HOME/.cache/PROJECT_NAME
543 const char *home_dir = getenv("HOME");
545 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
546 + DIR_DELIM + PROJECT_NAME;
548 // If neither works, leave it at $PATH_USER/cache
550 // Migrate cache folder to new location if possible
554 infostream << "Detected share path: " << path_share << std::endl;
555 infostream << "Detected user path: " << path_user << std::endl;
556 infostream << "Detected cache path: " << path_cache << std::endl;
558 bool found_localedir = false;
559 #ifdef STATIC_LOCALEDIR
560 if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
561 found_localedir = true;
562 path_locale = STATIC_LOCALEDIR;
563 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
565 path_locale = getDataPath("locale");
566 if (fs::PathExists(path_locale)) {
567 found_localedir = true;
568 infostream << "Using in-place locale directory " << path_locale
569 << " even though a static one was provided "
570 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
574 path_locale = getDataPath("locale");
575 if (fs::PathExists(path_locale)) {
576 found_localedir = true;
579 if (!found_localedir) {
580 errorstream << "Couldn't find a locale directory!" << std::endl;
586 void setXorgClassHint(const video::SExposedVideoData &video_data,
587 const std::string &name)
590 if (video_data.OpenGLLinux.X11Display == NULL)
593 XClassHint *classhint = XAllocClassHint();
594 classhint->res_name = (char *)name.c_str();
595 classhint->res_class = (char *)name.c_str();
597 XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
598 video_data.OpenGLLinux.X11Window, classhint);
605 //// Video/Display Information (Client-only)
610 static irr::IrrlichtDevice *device;
612 void initIrrlicht(irr::IrrlichtDevice *device_)
617 v2u32 getWindowSize()
619 return device->getVideoDriver()->getScreenSize();
623 std::vector<core::vector3d<u32> > getSupportedVideoModes()
625 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
626 sanity_check(nulldevice != NULL);
628 std::vector<core::vector3d<u32> > mlist;
629 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
631 u32 num_modes = modelist->getVideoModeCount();
632 for (u32 i = 0; i != num_modes; i++) {
633 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
634 s32 mode_depth = modelist->getVideoModeDepth(i);
635 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
643 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
645 std::vector<irr::video::E_DRIVER_TYPE> drivers;
647 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
648 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
649 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
655 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
657 static const char *driver_ids[] = {
668 return driver_ids[type];
672 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
674 static const char *driver_names[] = {
685 return driver_names[type];
691 static float calcDisplayDensity()
693 const char *current_display = getenv("DISPLAY");
695 if (current_display != NULL) {
696 Display *x11display = XOpenDisplay(current_display);
698 if (x11display != NULL) {
700 float dpi_height = floor(DisplayHeight(x11display, 0) /
701 (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
702 float dpi_width = floor(DisplayWidth(x11display, 0) /
703 (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
705 XCloseDisplay(x11display);
707 return std::max(dpi_height,dpi_width) / 96.0;
711 /* return manually specified dpi */
712 return g_settings->getFloat("screen_dpi")/96.0;
716 float getDisplayDensity()
718 static float cached_display_density = calcDisplayDensity();
719 return cached_display_density;
724 float getDisplayDensity()
726 return g_settings->getFloat("screen_dpi")/96.0;
730 v2u32 getDisplaySize()
732 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
734 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
735 nulldevice -> drop();
739 # endif // __ANDROID__
744 //// OS-specific Secure Random
749 bool secure_rand_fill_buf(void *buf, size_t len)
753 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
756 CryptGenRandom(wctx, len, (BYTE *)buf);
757 CryptReleaseContext(wctx, 0);
763 bool secure_rand_fill_buf(void *buf, size_t len)
765 // N.B. This function checks *only* for /dev/urandom, because on most
766 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
767 // is exceptionally uncommon for there to be a situation where /dev/random
768 // exists but /dev/urandom does not. This guesswork is necessary since
769 // random devices are not covered by any POSIX standard...
770 FILE *fp = fopen("/dev/urandom", "rb");
774 bool success = fread(buf, len, 1, fp) == 1;
782 } //namespace porting