Use CUSTOM_LOCALEDIR if specified
[oweals/minetest.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<<DTIME<<"INFO: sigint_handler(): "
80                                 <<"Ctrl-C pressed, shutting down."<<std::endl;
81
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();*/
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 == false) {
109                         dstream << DTIME << "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                         dstream << "WARNING: 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                         dstream << "WARNING: 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                 dstream << "WARNING: 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 #ifdef STATIC_LOCALEDIR
516         path_locale = STATIC_LOCALEDIR[0] ? STATIC_LOCALEDIR : getDataPath("locale");
517 #else
518         path_locale = getDataPath("locale");
519 #endif
520
521         infostream << "Detected share path: " << path_share << std::endl;
522         infostream << "Detected user path: " << path_user << std::endl;
523 }
524
525
526
527 void setXorgClassHint(const video::SExposedVideoData &video_data,
528         const std::string &name)
529 {
530 #ifdef XORG_USED
531         if (video_data.OpenGLLinux.X11Display == NULL)
532                 return;
533
534         XClassHint *classhint = XAllocClassHint();
535         classhint->res_name  = (char *)name.c_str();
536         classhint->res_class = (char *)name.c_str();
537
538         XSetClassHint((Display *)video_data.OpenGLLinux.X11Display,
539                 video_data.OpenGLLinux.X11Window, classhint);
540         XFree(classhint);
541 #endif
542 }
543
544
545 ////
546 //// Video/Display Information (Client-only)
547 ////
548
549 #ifndef SERVER
550
551 static irr::IrrlichtDevice *device;
552
553 void initIrrlicht(irr::IrrlichtDevice *device_)
554 {
555         device = device_;
556 }
557
558 v2u32 getWindowSize()
559 {
560         return device->getVideoDriver()->getScreenSize();
561 }
562
563
564 std::vector<core::vector3d<u32> > getSupportedVideoModes()
565 {
566         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
567         sanity_check(nulldevice != NULL);
568
569         std::vector<core::vector3d<u32> > mlist;
570         video::IVideoModeList *modelist = nulldevice->getVideoModeList();
571
572         u32 num_modes = modelist->getVideoModeCount();
573         for (u32 i = 0; i != num_modes; i++) {
574                 core::dimension2d<u32> mode_res = modelist->getVideoModeResolution(i);
575                 s32 mode_depth = modelist->getVideoModeDepth(i);
576                 mlist.push_back(core::vector3d<u32>(mode_res.Width, mode_res.Height, mode_depth));
577         }
578
579         nulldevice->drop();
580
581         return mlist;
582 }
583
584 std::vector<irr::video::E_DRIVER_TYPE> getSupportedVideoDrivers()
585 {
586         std::vector<irr::video::E_DRIVER_TYPE> drivers;
587
588         for (int i = 0; i != irr::video::EDT_COUNT; i++) {
589                 if (irr::IrrlichtDevice::isDriverSupported((irr::video::E_DRIVER_TYPE)i))
590                         drivers.push_back((irr::video::E_DRIVER_TYPE)i);
591         }
592
593         return drivers;
594 }
595
596 const char *getVideoDriverName(irr::video::E_DRIVER_TYPE type)
597 {
598         static const char *driver_ids[] = {
599                 "null",
600                 "software",
601                 "burningsvideo",
602                 "direct3d8",
603                 "direct3d9",
604                 "opengl",
605                 "ogles1",
606                 "ogles2",
607         };
608
609         return driver_ids[type];
610 }
611
612
613 const char *getVideoDriverFriendlyName(irr::video::E_DRIVER_TYPE type)
614 {
615         static const char *driver_names[] = {
616                 "NULL Driver",
617                 "Software Renderer",
618                 "Burning's Video",
619                 "Direct3D 8",
620                 "Direct3D 9",
621                 "OpenGL",
622                 "OpenGL ES1",
623                 "OpenGL ES2",
624         };
625
626         return driver_names[type];
627 }
628
629 #       ifndef __ANDROID__
630 #               ifdef XORG_USED
631
632 static float calcDisplayDensity()
633 {
634         const char *current_display = getenv("DISPLAY");
635
636         if (current_display != NULL) {
637                 Display *x11display = XOpenDisplay(current_display);
638
639                 if (x11display != NULL) {
640                         /* try x direct */
641                         float dpi_height = floor(DisplayHeight(x11display, 0) /
642                                                         (DisplayHeightMM(x11display, 0) * 0.039370) + 0.5);
643                         float dpi_width = floor(DisplayWidth(x11display, 0) /
644                                                         (DisplayWidthMM(x11display, 0) * 0.039370) + 0.5);
645
646                         XCloseDisplay(x11display);
647
648                         return std::max(dpi_height,dpi_width) / 96.0;
649                 }
650         }
651
652         /* return manually specified dpi */
653         return g_settings->getFloat("screen_dpi")/96.0;
654 }
655
656
657 float getDisplayDensity()
658 {
659         static float cached_display_density = calcDisplayDensity();
660         return cached_display_density;
661 }
662
663
664 #               else // XORG_USED
665 float getDisplayDensity()
666 {
667         return g_settings->getFloat("screen_dpi")/96.0;
668 }
669 #               endif // XORG_USED
670
671 v2u32 getDisplaySize()
672 {
673         IrrlichtDevice *nulldevice = createDevice(video::EDT_NULL);
674
675         core::dimension2d<u32> deskres = nulldevice->getVideoModeList()->getDesktopResolution();
676         nulldevice -> drop();
677
678         return deskres;
679 }
680 #       endif // __ANDROID__
681 #endif // SERVER
682
683 } //namespace porting
684