]> git.lizzy.rs Git - dragonfireclient.git/blob - src/porting.cpp
Also support X11 icon for minetest copies installed via make install (#4407)
[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 {
616 #if RUN_IN_PLACE
617         return setXorgWindowIconFromPath(device,
618                         path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png");
619 #else
620         // We have semi-support for reading in-place data if we are
621         // compiled with RUN_IN_PLACE. Don't break with this and
622         // also try the path_share location.
623         return
624                 setXorgWindowIconFromPath(device,
625                         ICON_DIR "/hicolor/128x128/apps/" PROJECT_NAME ".png") ||
626                 setXorgWindowIconFromPath(device,
627                         path_share + "/misc/" PROJECT_NAME "-xorg-icon-128.png");
628 #endif
629 }
630
631 bool setXorgWindowIconFromPath(IrrlichtDevice *device,
632         const std::string &icon_file)
633 {
634 #ifdef XORG_USED
635
636         video::IVideoDriver *v_driver = device->getVideoDriver();
637
638         video::IImageLoader *image_loader = NULL;
639         u32 cnt = v_driver->getImageLoaderCount();
640         for (u32 i = 0; i < cnt; i++) {
641                 if (v_driver->getImageLoader(i)->isALoadableFileExtension(icon_file.c_str())) {
642                         image_loader = v_driver->getImageLoader(i);
643                         break;
644                 }
645         }
646
647         if (!image_loader) {
648                 warningstream << "Could not find image loader for file '"
649                         << icon_file << "'" << std::endl;
650                 return false;
651         }
652
653         io::IReadFile *icon_f = device->getFileSystem()->createAndOpenFile(icon_file.c_str());
654
655         if (!icon_f) {
656                 warningstream << "Could not load icon file '"
657                         << icon_file << "'" << std::endl;
658                 return false;
659         }
660
661         video::IImage *img = image_loader->loadImage(icon_f);
662
663         if (!img) {
664                 warningstream << "Could not load icon file '"
665                         << icon_file << "'" << std::endl;
666                 icon_f->drop();
667                 return false;
668         }
669
670         u32 height = img->getDimension().Height;
671         u32 width = img->getDimension().Width;
672
673         size_t icon_buffer_len = 2 + height * width;
674         long *icon_buffer = new long[icon_buffer_len];
675
676         icon_buffer[0] = width;
677         icon_buffer[1] = height;
678
679         for (u32 x = 0; x < width; x++) {
680                 for (u32 y = 0; y < height; y++) {
681                         video::SColor col = img->getPixel(x, y);
682                         long pixel_val = 0;
683                         pixel_val |= (u8)col.getAlpha() << 24;
684                         pixel_val |= (u8)col.getRed() << 16;
685                         pixel_val |= (u8)col.getGreen() << 8;
686                         pixel_val |= (u8)col.getBlue();
687                         icon_buffer[2 + x + y * width] = pixel_val;
688                 }
689         }
690
691         img->drop();
692         icon_f->drop();
693
694         const video::SExposedVideoData &video_data = v_driver->getExposedVideoData();
695
696         Display *x11_dpl = (Display *)video_data.OpenGLLinux.X11Display;
697
698         if (x11_dpl == NULL) {
699                 warningstream << "Could not find x11 display for setting its icon."
700                         << std::endl;
701                 delete [] icon_buffer;
702                 return false;
703         }
704
705         Window x11_win = (Window)video_data.OpenGLLinux.X11Window;
706
707         Atom net_wm_icon = XInternAtom(x11_dpl, "_NET_WM_ICON", False);
708         Atom cardinal = XInternAtom(x11_dpl, "CARDINAL", False);
709         XChangeProperty(x11_dpl, x11_win,
710                 net_wm_icon, cardinal, 32,
711                 PropModeReplace, (const unsigned char *)icon_buffer,
712                 icon_buffer_len);
713
714         delete [] icon_buffer;
715
716 #endif
717         return true;
718 }
719
720 ////
721 //// Video/Display Information (Client-only)
722 ////
723
724 #ifndef SERVER
725
726 static irr::IrrlichtDevice *device;
727
728 void initIrrlicht(irr::IrrlichtDevice *device_)
729 {
730         device = device_;
731 }
732
733 v2u32 getWindowSize()
734 {
735         return device->getVideoDriver()->getScreenSize();
736 }
737
738
739 std::vector<core::vector3d<u32> > getSupportedVideoModes()
740 {
741         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
742         sanity_check(nulldevice != NULL);
743
744         std::vector<core::vector3d<u32> > mlist;
745         video::IVideoModeList *modelist = nulldevice->getVideoModeList();
746
747         u32 num_modes = modelist->getVideoModeCount();
748         for (u32 i = 0; i != num_modes; i++) {
749                 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
750                 s32 mode_depth = modelist->getVideoModeDepth(i);
751                 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
752         }
753
754         nulldevice->drop();
755
756         return mlist;
757 }
758
759 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
760 {
761         std::vector<irr::video::E_DRIVER_TYPE> drivers;
762
763         for (int i = 0; i != irr::video::EDT_COUNT; i++) {
764                 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
765                         drivers.push_back((irr::video::E_DRIVER_TYPE)i);
766         }
767
768         return drivers;
769 }
770
771 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
772 {
773         static const char *driver_ids[] = {
774                 "null",
775                 "software",
776                 "burningsvideo",
777                 "direct3d8",
778                 "direct3d9",
779                 "opengl",
780                 "ogles1",
781                 "ogles2",
782         };
783
784         return driver_ids[type];
785 }
786
787
788 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
789 {
790         static const char *driver_names[] = {
791                 "NULL Driver",
792                 "Software Renderer",
793                 "Burning's Video",
794                 "Direct3D 8",
795                 "Direct3D 9",
796                 "OpenGL",
797                 "OpenGL ES1",
798                 "OpenGL ES2",
799         };
800
801         return driver_names[type];
802 }
803
804 #       ifndef __ANDROID__
805 #               ifdef XORG_USED
806
807 static float calcDisplayDensity()
808 {
809         const char *current_display = getenv("DISPLAY");
810
811         if (current_display != NULL) {
812                 Display *x11display = XOpenDisplay(current_display);
813
814                 if (x11display != NULL) {
815                         /* try x direct */
816                         float dpi_height = floor(DisplayHeight(x11display, 0) /
817                                                         (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
818                         float dpi_width = floor(DisplayWidth(x11display, 0) /
819                                                         (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
820
821                         XCloseDisplay(x11display);
822
823                         return std::max(dpi_height,dpi_width) / 96.0;
824                 }
825         }
826
827         /* return manually specified dpi */
828         return g_settings->getFloat("screen_dpi")/96.0;
829 }
830
831
832 float getDisplayDensity()
833 {
834         static float cached_display_density = calcDisplayDensity();
835         return cached_display_density;
836 }
837
838
839 #               else // XORG_USED
840 float getDisplayDensity()
841 {
842         return g_settings->getFloat("screen_dpi")/96.0;
843 }
844 #               endif // XORG_USED
845
846 v2u32 getDisplaySize()
847 {
848         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
849
850         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
851         nulldevice -> drop();
852
853         return deskres;
854 }
855 #       endif // __ANDROID__
856 #endif // SERVER
857
858
859 ////
860 //// OS-specific Secure Random
861 ////
862
863 #ifdef WIN32
864
865 bool secure_rand_fill_buf(void *buf, size_t len)
866 {
867         HCRYPTPROV wctx;
868
869         if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
870                 return false;
871
872         CryptGenRandom(wctx, len, (BYTE *)buf);
873         CryptReleaseContext(wctx, 0);
874         return true;
875 }
876
877 #else
878
879 bool secure_rand_fill_buf(void *buf, size_t len)
880 {
881         // N.B.  This function checks *only* for /dev/urandom, because on most
882         // common OSes it is non-blocking, whereas /dev/random is blocking, and it
883         // is exceptionally uncommon for there to be a situation where /dev/random
884         // exists but /dev/urandom does not.  This guesswork is necessary since
885         // random devices are not covered by any POSIX standard...
886         FILE *fp = fopen("/dev/urandom", "rb");
887         if (!fp)
888                 return false;
889
890         bool success = fread(buf, len, 1, fp) == 1;
891
892         fclose(fp);
893         return success;
894 }
895
896 #endif
897
898 } //namespace porting