]> git.lizzy.rs Git - dragonfireclient.git/blob - src/porting.cpp
Porting: Fix endless loop if image format is not recognized
[dragonfireclient.git] / src / porting.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 /*
21         Random portability stuff
22
23         See comments in porting.h
24 */
25
26 #include "porting.h"
27
28 #if defined(__FreeBSD__)
29         #include <sys/types.h>
30         #include <sys/sysctl.h>
31 #elif defined(_WIN32)
32         #include <windows.h>
33         #include <wincrypt.h>
34         #include <algorithm>
35 #endif
36 #if !defined(_WIN32)
37         #include <unistd.h>
38         #include <sys/utsname.h>
39 #endif
40 #if defined(__hpux)
41         #define _PSTAT64
42         #include <sys/pstat.h>
43 #endif
44 #if !defined(_WIN32) && !defined(__APPLE__) && \
45         !defined(__ANDROID__) && !defined(SERVER)
46         #define XORG_USED
47 #endif
48 #ifdef XORG_USED
49         #include <X11/Xlib.h>
50         #include <X11/Xutil.h>
51 #endif
52
53 #include "config.h"
54 #include "debug.h"
55 #include "filesys.h"
56 #include "log.h"
57 #include "util/string.h"
58 #include "settings.h"
59 #include <list>
60
61 namespace porting
62 {
63
64 /*
65         Signal handler (grabs Ctrl-C on POSIX systems)
66 */
67
68 bool g_killed = false;
69
70 bool * signal_handler_killstatus(void)
71 {
72         return &g_killed;
73 }
74
75 #if !defined(_WIN32) // POSIX
76         #include <signal.h>
77
78 void signal_handler(int sig)
79 {
80         if (!g_killed) {
81                 if (sig == SIGINT) {
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;
87                 }
88
89                 // Comment out for less clutter when testing scripts
90                 /*dstream << "INFO: sigint_handler(): "
91                                 << "Printing debug stacks" << std::endl;
92                 debug_stacks_print();*/
93
94                 g_killed = true;
95         } else {
96                 (void)signal(sig, SIG_DFL);
97         }
98 }
99
100 void signal_handler_init(void)
101 {
102         (void)signal(SIGINT, signal_handler);
103         (void)signal(SIGTERM, signal_handler);
104 }
105
106 #else // _WIN32
107         #include <signal.h>
108
109 BOOL WINAPI event_handler(DWORD sig)
110 {
111         switch (sig) {
112         case CTRL_C_EVENT:
113         case CTRL_CLOSE_EVENT:
114         case CTRL_LOGOFF_EVENT:
115         case CTRL_SHUTDOWN_EVENT:
116                 if (!g_killed) {
117                         dstream << "INFO: event_handler(): "
118                                 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
119                                 " shutting down." << std::endl;
120                         g_killed = true;
121                 } else {
122                         (void)signal(SIGINT, SIG_DFL);
123                 }
124                 break;
125         case CTRL_BREAK_EVENT:
126                 break;
127         }
128
129         return TRUE;
130 }
131
132 void signal_handler_init(void)
133 {
134         SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
135 }
136
137 #endif
138
139
140 /*
141         Path mangler
142 */
143
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";
149
150
151 std::string getDataPath(const char *subpath)
152 {
153         return path_share + DIR_DELIM + subpath;
154 }
155
156 void pathRemoveFile(char *path, char delim)
157 {
158         // Remove filename and path delimiter
159         int i;
160         for(i = strlen(path)-1; i>=0; i--)
161         {
162                 if(path[i] == delim)
163                         break;
164         }
165         path[i] = 0;
166 }
167
168 bool detectMSVCBuildDir(const std::string &path)
169 {
170         const char *ends[] = {
171                 "bin\\Release",
172                 "bin\\MinSizeRel",
173                 "bin\\RelWithDebInfo",
174                 "bin\\Debug",
175                 "bin\\Build",
176                 NULL
177         };
178         return (removeStringEnd(path, ends) != "");
179 }
180
181 std::string get_sysinfo()
182 {
183 #ifdef _WIN32
184         OSVERSIONINFO osvi;
185         std::ostringstream oss;
186         std::string tmp;
187         ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
188         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
189         GetVersionEx(&osvi);
190         tmp = osvi.szCSDVersion;
191         std::replace(tmp.begin(), tmp.end(), ' ', '_');
192
193         oss << "Windows/" << osvi.dwMajorVersion << "."
194                 << osvi.dwMinorVersion;
195         if (osvi.szCSDVersion[0])
196                 oss << "-" << tmp;
197         oss << " ";
198         #ifdef _WIN64
199         oss << "x86_64";
200         #else
201         BOOL is64 = FALSE;
202         if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
203                 oss << "x86_64"; // 32-bit app on 64-bit OS
204         else
205                 oss << "x86";
206         #endif
207
208         return oss.str();
209 #else
210         struct utsname osinfo;
211         uname(&osinfo);
212         return std::string(osinfo.sysname) + "/"
213                 + osinfo.release + " " + osinfo.machine;
214 #endif
215 }
216
217
218 bool getCurrentWorkingDir(char *buf, size_t len)
219 {
220 #ifdef _WIN32
221         DWORD ret = GetCurrentDirectory(len, buf);
222         return (ret != 0) && (ret <= len);
223 #else
224         return getcwd(buf, len);
225 #endif
226 }
227
228
229 bool getExecPathFromProcfs(char *buf, size_t buflen)
230 {
231 #ifndef _WIN32
232         buflen--;
233
234         ssize_t len;
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)
238                 return false;
239
240         buf[len] = '\0';
241         return true;
242 #else
243         return false;
244 #endif
245 }
246
247 //// Windows
248 #if defined(_WIN32)
249
250 bool getCurrentExecPath(char *buf, size_t len)
251 {
252         DWORD written = GetModuleFileNameA(NULL, buf, len);
253         if (written == 0 || written == len)
254                 return false;
255
256         return true;
257 }
258
259
260 //// Linux
261 #elif defined(__linux__)
262
263 bool getCurrentExecPath(char *buf, size_t len)
264 {
265         if (!getExecPathFromProcfs(buf, len))
266                 return false;
267
268         return true;
269 }
270
271
272 //// Mac OS X, Darwin
273 #elif defined(__APPLE__)
274
275 bool getCurrentExecPath(char *buf, size_t len)
276 {
277         uint32_t lenb = (uint32_t)len;
278         if (_NSGetExecutablePath(buf, &lenb) == -1)
279                 return false;
280
281         return true;
282 }
283
284
285 //// FreeBSD, NetBSD, DragonFlyBSD
286 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
287
288 bool getCurrentExecPath(char *buf, size_t len)
289 {
290         // Try getting path from procfs first, since valgrind
291         // doesn't work with the latter
292         if (getExecPathFromProcfs(buf, len))
293                 return true;
294
295         int mib[4];
296
297         mib[0] = CTL_KERN;
298         mib[1] = KERN_PROC;
299         mib[2] = KERN_PROC_PATHNAME;
300         mib[3] = -1;
301
302         if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
303                 return false;
304
305         return true;
306 }
307
308
309 //// Solaris
310 #elif defined(__sun) || defined(sun)
311
312 bool getCurrentExecPath(char *buf, size_t len)
313 {
314         const char *exec = getexecname();
315         if (exec == NULL)
316                 return false;
317
318         if (strlcpy(buf, exec, len) >= len)
319                 return false;
320
321         return true;
322 }
323
324
325 // HP-UX
326 #elif defined(__hpux)
327
328 bool getCurrentExecPath(char *buf, size_t len)
329 {
330         struct pst_status psts;
331
332         if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
333                 return false;
334
335         if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
336                 return false;
337
338         return true;
339 }
340
341
342 #else
343
344 bool getCurrentExecPath(char *buf, size_t len)
345 {
346         return false;
347 }
348
349 #endif
350
351
352 //// Windows
353 #if defined(_WIN32)
354
355 bool setSystemPaths()
356 {
357         char buf[BUFSIZ];
358
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, '\\');
363
364         // Use ".\bin\.."
365         path_share = std::string(buf) + "\\..";
366
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");
370
371         path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
372         return true;
373 }
374
375
376 //// Linux
377 #elif defined(__linux__)
378
379 bool setSystemPaths()
380 {
381         char buf[BUFSIZ];
382
383         if (!getCurrentExecPath(buf, sizeof(buf))) {
384 #ifdef __ANDROID__
385                 errorstream << "Unable to read bindir "<< std::endl;
386 #else
387                 FATAL_ERROR("Unable to read bindir");
388 #endif
389                 return false;
390         }
391
392         pathRemoveFile(buf, '/');
393         std::string bindir(buf);
394
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);
401
402         trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
403                 DIR_DELIM + PROJECT_NAME);
404         trylist.push_back(bindir + DIR_DELIM "..");
405
406 #ifdef __ANDROID__
407         trylist.push_back(path_user);
408 #endif
409
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;
417                         continue;
418                 }
419
420                 // Warn if was not the first alternative
421                 if (i != trylist.begin()) {
422                         warningstream << "system-wide share found at \""
423                                         << trypath << "\"" << std::endl;
424                 }
425
426                 path_share = trypath;
427                 break;
428         }
429
430 #ifndef __ANDROID__
431         path_user = std::string(getenv("HOME")) + DIR_DELIM "."
432                 + PROJECT_NAME;
433 #endif
434
435         return true;
436 }
437
438
439 //// Mac OS X
440 #elif defined(__APPLE__)
441
442 bool setSystemPaths()
443 {
444         CFBundleRef main_bundle = CFBundleGetMainBundle();
445         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
446         char path[PATH_MAX];
447         if (CFURLGetFileSystemRepresentation(resources_url,
448                         TRUE, (UInt8 *)path, PATH_MAX)) {
449                 path_share = std::string(path);
450         } else {
451                 warningstream << "Could not determine bundle resource path" << std::endl;
452         }
453         CFRelease(resources_url);
454
455         path_user = std::string(getenv("HOME"))
456                 + "/Library/Application Support/"
457                 + PROJECT_NAME;
458         return true;
459 }
460
461
462 #else
463
464 bool setSystemPaths()
465 {
466         path_share = STATIC_SHAREDIR;
467         path_user  = std::string(getenv("HOME")) + DIR_DELIM "."
468                 + lowercase(PROJECT_NAME);
469         return true;
470 }
471
472
473 #endif
474
475 void migrateCachePath()
476 {
477         const std::string local_cache_path = path_user + DIR_DELIM + "cache";
478
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");
483
484         // Bail if migration impossible
485         if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
486                         || fs::PathExists(path_cache)) {
487                 return;
488         }
489         if (!fs::Rename(local_cache_path, path_cache)) {
490                 errorstream << "Failed to migrate local cache path "
491                         "to system path!" << std::endl;
492         }
493 }
494
495 void initializePaths()
496 {
497 #if RUN_IN_PLACE
498         char buf[BUFSIZ];
499
500         infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
501
502         bool success =
503                 getCurrentExecPath(buf, sizeof(buf)) ||
504                 getExecPathFromProcfs(buf, sizeof(buf));
505
506         if (success) {
507                 pathRemoveFile(buf, DIR_DELIM_CHAR);
508                 std::string execpath(buf);
509
510                 path_share = execpath + DIR_DELIM "..";
511                 path_user  = execpath + DIR_DELIM "..";
512
513                 if (detectMSVCBuildDir(execpath)) {
514                         path_share += DIR_DELIM "..";
515                         path_user  += DIR_DELIM "..";
516                 }
517         } else {
518                 errorstream << "Failed to get paths by executable location, "
519                         "trying cwd" << std::endl;
520
521                 if (!getCurrentWorkingDir(buf, sizeof(buf)))
522                         FATAL_ERROR("Ran out of methods to get paths");
523
524                 size_t cwdlen = strlen(buf);
525                 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
526                         cwdlen--;
527                         buf[cwdlen] = '\0';
528                 }
529
530                 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
531                         pathRemoveFile(buf, DIR_DELIM_CHAR);
532
533                 std::string execpath(buf);
534
535                 path_share = execpath;
536                 path_user  = execpath;
537         }
538         path_cache = path_user + DIR_DELIM + "cache";
539 #else
540         infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
541
542         if (!setSystemPaths())
543                 errorstream << "Failed to get one or more system-wide path" << std::endl;
544
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");
549         if (cache_dir) {
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;
555         } else {
556                 // If neither works, use $PATH_USER/cache
557                 path_cache = path_user + DIR_DELIM + "cache";
558         }
559         // Migrate cache folder to new location if possible
560         migrateCachePath();
561 #endif
562
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;
566
567 #ifdef USE_GETTEXT
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;
574         } else {
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;
581                 }
582         }
583 #  else
584         path_locale = getDataPath("locale");
585         if (fs::PathExists(path_locale)) {
586                 found_localedir = true;
587         }
588 #  endif
589         if (!found_localedir) {
590                 warningstream << "Couldn't find a locale directory!" << std::endl;
591         }
592 #endif  // USE_GETTEXT
593 }
594
595
596
597 void setXorgClassHint(const video::SExposedVideoData &video_data,
598         const std::string &name)
599 {
600 #ifdef XORG_USED
601         if (video_data.OpenGLLinux.X11Display == NULL)
602                 return;
603
604         XClassHint *classhint = XAllocClassHint();
605         classhint->res_name  = (char *)name.c_str();
606         classhint->res_class = (char *)name.c_str();
607
608         XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
609                 video_data.OpenGLLinux.X11Window, classhint);
610         XFree(classhint);
611 #endif
612 }
613
614 bool setXorgWindowIcon(IrrlichtDevice *device,
615         const std::string &icon_file)
616 {
617 #ifdef XORG_USED
618
619         video::IVideoDriver *v_driver = device->getVideoDriver();
620
621         video::IImageLoader *image_loader = NULL;
622         u32 cnt = v_driver->getImageLoaderCount();
623         for (u32 i = 0; i < cnt; i++) {
624                 if (v_driver->getImageLoader(i)->isALoadableFileExtension(icon_file.c_str())) {
625                         image_loader = v_driver->getImageLoader(i);
626                         break;
627                 }
628         }
629
630         if (!image_loader) {
631                 warningstream << "Could not find image loader for file '"
632                         << icon_file << "'" << std::endl;
633                 return false;
634         }
635
636         io::IReadFile *icon_f = device->getFileSystem()->createAndOpenFile(icon_file.c_str());
637
638         if (!icon_f) {
639                 warningstream << "Could not load icon file '"
640                         << icon_file << "'" << std::endl;
641                 return false;
642         }
643
644         video::IImage *img = image_loader->loadImage(icon_f);
645
646         if (!img) {
647                 warningstream << "Could not load icon file '"
648                         << icon_file << "'" << std::endl;
649                 icon_f->drop();
650                 return false;
651         }
652
653         u32 height = img->getDimension().Height;
654         u32 width = img->getDimension().Width;
655
656         size_t icon_buffer_len = 2 + height * width;
657         long *icon_buffer = new long[icon_buffer_len];
658
659         icon_buffer[0] = width;
660         icon_buffer[1] = height;
661
662         for (u32 x = 0; x < width; x++) {
663                 for (u32 y = 0; y < height; y++) {
664                         video::SColor col = img->getPixel(x, y);
665                         long pixel_val = 0;
666                         pixel_val |= (u8)col.getAlpha() << 24;
667                         pixel_val |= (u8)col.getRed() << 16;
668                         pixel_val |= (u8)col.getGreen() << 8;
669                         pixel_val |= (u8)col.getBlue();
670                         icon_buffer[2 + x + y * width] = pixel_val;
671                 }
672         }
673
674         img->drop();
675         icon_f->drop();
676
677         const video::SExposedVideoData &video_data = v_driver->getExposedVideoData();
678
679         Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
680
681         if (x11_dpl == NULL) {
682                 warningstream << "Could not find x11 display for setting its icon."
683                         << std::endl;
684                 delete [] icon_buffer;
685                 return false;
686         }
687
688         Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
689
690         Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False);
691         Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False);
692         XChangeProperty(x11_dpl, x11_win,
693                 net_wm_icon, cardinal, 32,
694                 PropModeReplace, (const unsigned char *)icon_buffer,
695                 icon_buffer_len);
696
697         delete [] icon_buffer;
698
699 #endif
700         return true;
701 }
702
703 ////
704 //// Video/Display Information (Client-only)
705 ////
706
707 #ifndef SERVER
708
709 static irr::IrrlichtDevice *device;
710
711 void initIrrlicht(irr::IrrlichtDevice *device_)
712 {
713         device = device_;
714 }
715
716 v2u32 getWindowSize()
717 {
718         return device->getVideoDriver()->getScreenSize();
719 }
720
721
722 std::vector<core::vector3d<u32> > getSupportedVideoModes()
723 {
724         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
725         sanity_check(nulldevice != NULL);
726
727         std::vector<core::vector3d<u32> > mlist;
728         video::IVideoModeList *modelist = nulldevice->getVideoModeList();
729
730         u32 num_modes = modelist->getVideoModeCount();
731         for (u32 i = 0; i != num_modes; i++) {
732                 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
733                 s32 mode_depth = modelist->getVideoModeDepth(i);
734                 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
735         }
736
737         nulldevice->drop();
738
739         return mlist;
740 }
741
742 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
743 {
744         std::vector<irr::video::E_DRIVER_TYPE> drivers;
745
746         for (int i = 0; i != irr::video::EDT_COUNT; i++) {
747                 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
748                         drivers.push_back((irr::video::E_DRIVER_TYPE)i);
749         }
750
751         return drivers;
752 }
753
754 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
755 {
756         static const char *driver_ids[] = {
757                 "null",
758                 "software",
759                 "burningsvideo",
760                 "direct3d8",
761                 "direct3d9",
762                 "opengl",
763                 "ogles1",
764                 "ogles2",
765         };
766
767         return driver_ids[type];
768 }
769
770
771 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
772 {
773         static const char *driver_names[] = {
774                 "NULL Driver",
775                 "Software Renderer",
776                 "Burning's Video",
777                 "Direct3D 8",
778                 "Direct3D 9",
779                 "OpenGL",
780                 "OpenGL ES1",
781                 "OpenGL ES2",
782         };
783
784         return driver_names[type];
785 }
786
787 #       ifndef __ANDROID__
788 #               ifdef XORG_USED
789
790 static float calcDisplayDensity()
791 {
792         const char *current_display = getenv("DISPLAY");
793
794         if (current_display != NULL) {
795                 Display *x11display = XOpenDisplay(current_display);
796
797                 if (x11display != NULL) {
798                         /* try x direct */
799                         float dpi_height = floor(DisplayHeight(x11display, 0) /
800                                                         (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
801                         float dpi_width = floor(DisplayWidth(x11display, 0) /
802                                                         (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
803
804                         XCloseDisplay(x11display);
805
806                         return std::max(dpi_height,dpi_width) / 96.0;
807                 }
808         }
809
810         /* return manually specified dpi */
811         return g_settings->getFloat("screen_dpi")/96.0;
812 }
813
814
815 float getDisplayDensity()
816 {
817         static float cached_display_density = calcDisplayDensity();
818         return cached_display_density;
819 }
820
821
822 #               else // XORG_USED
823 float getDisplayDensity()
824 {
825         return g_settings->getFloat("screen_dpi")/96.0;
826 }
827 #               endif // XORG_USED
828
829 v2u32 getDisplaySize()
830 {
831         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
832
833         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
834         nulldevice -> drop();
835
836         return deskres;
837 }
838 #       endif // __ANDROID__
839 #endif // SERVER
840
841
842 ////
843 //// OS-specific Secure Random
844 ////
845
846 #ifdef WIN32
847
848 bool secure_rand_fill_buf(void *buf, size_t len)
849 {
850         HCRYPTPROV wctx;
851
852         if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
853                 return false;
854
855         CryptGenRandom(wctx, len, (BYTE *)buf);
856         CryptReleaseContext(wctx, 0);
857         return true;
858 }
859
860 #else
861
862 bool secure_rand_fill_buf(void *buf, size_t len)
863 {
864         // N.B.  This function checks *only* for /dev/urandom, because on most
865         // common OSes it is non-blocking, whereas /dev/random is blocking, and it
866         // is exceptionally uncommon for there to be a situation where /dev/random
867         // exists but /dev/urandom does not.  This guesswork is necessary since
868         // random devices are not covered by any POSIX standard...
869         FILE *fp = fopen("/dev/urandom", "rb");
870         if (!fp)
871                 return false;
872
873         bool success = fread(buf, len, 1, fp) == 1;
874
875         fclose(fp);
876         return success;
877 }
878
879 #endif
880
881 } //namespace porting