OpenTTD Source  14.0-beta1
unix.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "../../stdafx.h"
11 #include "../../textbuf_gui.h"
12 #include "../../debug.h"
13 #include "../../string_func.h"
14 #include "../../fios.h"
15 #include "../../thread.h"
16 
17 
18 #include <dirent.h>
19 #include <unistd.h>
20 #include <sys/stat.h>
21 #include <time.h>
22 #include <signal.h>
23 #include <pthread.h>
24 
25 #ifdef WITH_SDL2
26 #include <SDL.h>
27 #endif
28 
29 #ifdef __EMSCRIPTEN__
30 # include <emscripten.h>
31 #endif
32 
33 #ifdef __APPLE__
34 # include <sys/mount.h>
35 #elif (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L) || defined(__GLIBC__)
36 # define HAS_STATVFS
37 #endif
38 
39 #if defined(OPENBSD) || defined(__NetBSD__) || defined(__FreeBSD__)
40 # define HAS_SYSCTL
41 #endif
42 
43 #ifdef HAS_STATVFS
44 #include <sys/statvfs.h>
45 #endif
46 
47 #ifdef HAS_SYSCTL
48 #include <sys/sysctl.h>
49 #endif
50 
51 #if defined(__APPLE__)
52 # include "../macosx/macos.h"
53 #endif
54 
55 #include "../../safeguards.h"
56 
57 bool FiosIsRoot(const std::string &path)
58 {
59  return path == PATHSEP;
60 }
61 
62 void FiosGetDrives(FileList &)
63 {
64  return;
65 }
66 
67 std::optional<uint64_t> FiosGetDiskFreeSpace(const std::string &path)
68 {
69 #ifdef __APPLE__
70  struct statfs s;
71 
72  if (statfs(path.c_str(), &s) == 0) return static_cast<uint64_t>(s.f_bsize) * s.f_bavail;
73 #elif defined(HAS_STATVFS)
74  struct statvfs s;
75 
76  if (statvfs(path.c_str(), &s) == 0) return static_cast<uint64_t>(s.f_frsize) * s.f_bavail;
77 #endif
78  return std::nullopt;
79 }
80 
81 bool FiosIsValidFile(const std::string &path, const struct dirent *ent, struct stat *sb)
82 {
83  assert(path.back() == PATHSEPCHAR);
84  if (path.size() > 2) assert(path[path.size() - 2] != PATHSEPCHAR);
85  std::string filename = fmt::format("{}{}", path, ent->d_name);
86 
87  return stat(filename.c_str(), sb) == 0;
88 }
89 
90 bool FiosIsHiddenFile(const struct dirent *ent)
91 {
92  return ent->d_name[0] == '.';
93 }
94 
95 #ifdef WITH_ICONV
96 
97 #include <iconv.h>
98 #include "../../debug.h"
99 #include "../../string_func.h"
100 
101 const char *GetCurrentLocale(const char *param);
102 
103 #define INTERNALCODE "UTF-8"
104 
110 static const char *GetLocalCode()
111 {
112 #if defined(__APPLE__)
113  return "UTF-8-MAC";
114 #else
115  /* Strip locale (eg en_US.UTF-8) to only have UTF-8 */
116  const char *locale = GetCurrentLocale("LC_CTYPE");
117  if (locale != nullptr) locale = strchr(locale, '.');
118 
119  return (locale == nullptr) ? "" : locale + 1;
120 #endif
121 }
122 
127 static std::string convert_tofrom_fs(iconv_t convd, const std::string &name)
128 {
129  /* There are different implementations of iconv. The older ones,
130  * e.g. SUSv2, pass a const pointer, whereas the newer ones, e.g.
131  * IEEE 1003.1 (2004), pass a non-const pointer. */
132 #ifdef HAVE_NON_CONST_ICONV
133  char *inbuf = const_cast<char*>(name.data());
134 #else
135  const char *inbuf = name.data();
136 #endif
137 
138  /* If the output is UTF-32, then 1 ASCII character becomes 4 bytes. */
139  size_t inlen = name.size();
140  std::string buf(inlen * 4, '\0');
141 
142  size_t outlen = buf.size();
143  char *outbuf = buf.data();
144  iconv(convd, nullptr, nullptr, nullptr, nullptr);
145  if (iconv(convd, &inbuf, &inlen, &outbuf, &outlen) == (size_t)(-1)) {
146  Debug(misc, 0, "[iconv] error converting '{}'. Errno {}", name, errno);
147  return name;
148  }
149 
150  buf.resize(outbuf - buf.data());
151  return buf;
152 }
153 
159 std::string OTTD2FS(const std::string &name)
160 {
161  static iconv_t convd = (iconv_t)(-1);
162  if (convd == (iconv_t)(-1)) {
163  const char *env = GetLocalCode();
164  convd = iconv_open(env, INTERNALCODE);
165  if (convd == (iconv_t)(-1)) {
166  Debug(misc, 0, "[iconv] conversion from codeset '{}' to '{}' unsupported", INTERNALCODE, env);
167  return name;
168  }
169  }
170 
171  return convert_tofrom_fs(convd, name);
172 }
173 
179 std::string FS2OTTD(const std::string &name)
180 {
181  static iconv_t convd = (iconv_t)(-1);
182  if (convd == (iconv_t)(-1)) {
183  const char *env = GetLocalCode();
184  convd = iconv_open(INTERNALCODE, env);
185  if (convd == (iconv_t)(-1)) {
186  Debug(misc, 0, "[iconv] conversion from codeset '{}' to '{}' unsupported", env, INTERNALCODE);
187  return name;
188  }
189  }
190 
191  return convert_tofrom_fs(convd, name);
192 }
193 
194 #endif /* WITH_ICONV */
195 
196 void ShowInfoI(const std::string &str)
197 {
198  fmt::print(stderr, "{}\n", str);
199 }
200 
201 #if !defined(__APPLE__)
202 void ShowOSErrorBox(const char *buf, bool)
203 {
204  /* All unix systems, except OSX. Only use escape codes on a TTY. */
205  if (isatty(fileno(stderr))) {
206  fmt::print(stderr, "\033[1;31mError: {}\033[0;39m\n", buf);
207  } else {
208  fmt::print(stderr, "Error: {}\n", buf);
209  }
210 }
211 #endif
212 
213 #ifndef WITH_COCOA
214 std::optional<std::string> GetClipboardContents()
215 {
216 #ifdef WITH_SDL2
217  if (SDL_HasClipboardText() == SDL_FALSE) return std::nullopt;
218 
219  char *clip = SDL_GetClipboardText();
220  if (clip != nullptr) {
221  std::string result = clip;
222  SDL_free(clip);
223  return result;
224  }
225 #endif
226 
227  return std::nullopt;
228 }
229 #endif
230 
231 
232 #if defined(__EMSCRIPTEN__)
233 void OSOpenBrowser(const std::string &url)
234 {
235  /* Implementation in pre.js */
236  EM_ASM({ if (window["openttd_open_url"]) window.openttd_open_url($0, $1) }, url.c_str(), url.size());
237 }
238 #elif !defined( __APPLE__)
239 void OSOpenBrowser(const std::string &url)
240 {
241  pid_t child_pid = fork();
242  if (child_pid != 0) return;
243 
244  const char *args[3];
245  args[0] = "xdg-open";
246  args[1] = url.c_str();
247  args[2] = nullptr;
248  execvp(args[0], const_cast<char * const *>(args));
249  Debug(misc, 0, "Failed to open url: {}", url);
250  exit(0);
251 }
252 #endif /* __APPLE__ */
253 
254 void SetCurrentThreadName([[maybe_unused]] const char *threadName)
255 {
256 #if defined(__GLIBC__)
257  if (threadName) pthread_setname_np(pthread_self(), threadName);
258 #endif /* defined(__GLIBC__) */
259 #if defined(__APPLE__)
260  MacOSSetThreadName(threadName);
261 #endif /* defined(__APPLE__) */
262 }
FileList
List of file information.
Definition: fios.h:88
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
FS2OTTD
std::string FS2OTTD(const std::wstring &name)
Convert to OpenTTD's encoding from a wide string.
Definition: win32.cpp:462
GetCurrentLocale
const char * GetCurrentLocale(const char *)
Determine the current user's locale.
Definition: win32.cpp:527
GetClipboardContents
std::optional< std::string > GetClipboardContents()
Try to retrieve the current clipboard contents.
Definition: unix.cpp:214
OTTD2FS
std::wstring OTTD2FS(const std::string &name)
Convert from OpenTTD's encoding to a wide string.
Definition: win32.cpp:479