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 signal_handler(int sig)
82 dstream << "INFO: signal_handler(): "
83 << "Ctrl-C pressed, shutting down." << std::endl;
84 } else if (sig == SIGTERM) {
85 dstream << "INFO: signal_handler(): "
86 << "got SIGTERM, shutting down." << std::endl;
89 // Comment out for less clutter when testing scripts
90 /*dstream << "INFO: sigint_handler(): "
91 << "Printing debug stacks" << std::endl;
92 debug_stacks_print();*/
96 (void)signal(sig, SIG_DFL);
100 void signal_handler_init(void)
102 (void)signal(SIGINT, signal_handler);
103 (void)signal(SIGTERM, signal_handler);
109 BOOL WINAPI event_handler(DWORD sig)
113 case CTRL_CLOSE_EVENT:
114 case CTRL_LOGOFF_EVENT:
115 case CTRL_SHUTDOWN_EVENT:
117 dstream << "INFO: event_handler(): "
118 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
119 " shutting down." << std::endl;
122 (void)signal(SIGINT, SIG_DFL);
125 case CTRL_BREAK_EVENT:
132 void signal_handler_init(void)
134 SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
144 // Default to RUN_IN_PLACE style relative paths
145 std::string path_share = "..";
146 std::string path_user = "..";
147 std::string path_locale = path_share + DIR_DELIM + "locale";
148 std::string path_cache = path_user + DIR_DELIM + "cache";
151 std::string getDataPath(const char *subpath)
153 return path_share + DIR_DELIM + subpath;
156 void pathRemoveFile(char *path, char delim)
158 // Remove filename and path delimiter
160 for(i = strlen(path)-1; i>=0; i--)
168 bool detectMSVCBuildDir(const std::string &path)
170 const char *ends[] = {
173 "bin\\RelWithDebInfo",
178 return (removeStringEnd(path, ends) != "");
181 std::string get_sysinfo()
185 std::ostringstream oss;
187 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
188 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
190 tmp = osvi.szCSDVersion;
191 std::replace(tmp.begin(), tmp.end(), ' ', '_');
193 oss << "Windows/" << osvi.dwMajorVersion << "."
194 << osvi.dwMinorVersion;
195 if (osvi.szCSDVersion[0])
202 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
203 oss << "x86_64"; // 32-bit app on 64-bit OS
210 struct utsname osinfo;
212 return std::string(osinfo.sysname) + "/"
213 + osinfo.release + " " + osinfo.machine;
218 bool getCurrentWorkingDir(char *buf, size_t len)
221 DWORD ret = GetCurrentDirectory(len, buf);
222 return (ret != 0) && (ret <= len);
224 return getcwd(buf, len);
229 bool getExecPathFromProcfs(char *buf, size_t buflen)
235 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
236 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
237 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
250 bool getCurrentExecPath(char *buf, size_t len)
252 DWORD written = GetModuleFileNameA(NULL, buf, len);
253 if (written == 0 || written == len)
261 #elif defined(__linux__)
263 bool getCurrentExecPath(char *buf, size_t len)
265 if (!getExecPathFromProcfs(buf, len))
272 //// Mac OS X, Darwin
273 #elif defined(__APPLE__)
275 bool getCurrentExecPath(char *buf, size_t len)
277 uint32_t lenb = (uint32_t)len;
278 if (_NSGetExecutablePath(buf, &lenb) == -1)
285 //// FreeBSD, NetBSD, DragonFlyBSD
286 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
288 bool getCurrentExecPath(char *buf, size_t len)
290 // Try getting path from procfs first, since valgrind
291 // doesn't work with the latter
292 if (getExecPathFromProcfs(buf, len))
299 mib[2] = KERN_PROC_PATHNAME;
302 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
310 #elif defined(__sun) || defined(sun)
312 bool getCurrentExecPath(char *buf, size_t len)
314 const char *exec = getexecname();
318 if (strlcpy(buf, exec, len) >= len)
326 #elif defined(__hpux)
328 bool getCurrentExecPath(char *buf, size_t len)
330 struct pst_status psts;
332 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
335 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
344 bool getCurrentExecPath(char *buf, size_t len)
355 bool setSystemPaths()
359 // Find path of executable and set path_share relative to it
360 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
361 "Failed to get current executable path");
362 pathRemoveFile(buf, '\\');
365 path_share = std::string(buf) + "\\..";
367 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
368 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
369 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
371 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
377 #elif defined(__linux__)
379 bool setSystemPaths()
383 if (!getCurrentExecPath(buf, sizeof(buf))) {
385 errorstream << "Unable to read bindir "<< std::endl;
387 FATAL_ERROR("Unable to read bindir");
392 pathRemoveFile(buf, '/');
393 std::string bindir(buf);
395 // Find share directory from these.
396 // It is identified by containing the subdirectory "builtin".
397 std::list<std::string> trylist;
398 std::string static_sharedir = STATIC_SHAREDIR;
399 if (static_sharedir != "" && static_sharedir != ".")
400 trylist.push_back(static_sharedir);
402 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
403 DIR_DELIM + PROJECT_NAME);
404 trylist.push_back(bindir + DIR_DELIM "..");
407 trylist.push_back(path_user);
410 for (std::list<std::string>::const_iterator
411 i = trylist.begin(); i != trylist.end(); ++i) {
412 const std::string &trypath = *i;
413 if (!fs::PathExists(trypath) ||
414 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
415 warningstream << "system-wide share not found at \""
416 << trypath << "\""<< std::endl;
420 // Warn if was not the first alternative
421 if (i != trylist.begin()) {
422 warningstream << "system-wide share found at \""
423 << trypath << "\"" << std::endl;
426 path_share = trypath;
431 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
440 #elif defined(__APPLE__)
442 bool setSystemPaths()
444 CFBundleRef main_bundle = CFBundleGetMainBundle();
445 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
447 if (CFURLGetFileSystemRepresentation(resources_url,
448 TRUE, (UInt8 *)path, PATH_MAX)) {
449 path_share = std::string(path);
451 warningstream << "Could not determine bundle resource path" << std::endl;
453 CFRelease(resources_url);
455 path_user = std::string(getenv("HOME"))
456 + "/Library/Application Support/"
464 bool setSystemPaths()
466 path_share = STATIC_SHAREDIR;
467 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
468 + lowercase(PROJECT_NAME);
475 void migrateCachePath()
477 const std::string local_cache_path = path_user + DIR_DELIM + "cache";
479 // Delete tmp folder if it exists (it only ever contained
480 // a temporary ogg file, which is no longer used).
481 if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
482 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
484 // Bail if migration impossible
485 if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
486 || fs::PathExists(path_cache)) {
489 if (!fs::Rename(local_cache_path, path_cache)) {
490 errorstream << "Failed to migrate local cache path "
491 "to system path!" << std::endl;
495 void initializePaths()
500 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
503 getCurrentExecPath(buf, sizeof(buf)) ||
504 getExecPathFromProcfs(buf, sizeof(buf));
507 pathRemoveFile(buf, DIR_DELIM_CHAR);
508 std::string execpath(buf);
510 path_share = execpath + DIR_DELIM "..";
511 path_user = execpath + DIR_DELIM "..";
513 if (detectMSVCBuildDir(execpath)) {
514 path_share += DIR_DELIM "..";
515 path_user += DIR_DELIM "..";
518 errorstream << "Failed to get paths by executable location, "
519 "trying cwd" << std::endl;
521 if (!getCurrentWorkingDir(buf, sizeof(buf)))
522 FATAL_ERROR("Ran out of methods to get paths");
524 size_t cwdlen = strlen(buf);
525 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
530 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
531 pathRemoveFile(buf, DIR_DELIM_CHAR);
533 std::string execpath(buf);
535 path_share = execpath;
536 path_user = execpath;
538 path_cache = path_user + DIR_DELIM + "cache";
540 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
542 if (!setSystemPaths())
543 errorstream << "Failed to get one or more system-wide path" << std::endl;
545 // Initialize path_cache
546 // First try $XDG_CACHE_HOME/PROJECT_NAME
547 const char *cache_dir = getenv("XDG_CACHE_HOME");
548 const char *home_dir = getenv("HOME");
550 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
551 } else if (home_dir) {
552 // Then try $HOME/.cache/PROJECT_NAME
553 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
554 + DIR_DELIM + PROJECT_NAME;
556 // If neither works, use $PATH_USER/cache
557 path_cache = path_user + DIR_DELIM + "cache";
559 // Migrate cache folder to new location if possible
563 infostream << "Detected share path: " << path_share << std::endl;
564 infostream << "Detected user path: " << path_user << std::endl;
565 infostream << "Detected cache path: " << path_cache << std::endl;
568 bool found_localedir = false;
569 # ifdef STATIC_LOCALEDIR
570 if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
571 found_localedir = true;
572 path_locale = STATIC_LOCALEDIR;
573 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
575 path_locale = getDataPath("locale");
576 if (fs::PathExists(path_locale)) {
577 found_localedir = true;
578 infostream << "Using in-place locale directory " << path_locale
579 << " even though a static one was provided "
580 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
584 path_locale = getDataPath("locale");
585 if (fs::PathExists(path_locale)) {
586 found_localedir = true;
589 if (!found_localedir) {
590 warningstream << "Couldn't find a locale directory!" << std::endl;
592 #endif // USE_GETTEXT
597 void setXorgClassHint(const video::SExposedVideoData &video_data,
598 const std::string &name)
601 if (video_data.OpenGLLinux.X11Display == NULL)
604 XClassHint *classhint = XAllocClassHint();
605 classhint->res_name = (char *)name.c_str();
606 classhint->res_class = (char *)name.c_str();
608 XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
609 video_data.OpenGLLinux.X11Window, classhint);
614 bool setWindowIcon(IrrlichtDevice *device)
616 #if defined(XORG_USED)
618 return setXorgWindowIconFromPath(device,
619 path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png");
621 // We have semi-support for reading in-place data if we are
622 // compiled with RUN_IN_PLACE. Don't break with this and
623 // also try the path_share location.
625 setXorgWindowIconFromPath(device,
626 ICON_DIR "/hicolor/128x128/apps/" PROJECT_NAME ".png") ||
627 setXorgWindowIconFromPath(device,
628 path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png");
630 #elif defined(_WIN32)
631 const video::SExposedVideoData exposedData = device->getVideoDriver()->getExposedVideoData();
632 HWND hWnd; // Window handle
634 switch (device->getVideoDriver()->getDriverType()) {
635 case video::EDT_DIRECT3D8:
636 hWnd = reinterpret_cast<HWND>(exposedData.D3D8.HWnd);
638 case video::EDT_DIRECT3D9:
639 hWnd = reinterpret_cast<HWND>(exposedData.D3D9.HWnd);
641 case video::EDT_OPENGL:
642 hWnd = reinterpret_cast<HWND>(exposedData.OpenGLWin32.HWnd);
648 // Load the ICON from resource file
649 const HICON hicon = LoadIcon(
650 GetModuleHandle(NULL),
651 MAKEINTRESOURCE(130) // The ID of the ICON defined in winresource.rc
655 SendMessage(hWnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(hicon));
656 SendMessage(hWnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(hicon));
665 bool setXorgWindowIconFromPath(IrrlichtDevice *device,
666 const std::string &icon_file)
670 video::IVideoDriver *v_driver = device->getVideoDriver();
672 video::IImageLoader *image_loader = NULL;
673 u32 cnt = v_driver->getImageLoaderCount();
674 for (u32 i = 0; i < cnt; i++) {
675 if (v_driver->getImageLoader(i)->isALoadableFileExtension(icon_file.c_str())) {
676 image_loader = v_driver->getImageLoader(i);
682 warningstream << "Could not find image loader for file '"
683 << icon_file << "'" << std::endl;
687 io::IReadFile *icon_f = device->getFileSystem()->createAndOpenFile(icon_file.c_str());
690 warningstream << "Could not load icon file '"
691 << icon_file << "'" << std::endl;
695 video::IImage *img = image_loader->loadImage(icon_f);
698 warningstream << "Could not load icon file '"
699 << icon_file << "'" << std::endl;
704 u32 height = img->getDimension().Height;
705 u32 width = img->getDimension().Width;
707 size_t icon_buffer_len = 2 + height * width;
708 long *icon_buffer = new long[icon_buffer_len];
710 icon_buffer[0] = width;
711 icon_buffer[1] = height;
713 for (u32 x = 0; x < width; x++) {
714 for (u32 y = 0; y < height; y++) {
715 video::SColor col = img->getPixel(x, y);
717 pixel_val |= (u8)col.getAlpha() << 24;
718 pixel_val |= (u8)col.getRed() << 16;
719 pixel_val |= (u8)col.getGreen() << 8;
720 pixel_val |= (u8)col.getBlue();
721 icon_buffer[2 + x + y * width] = pixel_val;
728 const video::SExposedVideoData &video_data = v_driver->getExposedVideoData();
730 Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
732 if (x11_dpl == NULL) {
733 warningstream << "Could not find x11 display for setting its icon."
735 delete [] icon_buffer;
739 Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
741 Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False);
742 Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False);
743 XChangeProperty(x11_dpl, x11_win,
744 net_wm_icon, cardinal, 32,
745 PropModeReplace, (const unsigned char *)icon_buffer,
748 delete [] icon_buffer;
755 //// Video/Display Information (Client-only)
760 static irr::IrrlichtDevice *device;
762 void initIrrlicht(irr::IrrlichtDevice *device_)
767 v2u32 getWindowSize()
769 return device->getVideoDriver()->getScreenSize();
773 std::vector<core::vector3d<u32> > getSupportedVideoModes()
775 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
776 sanity_check(nulldevice != NULL);
778 std::vector<core::vector3d<u32> > mlist;
779 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
781 u32 num_modes = modelist->getVideoModeCount();
782 for (u32 i = 0; i != num_modes; i++) {
783 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
784 s32 mode_depth = modelist->getVideoModeDepth(i);
785 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
793 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
795 std::vector<irr::video::E_DRIVER_TYPE> drivers;
797 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
798 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
799 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
805 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
807 static const char *driver_ids[] = {
818 return driver_ids[type];
822 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
824 static const char *driver_names[] = {
835 return driver_names[type];
841 static float calcDisplayDensity()
843 const char *current_display = getenv("DISPLAY");
845 if (current_display != NULL) {
846 Display *x11display = XOpenDisplay(current_display);
848 if (x11display != NULL) {
850 float dpi_height = floor(DisplayHeight(x11display, 0) /
851 (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
852 float dpi_width = floor(DisplayWidth(x11display, 0) /
853 (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
855 XCloseDisplay(x11display);
857 return std::max(dpi_height,dpi_width) / 96.0;
861 /* return manually specified dpi */
862 return g_settings->getFloat("screen_dpi")/96.0;
866 float getDisplayDensity()
868 static float cached_display_density = calcDisplayDensity();
869 return cached_display_density;
874 float getDisplayDensity()
876 return g_settings->getFloat("screen_dpi")/96.0;
880 v2u32 getDisplaySize()
882 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
884 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
885 nulldevice -> drop();
889 # endif // __ANDROID__
894 //// OS-specific Secure Random
899 bool secure_rand_fill_buf(void *buf, size_t len)
903 if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
906 CryptGenRandom(wctx, len, (BYTE *)buf);
907 CryptReleaseContext(wctx, 0);
913 bool secure_rand_fill_buf(void *buf, size_t len)
915 // N.B. This function checks *only* for /dev/urandom, because on most
916 // common OSes it is non-blocking, whereas /dev/random is blocking, and it
917 // is exceptionally uncommon for there to be a situation where /dev/random
918 // exists but /dev/urandom does not. This guesswork is necessary since
919 // random devices are not covered by any POSIX standard...
920 FILE *fp = fopen("/dev/urandom", "rb");
924 bool success = fread(buf, len, 1, fp) == 1;
932 void attachOrCreateConsole(void)
935 static bool consoleAllocated = false;
936 const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
937 if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
938 freopen("CONOUT$", "w", stdout);
939 freopen("CONOUT$", "w", stderr);
940 consoleAllocated = true;
945 // Load performance counter frequency only once at startup
948 inline double get_perf_freq()
951 QueryPerformanceFrequency(&freq);
952 return freq.QuadPart;
955 double perf_freq = get_perf_freq();
959 } //namespace porting