Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / os / unix / unix.cpp
blob2583be3347327f1691647847a6ec078f855e5dca
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 */
8 /** @file unix.cpp Implementation of Unix specific file handling. */
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"
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>
25 #ifdef WITH_SDL2
26 #include <SDL.h>
27 #endif
29 #ifdef __EMSCRIPTEN__
30 # include <emscripten.h>
31 #endif
33 #ifdef __APPLE__
34 # include <sys/mount.h>
35 #elif (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L) || defined(__GLIBC__)
36 # define HAS_STATVFS
37 #endif
39 #if defined(OPENBSD) || defined(__NetBSD__) || defined(__FreeBSD__)
40 # define HAS_SYSCTL
41 #endif
43 #ifdef HAS_STATVFS
44 #include <sys/statvfs.h>
45 #endif
47 #ifdef HAS_SYSCTL
48 #include <sys/sysctl.h>
49 #endif
51 #if defined(__APPLE__)
52 # include "../macosx/macos.h"
53 #endif
55 #include "../../safeguards.h"
57 bool FiosIsRoot(const std::string &path)
59 return path == PATHSEP;
62 void FiosGetDrives(FileList &)
64 return;
67 std::optional<uint64_t> FiosGetDiskFreeSpace(const std::string &path)
69 #ifdef __APPLE__
70 struct statfs s;
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;
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;
81 bool FiosIsValidFile(const std::string &path, const struct dirent *ent, struct stat *sb)
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);
87 return stat(filename.c_str(), sb) == 0;
90 bool FiosIsHiddenFile(const struct dirent *ent)
92 return ent->d_name[0] == '.';
95 #ifdef WITH_ICONV
97 #include <iconv.h>
98 #include "../../debug.h"
99 #include "../../string_func.h"
101 const char *GetCurrentLocale(const char *param);
103 #define INTERNALCODE "UTF-8"
106 * Try and try to decipher the current locale from environmental
107 * variables. MacOSX is hardcoded, other OS's are dynamic. If no suitable
108 * locale can be found, don't do any conversion ""
110 static const char *GetLocalCode()
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, '.');
119 return (locale == nullptr) ? "" : locale + 1;
120 #endif
124 * Convert between locales, which from and which to is set in the calling
125 * functions OTTD2FS() and FS2OTTD().
127 static std::string convert_tofrom_fs(iconv_t convd, const std::string &name)
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
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');
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;
150 buf.resize(outbuf - buf.data());
151 return buf;
155 * Convert from OpenTTD's encoding to that of the local environment
156 * @param name pointer to a valid string that will be converted
157 * @return pointer to a new stringbuffer that contains the converted string
159 std::string OTTD2FS(const std::string &name)
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;
171 return convert_tofrom_fs(convd, name);
175 * Convert to OpenTTD's encoding from that of the local environment
176 * @param name valid string that will be converted
177 * @return pointer to a new stringbuffer that contains the converted string
179 std::string FS2OTTD(const std::string &name)
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;
191 return convert_tofrom_fs(convd, name);
194 #endif /* WITH_ICONV */
196 void ShowInfoI(const std::string &str)
198 fmt::print(stderr, "{}\n", str);
201 #if !defined(__APPLE__)
202 void ShowOSErrorBox(const char *buf, bool)
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);
211 #endif
213 #ifndef WITH_COCOA
214 std::optional<std::string> GetClipboardContents()
216 #ifdef WITH_SDL2
217 if (SDL_HasClipboardText() == SDL_FALSE) return std::nullopt;
219 char *clip = SDL_GetClipboardText();
220 if (clip != nullptr) {
221 std::string result = clip;
222 SDL_free(clip);
223 return result;
225 #endif
227 return std::nullopt;
229 #endif
232 #if defined(__EMSCRIPTEN__)
233 void OSOpenBrowser(const std::string &url)
235 /* Implementation in pre.js */
236 EM_ASM({ if (window["openttd_open_url"]) window.openttd_open_url($0, $1) }, url.c_str(), url.size());
238 #elif !defined( __APPLE__)
239 void OSOpenBrowser(const std::string &url)
241 pid_t child_pid = fork();
242 if (child_pid != 0) return;
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);
252 #endif /* __APPLE__ */
254 void SetCurrentThreadName([[maybe_unused]] const char *threadName)
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__) */