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