]> git.lizzy.rs Git - dragonfireclient.git/blob - src/porting.cpp
Merge pull request #59 from PrairieAstronomer/readme_irrlicht_change
[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__)  || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__)
29         #include <sys/types.h>
30         #include <sys/sysctl.h>
31         extern char **environ;
32 #elif defined(_WIN32)
33         #include <windows.h>
34         #include <wincrypt.h>
35         #include <algorithm>
36         #include <shlwapi.h>
37         #include <shellapi.h>
38         #include <mmsystem.h>
39 #endif
40 #if !defined(_WIN32)
41         #include <unistd.h>
42         #include <sys/utsname.h>
43         #if !defined(__ANDROID__)
44                 #include <spawn.h>
45         #endif
46 #endif
47 #if defined(__hpux)
48         #define _PSTAT64
49         #include <sys/pstat.h>
50 #endif
51 #if defined(__ANDROID__)
52         #include "porting_android.h"
53 #endif
54 #if defined(__APPLE__)
55         // For _NSGetEnviron()
56         // Related: https://gitlab.haskell.org/ghc/ghc/issues/2458
57         #include <crt_externs.h>
58 #endif
59
60 #if defined(__HAIKU__)
61         #include <FindDirectory.h>
62 #endif
63
64 #include "config.h"
65 #include "debug.h"
66 #include "filesys.h"
67 #include "log.h"
68 #include "util/string.h"
69 #include <list>
70 #include <cstdarg>
71 #include <cstdio>
72
73 #if !defined(SERVER) && defined(_WIN32)
74 // On Windows export some driver-specific variables to encourage Minetest to be
75 // executed on the discrete GPU in case of systems with two. Portability is fun.
76 extern "C" {
77         __declspec(dllexport) DWORD NvOptimusEnablement = 1;
78         __declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 1;
79 }
80 #endif
81
82 namespace porting
83 {
84
85 /*
86         Signal handler (grabs Ctrl-C on POSIX systems)
87 */
88
89 bool g_killed = false;
90
91 bool *signal_handler_killstatus()
92 {
93         return &g_killed;
94 }
95
96 #if !defined(_WIN32) // POSIX
97         #include <signal.h>
98
99 void signal_handler(int sig)
100 {
101         if (!g_killed) {
102                 if (sig == SIGINT) {
103                         dstream << "INFO: signal_handler(): "
104                                 << "Ctrl-C pressed, shutting down." << std::endl;
105                 } else if (sig == SIGTERM) {
106                         dstream << "INFO: signal_handler(): "
107                                 << "got SIGTERM, shutting down." << std::endl;
108                 }
109
110                 // Comment out for less clutter when testing scripts
111                 /*dstream << "INFO: sigint_handler(): "
112                                 << "Printing debug stacks" << std::endl;
113                 debug_stacks_print();*/
114
115                 g_killed = true;
116         } else {
117                 (void)signal(sig, SIG_DFL);
118         }
119 }
120
121 void signal_handler_init(void)
122 {
123         (void)signal(SIGINT, signal_handler);
124         (void)signal(SIGTERM, signal_handler);
125 }
126
127 #else // _WIN32
128         #include <signal.h>
129
130 BOOL WINAPI event_handler(DWORD sig)
131 {
132         switch (sig) {
133         case CTRL_C_EVENT:
134         case CTRL_CLOSE_EVENT:
135         case CTRL_LOGOFF_EVENT:
136         case CTRL_SHUTDOWN_EVENT:
137                 if (!g_killed) {
138                         dstream << "INFO: event_handler(): "
139                                 << "Ctrl+C, Close Event, Logoff Event or Shutdown Event,"
140                                 " shutting down." << std::endl;
141                         g_killed = true;
142                 } else {
143                         (void)signal(SIGINT, SIG_DFL);
144                 }
145                 break;
146         case CTRL_BREAK_EVENT:
147                 break;
148         }
149
150         return TRUE;
151 }
152
153 void signal_handler_init(void)
154 {
155         SetConsoleCtrlHandler((PHANDLER_ROUTINE)event_handler, TRUE);
156 }
157
158 #endif
159
160
161 /*
162         Path mangler
163 */
164
165 // Default to RUN_IN_PLACE style relative paths
166 std::string path_share = "..";
167 std::string path_user = "..";
168 std::string path_locale = path_share + DIR_DELIM + "locale";
169 std::string path_cache = path_user + DIR_DELIM + "cache";
170
171
172 std::string getDataPath(const char *subpath)
173 {
174         return path_share + DIR_DELIM + subpath;
175 }
176
177 void pathRemoveFile(char *path, char delim)
178 {
179         // Remove filename and path delimiter
180         int i;
181         for(i = strlen(path)-1; i>=0; i--)
182         {
183                 if(path[i] == delim)
184                         break;
185         }
186         path[i] = 0;
187 }
188
189 bool detectMSVCBuildDir(const std::string &path)
190 {
191         const char *ends[] = {
192                 "bin\\Release",
193                 "bin\\MinSizeRel",
194                 "bin\\RelWithDebInfo",
195                 "bin\\Debug",
196                 "bin\\Build",
197                 NULL
198         };
199         return (!removeStringEnd(path, ends).empty());
200 }
201
202 std::string get_sysinfo()
203 {
204 #ifdef _WIN32
205
206         std::ostringstream oss;
207         LPSTR filePath = new char[MAX_PATH];
208         UINT blockSize;
209         VS_FIXEDFILEINFO *fixedFileInfo;
210
211         GetSystemDirectoryA(filePath, MAX_PATH);
212         PathAppendA(filePath, "kernel32.dll");
213
214         DWORD dwVersionSize = GetFileVersionInfoSizeA(filePath, NULL);
215         LPBYTE lpVersionInfo = new BYTE[dwVersionSize];
216
217         GetFileVersionInfoA(filePath, 0, dwVersionSize, lpVersionInfo);
218         VerQueryValueA(lpVersionInfo, "\\", (LPVOID *)&fixedFileInfo, &blockSize);
219
220         oss << "Windows/"
221                 << HIWORD(fixedFileInfo->dwProductVersionMS) << '.' // Major
222                 << LOWORD(fixedFileInfo->dwProductVersionMS) << '.' // Minor
223                 << HIWORD(fixedFileInfo->dwProductVersionLS) << ' '; // Build
224
225         #ifdef _WIN64
226         oss << "x86_64";
227         #else
228         BOOL is64 = FALSE;
229         if (IsWow64Process(GetCurrentProcess(), &is64) && is64)
230                 oss << "x86_64"; // 32-bit app on 64-bit OS
231         else
232                 oss << "x86";
233         #endif
234
235         delete[] lpVersionInfo;
236         delete[] filePath;
237
238         return oss.str();
239 #else
240         struct utsname osinfo;
241         uname(&osinfo);
242         return std::string(osinfo.sysname) + "/"
243                 + osinfo.release + " " + osinfo.machine;
244 #endif
245 }
246
247
248 bool getCurrentWorkingDir(char *buf, size_t len)
249 {
250 #ifdef _WIN32
251         DWORD ret = GetCurrentDirectory(len, buf);
252         return (ret != 0) && (ret <= len);
253 #else
254         return getcwd(buf, len);
255 #endif
256 }
257
258
259 bool getExecPathFromProcfs(char *buf, size_t buflen)
260 {
261 #ifndef _WIN32
262         buflen--;
263
264         ssize_t len;
265         if ((len = readlink("/proc/self/exe",     buf, buflen)) == -1 &&
266                 (len = readlink("/proc/curproc/file", buf, buflen)) == -1 &&
267                 (len = readlink("/proc/curproc/exe",  buf, buflen)) == -1)
268                 return false;
269
270         buf[len] = '\0';
271         return true;
272 #else
273         return false;
274 #endif
275 }
276
277 //// Windows
278 #if defined(_WIN32)
279
280 bool getCurrentExecPath(char *buf, size_t len)
281 {
282         DWORD written = GetModuleFileNameA(NULL, buf, len);
283         if (written == 0 || written == len)
284                 return false;
285
286         return true;
287 }
288
289
290 //// Linux
291 #elif defined(__linux__)
292
293 bool getCurrentExecPath(char *buf, size_t len)
294 {
295         if (!getExecPathFromProcfs(buf, len))
296                 return false;
297
298         return true;
299 }
300
301
302 //// Mac OS X, Darwin
303 #elif defined(__APPLE__)
304
305 bool getCurrentExecPath(char *buf, size_t len)
306 {
307         uint32_t lenb = (uint32_t)len;
308         if (_NSGetExecutablePath(buf, &lenb) == -1)
309                 return false;
310
311         return true;
312 }
313
314
315 //// FreeBSD, NetBSD, DragonFlyBSD
316 #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
317
318 bool getCurrentExecPath(char *buf, size_t len)
319 {
320         // Try getting path from procfs first, since valgrind
321         // doesn't work with the latter
322         if (getExecPathFromProcfs(buf, len))
323                 return true;
324
325         int mib[4];
326
327         mib[0] = CTL_KERN;
328         mib[1] = KERN_PROC;
329         mib[2] = KERN_PROC_PATHNAME;
330         mib[3] = -1;
331
332         if (sysctl(mib, 4, buf, &len, NULL, 0) == -1)
333                 return false;
334
335         return true;
336 }
337
338 #elif defined(__HAIKU__)
339
340 bool getCurrentExecPath(char *buf, size_t len)
341 {
342         return find_path(B_APP_IMAGE_SYMBOL, B_FIND_PATH_IMAGE_PATH, NULL, buf, len) == B_OK;
343 }
344
345 //// Solaris
346 #elif defined(__sun) || defined(sun)
347
348 bool getCurrentExecPath(char *buf, size_t len)
349 {
350         const char *exec = getexecname();
351         if (exec == NULL)
352                 return false;
353
354         if (strlcpy(buf, exec, len) >= len)
355                 return false;
356
357         return true;
358 }
359
360
361 // HP-UX
362 #elif defined(__hpux)
363
364 bool getCurrentExecPath(char *buf, size_t len)
365 {
366         struct pst_status psts;
367
368         if (pstat_getproc(&psts, sizeof(psts), 0, getpid()) == -1)
369                 return false;
370
371         if (pstat_getpathname(buf, len, &psts.pst_fid_text) == -1)
372                 return false;
373
374         return true;
375 }
376
377
378 #else
379
380 bool getCurrentExecPath(char *buf, size_t len)
381 {
382         return false;
383 }
384
385 #endif
386
387
388 //// Non-Windows
389 #if !defined(_WIN32)
390
391 const char *getHomeOrFail()
392 {
393         const char *home = getenv("HOME");
394         // In rare cases the HOME environment variable may be unset
395         FATAL_ERROR_IF(!home,
396                 "Required environment variable HOME is not set");
397         return home;
398 }
399
400 #endif
401
402
403 //// Windows
404 #if defined(_WIN32)
405
406 bool setSystemPaths()
407 {
408         char buf[BUFSIZ];
409
410         // Find path of executable and set path_share relative to it
411         FATAL_ERROR_IF(!getCurrentExecPath(buf, sizeof(buf)),
412                 "Failed to get current executable path");
413         pathRemoveFile(buf, '\\');
414
415         std::string exepath(buf);
416
417         // Use ".\bin\.."
418         path_share = exepath + "\\..";
419         if (detectMSVCBuildDir(exepath)) {
420                 // The msvc build dir schould normaly not be present if properly installed,
421                 // but its usefull for debugging.
422                 path_share += DIR_DELIM "..";
423         }
424
425         // Use "C:\Users\<user>\AppData\Roaming\<PROJECT_NAME_C>"
426         DWORD len = GetEnvironmentVariable("APPDATA", buf, sizeof(buf));
427         FATAL_ERROR_IF(len == 0 || len > sizeof(buf), "Failed to get APPDATA");
428
429         path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME_C;
430         return true;
431 }
432
433
434 //// Linux
435 #elif defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
436
437 bool setSystemPaths()
438 {
439         char buf[BUFSIZ];
440
441         if (!getCurrentExecPath(buf, sizeof(buf))) {
442 #ifdef __ANDROID__
443                 errorstream << "Unable to read bindir "<< std::endl;
444 #else
445                 FATAL_ERROR("Unable to read bindir");
446 #endif
447                 return false;
448         }
449
450         pathRemoveFile(buf, '/');
451         std::string bindir(buf);
452
453         // Find share directory from these.
454         // It is identified by containing the subdirectory "builtin".
455         std::list<std::string> trylist;
456         std::string static_sharedir = STATIC_SHAREDIR;
457         if (!static_sharedir.empty() && static_sharedir != ".")
458                 trylist.push_back(static_sharedir);
459
460         trylist.push_back(bindir + DIR_DELIM ".." DIR_DELIM "share"
461                 DIR_DELIM + PROJECT_NAME);
462         trylist.push_back(bindir + DIR_DELIM "..");
463
464 #ifdef __ANDROID__
465         trylist.push_back(path_user);
466 #endif
467
468         for (std::list<std::string>::const_iterator
469                         i = trylist.begin(); i != trylist.end(); ++i) {
470                 const std::string &trypath = *i;
471                 if (!fs::PathExists(trypath) ||
472                         !fs::PathExists(trypath + DIR_DELIM + "builtin")) {
473                         warningstream << "system-wide share not found at \""
474                                         << trypath << "\""<< std::endl;
475                         continue;
476                 }
477
478                 // Warn if was not the first alternative
479                 if (i != trylist.begin()) {
480                         warningstream << "system-wide share found at \""
481                                         << trypath << "\"" << std::endl;
482                 }
483
484                 path_share = trypath;
485                 break;
486         }
487
488 #ifndef __ANDROID__
489         path_user = std::string(getHomeOrFail()) + DIR_DELIM "."
490                 + PROJECT_NAME;
491 #endif
492
493         return true;
494 }
495
496
497 //// Mac OS X
498 #elif defined(__APPLE__)
499
500 bool setSystemPaths()
501 {
502         CFBundleRef main_bundle = CFBundleGetMainBundle();
503         CFURLRef resources_url = CFBundleCopyResourcesDirectoryURL(main_bundle);
504         char path[PATH_MAX];
505         if (CFURLGetFileSystemRepresentation(resources_url,
506                         TRUE, (UInt8 *)path, PATH_MAX)) {
507                 path_share = std::string(path);
508         } else {
509                 warningstream << "Could not determine bundle resource path" << std::endl;
510         }
511         CFRelease(resources_url);
512
513         path_user = std::string(getHomeOrFail())
514                 + "/Library/Application Support/"
515                 + PROJECT_NAME;
516         return true;
517 }
518
519
520 #else
521
522 bool setSystemPaths()
523 {
524         path_share = STATIC_SHAREDIR;
525         path_user  = std::string(getHomeOrFail()) + DIR_DELIM "."
526                 + lowercase(PROJECT_NAME);
527         return true;
528 }
529
530
531 #endif
532
533 void migrateCachePath()
534 {
535         const std::string local_cache_path = path_user + DIR_DELIM + "cache";
536
537         // Delete tmp folder if it exists (it only ever contained
538         // a temporary ogg file, which is no longer used).
539         if (fs::PathExists(local_cache_path + DIR_DELIM + "tmp"))
540                 fs::RecursiveDelete(local_cache_path + DIR_DELIM + "tmp");
541
542         // Bail if migration impossible
543         if (path_cache == local_cache_path || !fs::PathExists(local_cache_path)
544                         || fs::PathExists(path_cache)) {
545                 return;
546         }
547         if (!fs::Rename(local_cache_path, path_cache)) {
548                 errorstream << "Failed to migrate local cache path "
549                         "to system path!" << std::endl;
550         }
551 }
552
553 void initializePaths()
554 {
555 #if RUN_IN_PLACE
556         char buf[BUFSIZ];
557
558         infostream << "Using relative paths (RUN_IN_PLACE)" << std::endl;
559
560         bool success =
561                 getCurrentExecPath(buf, sizeof(buf)) ||
562                 getExecPathFromProcfs(buf, sizeof(buf));
563
564         if (success) {
565                 pathRemoveFile(buf, DIR_DELIM_CHAR);
566                 std::string execpath(buf);
567
568                 path_share = execpath + DIR_DELIM "..";
569                 path_user  = execpath + DIR_DELIM "..";
570
571                 if (detectMSVCBuildDir(execpath)) {
572                         path_share += DIR_DELIM "..";
573                         path_user  += DIR_DELIM "..";
574                 }
575         } else {
576                 errorstream << "Failed to get paths by executable location, "
577                         "trying cwd" << std::endl;
578
579                 if (!getCurrentWorkingDir(buf, sizeof(buf)))
580                         FATAL_ERROR("Ran out of methods to get paths");
581
582                 size_t cwdlen = strlen(buf);
583                 if (cwdlen >= 1 && buf[cwdlen - 1] == DIR_DELIM_CHAR) {
584                         cwdlen--;
585                         buf[cwdlen] = '\0';
586                 }
587
588                 if (cwdlen >= 4 && !strcmp(buf + cwdlen - 4, DIR_DELIM "bin"))
589                         pathRemoveFile(buf, DIR_DELIM_CHAR);
590
591                 std::string execpath(buf);
592
593                 path_share = execpath;
594                 path_user  = execpath;
595         }
596         path_cache = path_user + DIR_DELIM + "cache";
597 #else
598         infostream << "Using system-wide paths (NOT RUN_IN_PLACE)" << std::endl;
599
600         if (!setSystemPaths())
601                 errorstream << "Failed to get one or more system-wide path" << std::endl;
602
603
604 #  ifdef _WIN32
605         path_cache = path_user + DIR_DELIM + "cache";
606 #  else
607         // Initialize path_cache
608         // First try $XDG_CACHE_HOME/PROJECT_NAME
609         const char *cache_dir = getenv("XDG_CACHE_HOME");
610         const char *home_dir = getenv("HOME");
611         if (cache_dir && cache_dir[0] != '\0') {
612                 path_cache = std::string(cache_dir) + DIR_DELIM + PROJECT_NAME;
613         } else if (home_dir) {
614                 // Then try $HOME/.cache/PROJECT_NAME
615                 path_cache = std::string(home_dir) + DIR_DELIM + ".cache"
616                         + DIR_DELIM + PROJECT_NAME;
617         } else {
618                 // If neither works, use $PATH_USER/cache
619                 path_cache = path_user + DIR_DELIM + "cache";
620         }
621         // Migrate cache folder to new location if possible
622         migrateCachePath();
623 #  endif // _WIN32
624 #endif // RUN_IN_PLACE
625
626         infostream << "Detected share path: " << path_share << std::endl;
627         infostream << "Detected user path: " << path_user << std::endl;
628         infostream << "Detected cache path: " << path_cache << std::endl;
629
630 #if USE_GETTEXT
631         bool found_localedir = false;
632 #  ifdef STATIC_LOCALEDIR
633         /* STATIC_LOCALEDIR may be a generalized path such as /usr/share/locale that
634          * doesn't necessarily contain our locale files, so check data path first. */
635         path_locale = getDataPath("locale");
636         if (fs::PathExists(path_locale)) {
637                 found_localedir = true;
638                 infostream << "Using in-place locale directory " << path_locale
639                         << " even though a static one was provided." << std::endl;
640         } else if (STATIC_LOCALEDIR[0] && fs::PathExists(STATIC_LOCALEDIR)) {
641                 found_localedir = true;
642                 path_locale = STATIC_LOCALEDIR;
643                 infostream << "Using static locale directory " << STATIC_LOCALEDIR
644                         << std::endl;
645         }
646 #  else
647         path_locale = getDataPath("locale");
648         if (fs::PathExists(path_locale)) {
649                 found_localedir = true;
650         }
651 #  endif
652         if (!found_localedir) {
653                 warningstream << "Couldn't find a locale directory!" << std::endl;
654         }
655 #endif  // USE_GETTEXT
656 }
657
658 ////
659 //// OS-specific Secure Random
660 ////
661
662 #ifdef WIN32
663
664 bool secure_rand_fill_buf(void *buf, size_t len)
665 {
666         HCRYPTPROV wctx;
667
668         if (!CryptAcquireContext(&wctx, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
669                 return false;
670
671         CryptGenRandom(wctx, len, (BYTE *)buf);
672         CryptReleaseContext(wctx, 0);
673         return true;
674 }
675
676 #else
677
678 bool secure_rand_fill_buf(void *buf, size_t len)
679 {
680         // N.B.  This function checks *only* for /dev/urandom, because on most
681         // common OSes it is non-blocking, whereas /dev/random is blocking, and it
682         // is exceptionally uncommon for there to be a situation where /dev/random
683         // exists but /dev/urandom does not.  This guesswork is necessary since
684         // random devices are not covered by any POSIX standard...
685         FILE *fp = fopen("/dev/urandom", "rb");
686         if (!fp)
687                 return false;
688
689         bool success = fread(buf, len, 1, fp) == 1;
690
691         fclose(fp);
692         return success;
693 }
694
695 #endif
696
697 void attachOrCreateConsole()
698 {
699 #ifdef _WIN32
700         static bool consoleAllocated = false;
701         const bool redirected = (_fileno(stdout) == -2 || _fileno(stdout) == -1); // If output is redirected to e.g a file
702         if (!consoleAllocated && redirected && (AttachConsole(ATTACH_PARENT_PROCESS) || AllocConsole())) {
703                 freopen("CONOUT$", "w", stdout);
704                 freopen("CONOUT$", "w", stderr);
705                 consoleAllocated = true;
706         }
707 #endif
708 }
709
710 int mt_snprintf(char *buf, const size_t buf_size, const char *fmt, ...)
711 {
712         // https://msdn.microsoft.com/en-us/library/bt7tawza.aspx
713         //  Many of the MSVC / Windows printf-style functions do not support positional
714         //  arguments (eg. "%1$s"). We just forward the call to vsnprintf for sane
715         //  platforms, but defer to _vsprintf_p on MSVC / Windows.
716         // https://github.com/FFmpeg/FFmpeg/blob/5ae9fa13f5ac640bec113120d540f70971aa635d/compat/msvcrt/snprintf.c#L46
717         //  _vsprintf_p has to be shimmed with _vscprintf_p on -1 (for an example see
718         //  above FFmpeg link).
719         va_list args;
720         va_start(args, fmt);
721 #ifndef _MSC_VER
722         int c = vsnprintf(buf, buf_size, fmt, args);
723 #else  // _MSC_VER
724         int c = _vsprintf_p(buf, buf_size, fmt, args);
725         if (c == -1)
726                 c = _vscprintf_p(fmt, args);
727 #endif // _MSC_VER
728         va_end(args);
729         return c;
730 }
731
732 static bool open_uri(const std::string &uri)
733 {
734         if (uri.find_first_of("\r\n") != std::string::npos) {
735                 errorstream << "Unable to open URI as it is invalid, contains new line: " << uri << std::endl;
736                 return false;
737         }
738
739 #if defined(_WIN32)
740         return (intptr_t)ShellExecuteA(NULL, NULL, uri.c_str(), NULL, NULL, SW_SHOWNORMAL) > 32;
741 #elif defined(__ANDROID__)
742         openURIAndroid(uri);
743         return true;
744 #elif defined(__APPLE__)
745         const char *argv[] = {"open", uri.c_str(), NULL};
746         return posix_spawnp(NULL, "open", NULL, NULL, (char**)argv,
747                 (*_NSGetEnviron())) == 0;
748 #else
749         const char *argv[] = {"xdg-open", uri.c_str(), NULL};
750         return posix_spawnp(NULL, "xdg-open", NULL, NULL, (char**)argv, environ) == 0;
751 #endif
752 }
753
754 bool open_url(const std::string &url)
755 {
756         if (url.substr(0, 7) != "http://" && url.substr(0, 8) != "https://") {
757                 errorstream << "Unable to open browser as URL is missing schema: " << url << std::endl;
758                 return false;
759         }
760
761         return open_uri(url);
762 }
763
764 bool open_directory(const std::string &path)
765 {
766         if (!fs::IsDir(path)) {
767                 errorstream << "Unable to open directory as it does not exist: " << path << std::endl;
768                 return false;
769         }
770
771         return open_uri(path);
772 }
773
774 // Load performance counter frequency only once at startup
775 #ifdef _WIN32
776
777 inline double get_perf_freq()
778 {
779         // Also use this opportunity to enable high-res timers
780         timeBeginPeriod(1);
781
782         LARGE_INTEGER freq;
783         QueryPerformanceFrequency(&freq);
784         return freq.QuadPart;
785 }
786
787 double perf_freq = get_perf_freq();
788
789 #endif
790
791 } //namespace porting