]> git.lizzy.rs Git - dragonfireclient.git/blob - src/porting.cpp
Use warningstream for log messages with WARNING
[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 <algorithm>
33 #endif
34 #if !defined(_WIN32)
35         #include <unistd.h>
36         #include <sys/utsname.h>
37 #endif
38 #if defined(__hpux)
39         #define _PSTAT64
40         #include <sys/pstat.h>
41 #endif
42 #if !defined(_WIN32) && !defined(__APPLE__) && \
43         !defined(__ANDROID__) && !defined(SERVER)
44         #define XORG_USED
45 #endif
46 #ifdef XORG_USED
47         #include <X11/Xlib.h>
48         #include <X11/Xutil.h>
49 #endif
50
51 #include "config.h"
52 #include "debug.h"
53 #include "filesys.h"
54 #include "log.h"
55 #include "util/string.h"
56 #include "settings.h"
57 #include <list>
58
59 namespace porting
60 {
61
62 /*
63         Signal handler (grabs Ctrl-C on POSIX systems)
64 */
65
66 bool g_killed = false;
67
68 bool * signal_handler_killstatus(void)
69 {
70         return &g_killed;
71 }
72
73 #if !defined(_WIN32) // POSIX
74         #include <signal.h>
75
76 void sigint_handler(int sig)
77 {
78         if (!g_killed) {
79                 dstream << "INFO: sigint_handler(): "
80                         << "Ctrl-C pressed, shutting down." << std::endl;
81
82                 // Comment out for less clutter when testing scripts
83                 /*dstream << "INFO: sigint_handler(): "
84                                 << "Printing debug stacks" << std::endl;
85                 debug_stacks_print();*/
86
87                 g_killed = true;
88         } else {
89                 (void)signal(SIGINT, SIG_DFL);
90         }
91 }
92
93 void signal_handler_init(void)
94 {
95         (void)signal(SIGINT, sigint_handler);
96 }
97
98 #else // _WIN32
99         #include <signal.h>
100
101 BOOL WINAPI event_handler(DWORD sig)
102 {
103         switch (sig) {
104         case CTRL_C_EVENT:
105         case CTRL_CLOSE_EVENT:
106         case CTRL_LOGOFF_EVENT:
107         case CTRL_SHUTDOWN_EVENT:
108                 if (!g_killed) {
109                         dstream << "INFO: event_handler(): "
110                                 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
111                                 " shutting down." << std::endl;
112                         g_killed = true;
113                 } else {
114                         (void)signal(SIGINT, SIG_DFL);
115                 }
116                 break;
117         case CTRL_BREAK_EVENT:
118                 break;
119         }
120
121         return TRUE;
122 }
123
124 void signal_handler_init(void)
125 {
126         SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
127 }
128
129 #endif
130
131
132 /*
133         Path mangler
134 */
135
136 // Default to RUN_IN_PLACE style relative paths
137 std::string path_share = "..";
138 std::string path_user = "..";
139 std::string path_locale = path_share + DIR_DELIM + "locale";
140
141
142 std::string getDataPath(const char *subpath)
143 {
144         return path_share + DIR_DELIM + subpath;
145 }
146
147 void pathRemoveFile(char *path, char delim)
148 {
149         // Remove filename and path delimiter
150         int i;
151         for(i = strlen(path)-1; i>=0; i--)
152         {
153                 if(path[i] == delim)
154                         break;
155         }
156         path[i] = 0;
157 }
158
159 bool detectMSVCBuildDir(const std::string &path)
160 {
161         const char *ends[] = {
162                 "bin\\Release",
163                 "bin\\Debug",
164                 "bin\\Build",
165                 NULL
166         };
167         return (removeStringEnd(path, ends) != "");
168 }
169
170 std::string get_sysinfo()
171 {
172 #ifdef _WIN32
173         OSVERSIONINFO osvi;
174         std::ostringstream oss;
175         std::string tmp;
176         ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
177         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
178         GetVersionEx(&osvi);
179         tmp = osvi.szCSDVersion;
180         std::replace(tmp.begin(), tmp.end(), ' ', '_');
181
182         oss << "Windows/" << osvi.dwMajorVersion << "."
183                 << osvi.dwMinorVersion;
184         if (osvi.szCSDVersion[0])
185                 oss << "-" << tmp;
186         oss << " ";
187         #ifdef _WIN64
188         oss << "x86_64";
189         #else
190         BOOL is64 = FALSE;
191         if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
192                 oss << "x86_64"; // 32-bit app on 64-bit OS
193         else
194                 oss << "x86";
195         #endif
196
197         return oss.str();
198 #else
199         struct utsname osinfo;
200         uname(&osinfo);
201         return std::string(osinfo.sysname) + "/"
202                 + osinfo.release + " " + osinfo.machine;
203 #endif
204 }
205
206
207 bool getCurrentWorkingDir(char *buf, size_t len)
208 {
209 #ifdef _WIN32
210         DWORD ret = GetCurrentDirectory(len, buf);
211         return (ret != 0) && (ret <= len);
212 #else
213         return getcwd(buf, len);
214 #endif
215 }
216
217
218 bool getExecPathFromProcfs(char *buf, size_t buflen)
219 {
220 #ifndef _WIN32
221         buflen--;
222
223         ssize_t len;
224         if ((len = readlink("/proc/self/exe",     buf, buflen)) == -1 &&
225                 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
226                 (len = readlink("/proc/curproc/exe",  buf, buflen)) == -1)
227                 return false;
228
229         buf[len] = '\0';
230         return true;
231 #else
232         return false;
233 #endif
234 }
235
236 //// Windows
237 #if defined(_WIN32)
238
239 bool getCurrentExecPath(char *buf, size_t len)
240 {
241         DWORD written = GetModuleFileNameA(NULL, buf, len);
242         if (written == 0 || written == len)
243                 return false;
244
245         return true;
246 }
247
248
249 //// Linux
250 #elif defined(linux) || defined(__linux) || defined(__linux__)
251
252 bool getCurrentExecPath(char *buf, size_t len)
253 {
254         if (!getExecPathFromProcfs(buf, len))
255                 return false;
256
257         return true;
258 }
259
260
261 //// Mac OS X, Darwin
262 #elif defined(__APPLE__)
263
264 bool getCurrentExecPath(char *buf, size_t len)
265 {
266         uint32_t lenb = (uint32_t)len;
267         if (_NSGetExecutablePath(buf, &lenb) == -1)
268                 return false;
269
270         return true;
271 }
272
273
274 //// FreeBSD, NetBSD, DragonFlyBSD
275 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
276
277 bool getCurrentExecPath(char *buf, size_t len)
278 {
279         // Try getting path from procfs first, since valgrind
280         // doesn't work with the latter
281         if (getExecPathFromProcfs(buf, len))
282                 return true;
283
284         int mib[4];
285
286         mib[0] = CTL_KERN;
287         mib[1] = KERN_PROC;
288         mib[2] = KERN_PROC_PATHNAME;
289         mib[3] = -1;
290
291         if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
292                 return false;
293
294         return true;
295 }
296
297
298 //// Solaris
299 #elif defined(__sun) || defined(sun)
300
301 bool getCurrentExecPath(char *buf, size_t len)
302 {
303         const char *exec = getexecname();
304         if (exec == NULL)
305                 return false;
306
307         if (strlcpy(buf, exec, len) >= len)
308                 return false;
309
310         return true;
311 }
312
313
314 // HP-UX
315 #elif defined(__hpux)
316
317 bool getCurrentExecPath(char *buf, size_t len)
318 {
319         struct pst_status psts;
320
321         if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
322                 return false;
323
324         if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
325                 return false;
326
327         return true;
328 }
329
330
331 #else
332
333 bool getCurrentExecPath(char *buf, size_t len)
334 {
335         return false;
336 }
337
338 #endif
339
340
341 //// Windows
342 #if defined(_WIN32)
343
344 bool setSystemPaths()
345 {
346         char buf[BUFSIZ];
347
348         // Find path of executable and set path_share relative to it
349         FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
350                 "Failed to get current executable path");
351         pathRemoveFile(buf, '\\');
352
353         // Use ".\bin\.."
354         path_share = std::string(buf) + "\\..";
355
356         // Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
357         DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
358         FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
359
360         path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
361         return true;
362 }
363
364
365 //// Linux
366 #elif defined(linux) || defined(__linux)
367
368 bool setSystemPaths()
369 {
370         char buf[BUFSIZ];
371
372         if (!getCurrentExecPath(buf, sizeof(buf))) {
373 #ifdef __ANDROID__
374                 errorstream << "Unable to read bindir "<< std::endl;
375 #else
376                 FATAL_ERROR("Unable to read bindir");
377 #endif
378                 return false;
379         }
380
381         pathRemoveFile(buf, '/');
382         std::string bindir(buf);
383
384         // Find share directory from these.
385         // It is identified by containing the subdirectory "builtin".
386         std::list<std::string> trylist;
387         std::string static_sharedir = STATIC_SHAREDIR;
388         if (static_sharedir != "" && static_sharedir != ".")
389                 trylist.push_back(static_sharedir);
390
391         trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
392                 DIR_DELIM + PROJECT_NAME);
393         trylist.push_back(bindir + DIR_DELIM "..");
394
395 #ifdef __ANDROID__
396         trylist.push_back(path_user);
397 #endif
398
399         for (std::list<std::string>::const_iterator
400                         i = trylist.begin(); i != trylist.end(); i++) {
401                 const std::string &trypath = *i;
402                 if (!fs::PathExists(trypath) ||
403                         !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
404                         warningstream << "system-wide share not found at \""
405                                         << trypath << "\""<< std::endl;
406                         continue;
407                 }
408
409                 // Warn if was not the first alternative
410                 if (i != trylist.begin()) {
411                         warningstream << "system-wide share found at \""
412                                         << trypath << "\"" << std::endl;
413                 }
414
415                 path_share = trypath;
416                 break;
417         }
418
419 #ifndef __ANDROID__
420         path_user = std::string(getenv("HOME")) + DIR_DELIM "."
421                 + PROJECT_NAME;
422 #endif
423
424         return true;
425 }
426
427
428 //// Mac OS X
429 #elif defined(__APPLE__)
430
431 bool setSystemPaths()
432 {
433         CFBundleRef main_bundle = CFBundleGetMainBundle();
434         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
435         char path[PATH_MAX];
436         if (CFURLGetFileSystemRepresentation(resources_url,
437                         TRUE, (UInt8 *)path, PATH_MAX)) {
438                 path_share = std::string(path);
439         } else {
440                 warningstream << "Could not determine bundle resource path" << std::endl;
441         }
442         CFRelease(resources_url);
443
444         path_user = std::string(getenv("HOME"))
445                 + "/Library/Application Support/"
446                 + PROJECT_NAME;
447         return true;
448 }
449
450
451 #else
452
453 bool setSystemPaths()
454 {
455         path_share = STATIC_SHAREDIR;
456         path_user  = std::string(getenv("HOME")) + DIR_DELIM "."
457                 + lowercase(PROJECT_NAME);
458         return true;
459 }
460
461
462 #endif
463
464
465 void initializePaths()
466 {
467 #if RUN_IN_PLACE
468         char buf[BUFSIZ];
469
470         infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
471
472         bool success =
473                 getCurrentExecPath(buf, sizeof(buf)) ||
474                 getExecPathFromProcfs(buf, sizeof(buf));
475
476         if (success) {
477                 pathRemoveFile(buf, DIR_DELIM_CHAR);
478                 std::string execpath(buf);
479
480                 path_share = execpath + DIR_DELIM "..";
481                 path_user  = execpath + DIR_DELIM "..";
482
483                 if (detectMSVCBuildDir(execpath)) {
484                         path_share += DIR_DELIM "..";
485                         path_user  += DIR_DELIM "..";
486                 }
487         } else {
488                 errorstream << "Failed to get paths by executable location, "
489                         "trying cwd" << std::endl;
490
491                 if (!getCurrentWorkingDir(buf, sizeof(buf)))
492                         FATAL_ERROR("Ran out of methods to get paths");
493
494                 size_t cwdlen = strlen(buf);
495                 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
496                         cwdlen--;
497                         buf[cwdlen] = '\0';
498                 }
499
500                 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
501                         pathRemoveFile(buf, DIR_DELIM_CHAR);
502
503                 std::string execpath(buf);
504
505                 path_share = execpath;
506                 path_user  = execpath;
507         }
508 #else
509         infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
510
511         if (!setSystemPaths())
512                 errorstream << "Failed to get one or more system-wide path" << std::endl;
513
514 #endif
515
516         infostream << "Detected share path: " << path_share << std::endl;
517         infostream << "Detected user path: " << path_user << std::endl;
518
519         bool found_localedir = false;
520 #ifdef STATIC_LOCALEDIR
521         if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
522                 found_localedir = true;
523                 path_locale = STATIC_LOCALEDIR;
524                 infostream << "Using locale directory " << STATIC_LOCALEDIR << std::endl;
525         } else {
526                 path_locale = getDataPath("locale");
527                 if (fs::PathExists(path_locale)) {
528                         found_localedir = true;
529                         infostream << "Using in-place locale directory " << path_locale
530                                 << " even though a static one was provided "
531                                 << "(RUN_IN_PLACE or CUSTOM_LOCALEDIR)." << std::endl;
532                 }
533         }
534 #else
535         path_locale = getDataPath("locale");
536         if (fs::PathExists(path_locale)) {
537                 found_localedir = true;
538         }
539 #endif
540         if (!found_localedir) {
541                 errorstream << "Couldn't find a locale directory!" << std::endl;
542         }
543
544 }
545
546
547
548 void setXorgClassHint(const video::SExposedVideoData &video_data,
549         const std::string &name)
550 {
551 #ifdef XORG_USED
552         if (video_data.OpenGLLinux.X11Display == NULL)
553                 return;
554
555         XClassHint *classhint = XAllocClassHint();
556         classhint->res_name  = (char *)name.c_str();
557         classhint->res_class = (char *)name.c_str();
558
559         XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
560                 video_data.OpenGLLinux.X11Window, classhint);
561         XFree(classhint);
562 #endif
563 }
564
565
566 ////
567 //// Video/Display Information (Client-only)
568 ////
569
570 #ifndef SERVER
571
572 static irr::IrrlichtDevice *device;
573
574 void initIrrlicht(irr::IrrlichtDevice *device_)
575 {
576         device = device_;
577 }
578
579 v2u32 getWindowSize()
580 {
581         return device->getVideoDriver()->getScreenSize();
582 }
583
584
585 std::vector<core::vector3d<u32> > getSupportedVideoModes()
586 {
587         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
588         sanity_check(nulldevice != NULL);
589
590         std::vector<core::vector3d<u32> > mlist;
591         video::IVideoModeList *modelist = nulldevice->getVideoModeList();
592
593         u32 num_modes = modelist->getVideoModeCount();
594         for (u32 i = 0; i != num_modes; i++) {
595                 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
596                 s32 mode_depth = modelist->getVideoModeDepth(i);
597                 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
598         }
599
600         nulldevice->drop();
601
602         return mlist;
603 }
604
605 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
606 {
607         std::vector<irr::video::E_DRIVER_TYPE> drivers;
608
609         for (int i = 0; i != irr::video::EDT_COUNT; i++) {
610                 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
611                         drivers.push_back((irr::video::E_DRIVER_TYPE)i);
612         }
613
614         return drivers;
615 }
616
617 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
618 {
619         static const char *driver_ids[] = {
620                 "null",
621                 "software",
622                 "burningsvideo",
623                 "direct3d8",
624                 "direct3d9",
625                 "opengl",
626                 "ogles1",
627                 "ogles2",
628         };
629
630         return driver_ids[type];
631 }
632
633
634 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
635 {
636         static const char *driver_names[] = {
637                 "NULL Driver",
638                 "Software Renderer",
639                 "Burning's Video",
640                 "Direct3D 8",
641                 "Direct3D 9",
642                 "OpenGL",
643                 "OpenGL ES1",
644                 "OpenGL ES2",
645         };
646
647         return driver_names[type];
648 }
649
650 #       ifndef __ANDROID__
651 #               ifdef XORG_USED
652
653 static float calcDisplayDensity()
654 {
655         const char *current_display = getenv("DISPLAY");
656
657         if (current_display != NULL) {
658                 Display *x11display = XOpenDisplay(current_display);
659
660                 if (x11display != NULL) {
661                         /* try x direct */
662                         float dpi_height = floor(DisplayHeight(x11display, 0) /
663                                                         (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
664                         float dpi_width = floor(DisplayWidth(x11display, 0) /
665                                                         (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
666
667                         XCloseDisplay(x11display);
668
669                         return std::max(dpi_height,dpi_width) / 96.0;
670                 }
671         }
672
673         /* return manually specified dpi */
674         return g_settings->getFloat("screen_dpi")/96.0;
675 }
676
677
678 float getDisplayDensity()
679 {
680         static float cached_display_density = calcDisplayDensity();
681         return cached_display_density;
682 }
683
684
685 #               else // XORG_USED
686 float getDisplayDensity()
687 {
688         return g_settings->getFloat("screen_dpi")/96.0;
689 }
690 #               endif // XORG_USED
691
692 v2u32 getDisplaySize()
693 {
694         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
695
696         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
697         nulldevice -> drop();
698
699         return deskres;
700 }
701 #       endif // __ANDROID__
702 #endif // SERVER
703
704 } //namespace porting
705