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<<DTIME<<"INFO: sigint_handler(): "
80 <<"Ctrl-C pressed, shutting down."<<std::endl;
82 // Comment out for less clutter when testing scripts
83 /*dstream<<DTIME<<"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:
108 if (g_killed == false) {
109 dstream << DTIME << "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 = "..";
140 std::string getDataPath(const char *subpath)
142 return path_share + DIR_DELIM + subpath;
145 void pathRemoveFile(char *path, char delim)
147 // Remove filename and path delimiter
149 for(i = strlen(path)-1; i>=0; i--)
157 bool detectMSVCBuildDir(const std::string &path)
159 const char *ends[] = {
165 return (removeStringEnd(path, ends) != "");
168 std::string get_sysinfo()
172 std::ostringstream oss;
174 ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
175 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
177 tmp = osvi.szCSDVersion;
178 std::replace(tmp.begin(), tmp.end(), ' ', '_');
180 oss << "Windows/" << osvi.dwMajorVersion << "."
181 << osvi.dwMinorVersion;
182 if (osvi.szCSDVersion[0])
189 if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
190 oss << "x86_64"; // 32-bit app on 64-bit OS
197 struct utsname osinfo;
199 return std::string(osinfo.sysname) + "/"
200 + osinfo.release + " " + osinfo.machine;
205 bool getCurrentWorkingDir(char *buf, size_t len)
208 DWORD ret = GetCurrentDirectory(len, buf);
209 return (ret != 0) && (ret <= len);
211 return getcwd(buf, len);
216 bool getExecPathFromProcfs(char *buf, size_t buflen)
222 if ((len = readlink("/proc/self/exe", buf, buflen)) == -1 &&
223 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
224 (len = readlink("/proc/curproc/exe", buf, buflen)) == -1)
237 bool getCurrentExecPath(char *buf, size_t len)
239 DWORD written = GetModuleFileNameA(NULL, buf, len);
240 if (written == 0 || written == len)
248 #elif defined(linux) || defined(__linux) || defined(__linux__)
250 bool getCurrentExecPath(char *buf, size_t len)
252 if (!getExecPathFromProcfs(buf, len))
259 //// Mac OS X, Darwin
260 #elif defined(__APPLE__)
262 bool getCurrentExecPath(char *buf, size_t len)
264 uint32_t lenb = (uint32_t)len;
265 if (_NSGetExecutablePath(buf, &lenb) == -1)
272 //// FreeBSD, NetBSD, DragonFlyBSD
273 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
275 bool getCurrentExecPath(char *buf, size_t len)
277 // Try getting path from procfs first, since valgrind
278 // doesn't work with the latter
279 if (getExecPathFromProcfs(buf, len))
286 mib[2] = KERN_PROC_PATHNAME;
289 if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
297 #elif defined(__sun) || defined(sun)
299 bool getCurrentExecPath(char *buf, size_t len)
301 const char *exec = getexecname();
305 if (strlcpy(buf, exec, len) >= len)
313 #elif defined(__hpux)
315 bool getCurrentExecPath(char *buf, size_t len)
317 struct pst_status psts;
319 if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
322 if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
331 bool getCurrentExecPath(char *buf, size_t len)
342 bool setSystemPaths()
346 // Find path of executable and set path_share relative to it
347 FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
348 "Failed to get current executable path");
349 pathRemoveFile(buf, '\\');
352 path_share = std::string(buf) + "\\..";
354 // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
355 DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
356 FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
358 path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
364 #elif defined(linux) || defined(__linux)
366 bool setSystemPaths()
370 if (!getCurrentExecPath(buf, sizeof(buf))) {
372 errorstream << "Unable to read bindir "<< std::endl;
374 FATAL_ERROR("Unable to read bindir");
379 pathRemoveFile(buf, '/');
380 std::string bindir(buf);
382 // Find share directory from these.
383 // It is identified by containing the subdirectory "builtin".
384 std::list<std::string> trylist;
385 std::string static_sharedir = STATIC_SHAREDIR;
386 if (static_sharedir != "" && static_sharedir != ".")
387 trylist.push_back(static_sharedir);
389 trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
390 DIR_DELIM + PROJECT_NAME);
391 trylist.push_back(bindir + DIR_DELIM "..");
394 trylist.push_back(path_user);
397 for (std::list<std::string>::const_iterator
398 i = trylist.begin(); i != trylist.end(); i++) {
399 const std::string &trypath = *i;
400 if (!fs::PathExists(trypath) ||
401 !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
402 dstream << "WARNING: system-wide share not found at \""
403 << trypath << "\""<< std::endl;
407 // Warn if was not the first alternative
408 if (i != trylist.begin()) {
409 dstream << "WARNING: system-wide share found at \""
410 << trypath << "\"" << std::endl;
413 path_share = trypath;
418 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
427 #elif defined(__APPLE__)
429 bool setSystemPaths()
431 CFBundleRef main_bundle = CFBundleGetMainBundle();
432 CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
434 if (CFURLGetFileSystemRepresentation(resources_url,
435 TRUE, (UInt8 *)path, PATH_MAX)) {
436 path_share = std::string(path);
438 dstream << "WARNING: Could not determine bundle resource path" << std::endl;
440 CFRelease(resources_url);
442 path_user = std::string(getenv("HOME"))
443 + "/Library/Application Support/"
451 bool setSystemPaths()
453 path_share = STATIC_SHAREDIR;
454 path_user = std::string(getenv("HOME")) + DIR_DELIM "."
455 + lowercase(PROJECT_NAME);
463 void initializePaths()
468 infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
471 getCurrentExecPath(buf, sizeof(buf)) ||
472 getExecPathFromProcfs(buf, sizeof(buf));
475 pathRemoveFile(buf, DIR_DELIM_CHAR);
476 std::string execpath(buf);
478 path_share = execpath + DIR_DELIM "..";
479 path_user = execpath + DIR_DELIM "..";
481 if (detectMSVCBuildDir(execpath)) {
482 path_share += DIR_DELIM "..";
483 path_user += DIR_DELIM "..";
486 errorstream << "Failed to get paths by executable location, "
487 "trying cwd" << std::endl;
489 if (!getCurrentWorkingDir(buf, sizeof(buf)))
490 FATAL_ERROR("Ran out of methods to get paths");
492 size_t cwdlen = strlen(buf);
493 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
498 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
499 pathRemoveFile(buf, DIR_DELIM_CHAR);
501 std::string execpath(buf);
503 path_share = execpath;
504 path_user = execpath;
508 infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
510 if (!setSystemPaths())
511 errorstream << "Failed to get one or more system-wide path" << std::endl;
515 infostream << "Detected share path: " << path_share << std::endl;
516 infostream << "Detected user path: " << path_user << std::endl;
521 void setXorgClassHint(const video::SExposedVideoData &video_data,
522 const std::string &name)
525 if (video_data.OpenGLLinux.X11Display == NULL)
528 XClassHint *classhint = XAllocClassHint();
529 classhint->res_name = (char *)name.c_str();
530 classhint->res_class = (char *)name.c_str();
532 XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
533 video_data.OpenGLLinux.X11Window, classhint);
540 //// Video/Display Information (Client-only)
545 static irr::IrrlichtDevice *device;
547 void initIrrlicht(irr::IrrlichtDevice *device_)
552 v2u32 getWindowSize()
554 return device->getVideoDriver()->getScreenSize();
558 std::vector<core::vector3d<u32> > getSupportedVideoModes()
560 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
561 sanity_check(nulldevice != NULL);
563 std::vector<core::vector3d<u32> > mlist;
564 video::IVideoModeList *modelist = nulldevice->getVideoModeList();
566 u32 num_modes = modelist->getVideoModeCount();
567 for (u32 i = 0; i != num_modes; i++) {
568 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
569 s32 mode_depth = modelist->getVideoModeDepth(i);
570 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
578 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
580 std::vector<irr::video::E_DRIVER_TYPE> drivers;
582 for (int i = 0; i != irr::video::EDT_COUNT; i++) {
583 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
584 drivers.push_back((irr::video::E_DRIVER_TYPE)i);
590 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
592 static const char *driver_ids[] = {
603 return driver_ids[type];
607 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
609 static const char *driver_names[] = {
620 return driver_names[type];
626 static float calcDisplayDensity()
628 const char *current_display = getenv("DISPLAY");
630 if (current_display != NULL) {
631 Display *x11display = XOpenDisplay(current_display);
633 if (x11display != NULL) {
635 float dpi_height = floor(DisplayHeight(x11display, 0) /
636 (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
637 float dpi_width = floor(DisplayWidth(x11display, 0) /
638 (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
640 XCloseDisplay(x11display);
642 return std::max(dpi_height,dpi_width) / 96.0;
646 /* return manually specified dpi */
647 return g_settings->getFloat("screen_dpi")/96.0;
651 float getDisplayDensity()
653 static float cached_display_density = calcDisplayDensity();
654 return cached_display_density;
659 float getDisplayDensity()
661 return g_settings->getFloat("screen_dpi")/96.0;
665 v2u32 getDisplaySize()
667 IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
669 core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
670 nulldevice -> drop();
674 # endif // __ANDROID__
677 } //namespace porting