19#include <processthreadsapi.h>
21#define NO_SHOBJIDL_SORTDIRECTION
34#include "table/strings.h"
38static bool _has_console;
39static bool _cursor_disable =
true;
40static bool _cursor_visible =
true;
42bool MyShowCursor(
bool show,
bool toggle)
44 if (toggle) _cursor_disable = !_cursor_disable;
45 if (_cursor_disable)
return show;
46 if (_cursor_visible == show)
return show;
48 _cursor_visible = show;
57 MessageBox(GetActiveWindow(),
OTTD2FS(buf).c_str(), L
"Error!", MB_ICONSTOP | MB_TASKMODAL);
62 ShellExecute(GetActiveWindow(), L
"open",
OTTD2FS(url).c_str(),
nullptr,
nullptr, SW_SHOWNORMAL);
65bool FiosIsRoot(
const std::string &file)
67 return file.size() == 3;
70void FiosGetDrives(
FileList &file_list)
75 GetLogicalDriveStrings(
static_cast<DWORD
>(std::size(drives)), drives);
76 for (s = drives; *s !=
'\0';) {
77 FiosItem *fios = &file_list.emplace_back();
78 fios->type = FIOS_TYPE_DRIVE;
80 fios->name += (char)(s[0] & 0xFF);
83 while (*s++ !=
'\0') { }
87bool FiosIsHiddenFile(
const std::filesystem::path &path)
89 UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS);
91 DWORD attributes = GetFileAttributes(path.c_str());
95 return (attributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) != 0;
98std::optional<uint64_t> FiosGetDiskFreeSpace(
const std::string &path)
100 UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS);
102 ULARGE_INTEGER bytes_free;
103 bool retval = GetDiskFreeSpaceEx(
OTTD2FS(path).c_str(), &bytes_free,
nullptr,
nullptr);
107 if (retval)
return bytes_free.QuadPart;
114 CONSOLE_SCREEN_BUFFER_INFO coninfo;
116 if (_has_console)
return;
119 if (!AllocConsole())
return;
121 hand = GetStdHandle(STD_OUTPUT_HANDLE);
122 GetConsoleScreenBufferInfo(hand, &coninfo);
123 coninfo.dwSize.Y = 500;
124 SetConsoleScreenBufferSize(hand, coninfo.dwSize);
127#if !defined(__CYGWIN__)
130 int fd = _open_osfhandle((intptr_t)hand, _O_TEXT);
134 _has_console =
false;
138 ShowInfo(
"Unable to open an output handle to the console. Check known-bugs.md for details.");
143 freopen(
"CONOUT$",
"a", stdout);
144 freopen(
"CONIN$",
"r", stdin);
145 freopen(
"CONOUT$",
"a", stderr);
147 *stdout = *_fdopen(fd,
"w");
148 *stdin = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT),
"r" );
149 *stderr = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT),
"w" );
154 *stdout = *fdopen(1,
"w" );
155 *stdin = *fdopen(0,
"r" );
156 *stderr = *fdopen(2,
"w" );
159 setvbuf(stdin,
nullptr, _IONBF, 0);
160 setvbuf(stdout,
nullptr, _IONBF, 0);
161 setvbuf(stderr,
nullptr, _IONBF, 0);
175 while ((next = msg.find(
'\n', last)) != std::string_view::npos) {
176 output += msg.substr(last, next - last);
180 output += msg.substr(last);
195static INT_PTR CALLBACK
HelpDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
197 static constexpr int TEXT_CONTROL = 11;
198 static constexpr int OK_BUTTON = 12;
201 case WM_INITDIALOG: {
202 std::wstring &msg = *
reinterpret_cast<std::wstring *
>(lParam);
203 SetDlgItemText(wnd, TEXT_CONTROL, msg.c_str());
204 SendDlgItemMessage(wnd, TEXT_CONTROL, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE);
208 if (wParam == OK_BUTTON) ExitProcess(0);
217void ShowInfoI(std::string_view str)
220 fmt::print(stderr,
"{}\n", str);
227 old = MyShowCursor(
true);
229 if (native_str.size() > 2048) {
233 DialogBoxParam(GetModuleHandle(
nullptr), MAKEINTRESOURCE(101),
nullptr,
HelpDialogFunc,
reinterpret_cast<LPARAM
>(&native_str));
235 MessageBox(GetActiveWindow(), native_str.c_str(), L
"OpenTTD", MB_ICONINFORMATION | MB_OK);
241char *getcwd(
char *buf,
size_t size)
243 wchar_t path[MAX_PATH];
244 GetCurrentDirectory(MAX_PATH - 1, path);
255 wchar_t path[MAX_PATH];
256#ifdef WITH_PERSONAL_DIR
257 if (SUCCEEDED(SHGetFolderPath(
nullptr, CSIDL_PERSONAL,
nullptr, SHGFP_TYPE_CURRENT, path))) {
258 std::string tmp(
FS2OTTD(path));
264 tmp +=
"content_download";
271 if (SUCCEEDED(SHGetFolderPath(
nullptr, CSIDL_COMMON_DOCUMENTS,
nullptr, SHGFP_TYPE_CURRENT, path))) {
272 std::string tmp(
FS2OTTD(path));
288 std::string cwd_s(cwd);
293 wchar_t config_dir[MAX_PATH];
295 if (!GetFullPathName(path,
static_cast<DWORD
>(std::size(config_dir)), config_dir,
nullptr)) {
299 std::string tmp(
FS2OTTD(config_dir));
300 auto pos = tmp.find_last_of(PATHSEPCHAR);
301 if (pos != std::string::npos) tmp.erase(pos + 1);
307 if (!GetModuleFileName(
nullptr, path,
static_cast<DWORD
>(std::size(path)))) {
311 wchar_t exec_dir[MAX_PATH];
313 if (!GetFullPathName(path,
static_cast<DWORD
>(std::size(exec_dir)), exec_dir,
nullptr)) {
317 std::string tmp(
FS2OTTD(exec_dir));
318 auto pos = tmp.find_last_of(PATHSEPCHAR);
319 if (pos != std::string::npos) tmp.erase(pos + 1);
329 if (SUCCEEDED(SHGetFolderPath(
nullptr, CSIDL_APPDATA,
nullptr, SHGFP_TYPE_CURRENT, path))) {
330 std::string config_file_path(
FS2OTTD(path));
332 config_file_path +=
"Atari\\Transport Tycoon Deluxe\\installpath.ini";
334 size_t installpath_len;
335 std::unique_ptr<char[]> installpath =
ReadFileToMem(config_file_path, installpath_len, MAX_PATH);
337 if (installpath !=
nullptr && installpath_len > 0) {
338 std::string ttd_path = installpath.get();
351 if (!IsClipboardFormatAvailable(CF_UNICODETEXT))
return std::nullopt;
353 OpenClipboard(
nullptr);
354 HGLOBAL cbuf = GetClipboardData(CF_UNICODETEXT);
356 std::string result =
FS2OTTD(
static_cast<LPCWSTR
>(GlobalLock(cbuf)));
360 if (result.empty())
return std::nullopt;
375 int name_len = (name.length() >= INT_MAX) ? INT_MAX :
static_cast<int>(name.length());
376 int len = WideCharToMultiByte(CP_UTF8, 0, name.data(), name_len,
nullptr, 0,
nullptr,
nullptr);
377 if (len <= 0)
return std::string();
378 std::string utf8_buf(len,
'\0');
379 WideCharToMultiByte(CP_UTF8, 0, name.data(), name_len, utf8_buf.data(), len,
nullptr,
nullptr);
391 int name_len = (name.length() >= INT_MAX) ? INT_MAX :
static_cast<int>(name.length());
392 int len = MultiByteToWideChar(CP_UTF8, 0, name.data(), name_len,
nullptr, 0);
393 if (len <= 0)
return std::wstring();
394 std::wstring system_buf(len, L
'\0');
395 MultiByteToWideChar(CP_UTF8, 0, name.data(), name_len, system_buf.data(), len);
410 int len = WideCharToMultiByte(CP_UTF8, 0, src.data(),
static_cast<int>(src.size()), dst_buf.data(),
static_cast<int>(dst_buf.size() - 1U),
nullptr,
nullptr);
413 return std::string_view(dst_buf.data(), len);
426 int len = MultiByteToWideChar(CP_UTF8, 0, src.data(),
static_cast<int>(src.size()), dst_buf.data(),
static_cast<int>(dst_buf.size() - 1U));
429 return dst_buf.data();
438 const LANGID userUiLang = GetUserDefaultUILanguage();
439 const LCID userUiLocale = MAKELCID(userUiLang, SORT_DEFAULT);
441 char lang[9], country[9];
442 if (GetLocaleInfoA(userUiLocale, LOCALE_SISO639LANGNAME, lang,
static_cast<int>(std::size(lang))) == 0 ||
443 GetLocaleInfoA(userUiLocale, LOCALE_SISO3166CTRYNAME, country,
static_cast<int>(std::size(country))) == 0) {
448 return fmt::format(
"{}_{}", std::string_view{lang, 2}, std::string_view{country, 2});
452static WCHAR _cur_iso_locale[16] = L
"";
454void Win32SetCurrentLocaleName(std::string iso_code)
457 if (iso_code ==
"zh_TW") {
458 iso_code =
"zh-Hant";
459 }
else if (iso_code ==
"zh_CN") {
460 iso_code =
"zh-Hans";
463 for (
char &c : iso_code) {
464 if (c ==
'_') c =
'-';
468 MultiByteToWideChar(CP_UTF8, 0, iso_code.data(),
static_cast<int>(iso_code.size()), _cur_iso_locale,
static_cast<int>(std::size(_cur_iso_locale)));
474 return _kernel32.GetFunction(symbol_name);
477int OTTDStringCompare(std::string_view s1, std::string_view s2)
479 typedef int (WINAPI *PFNCOMPARESTRINGEX)(LPCWSTR, DWORD, LPCWCH, int, LPCWCH, int, LPVOID, LPVOID, LPARAM);
480 static const PFNCOMPARESTRINGEX _CompareStringEx = GetKernel32Function(
"CompareStringEx");
482#ifndef SORT_DIGITSASNUMBERS
483# define SORT_DIGITSASNUMBERS 0x00000008
485#ifndef LINGUISTIC_IGNORECASE
486# define LINGUISTIC_IGNORECASE 0x00000010
489 int len_s1 = MultiByteToWideChar(CP_UTF8, 0, s1.data(), (
int)s1.size(),
nullptr, 0);
490 int len_s2 = MultiByteToWideChar(CP_UTF8, 0, s2.data(), (
int)s2.size(),
nullptr, 0);
492 std::wstring str_s1(len_s1, L
'\0');
493 std::wstring str_s2(len_s2, L
'\0');
495 if (len_s1 != 0) MultiByteToWideChar(CP_UTF8, 0, s1.data(), (
int)s1.size(), str_s1.data(), len_s1);
496 if (len_s2 != 0) MultiByteToWideChar(CP_UTF8, 0, s2.data(), (
int)s2.size(), str_s2.data(), len_s2);
499 if (_CompareStringEx !=
nullptr) {
500 int result = _CompareStringEx(_cur_iso_locale, LINGUISTIC_IGNORECASE | SORT_DIGITSASNUMBERS, str_s1.data(), len_s1, str_s2.data(), len_s2,
nullptr,
nullptr, 0);
501 if (result != 0)
return result;
504 return CompareString(MAKELCID(
_current_language->winlangid, SORT_DEFAULT), NORM_IGNORECASE, str_s1.data(), len_s1, str_s2.data(), len_s2);
517 typedef int (WINAPI *PFNFINDNLSSTRINGEX)(LPCWSTR, DWORD, LPCWSTR, int, LPCWSTR, int, LPINT, LPNLSVERSIONINFO, LPVOID, LPARAM);
518 static const PFNFINDNLSSTRINGEX _FindNLSStringEx = GetKernel32Function(
"FindNLSStringEx");
520 if (_FindNLSStringEx !=
nullptr) {
521 int len_str = MultiByteToWideChar(CP_UTF8, 0, str.data(), (
int)str.size(),
nullptr, 0);
522 int len_value = MultiByteToWideChar(CP_UTF8, 0, value.data(), (
int)value.size(),
nullptr, 0);
524 if (len_str != 0 && len_value != 0) {
525 std::wstring str_str(len_str, L
'\0');
526 std::wstring str_value(len_value, L
'\0');
528 MultiByteToWideChar(CP_UTF8, 0, str.data(), (
int)str.size(), str_str.data(), len_str);
529 MultiByteToWideChar(CP_UTF8, 0, value.data(), (
int)value.size(), str_value.data(), len_value);
531 return _FindNLSStringEx(_cur_iso_locale, FIND_FROMSTART | (case_insensitive ? LINGUISTIC_IGNORECASE : 0), str_str.data(), len_str, str_value.data(), len_value,
nullptr,
nullptr,
nullptr, 0) >= 0 ? 1 : 0;
540 using SetThreadDescriptionProc = HRESULT(WINAPI *)(HANDLE, PCWSTR);
541 static const SetThreadDescriptionProc std_proc = GetKernel32Function(
"SetThreadDescription");
542 if (std_proc !=
nullptr) std_proc(GetCurrentThread(),
OTTD2FS(name).c_str());
List of file information.
A function loaded from a library.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
@ Misc
Misc message facility.
@ Critical
Critical, user should know about this.
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
void DetermineBasePaths(std::string_view exe)
Determine the base (personal dir and game data dir) paths.
void AppendPathSeparator(std::string &buf)
Appends, if necessary, the path separator character to the end of the string.
bool FileExists(std::string_view filename)
Test whether the given filename exists.
std::string _config_file
Configuration file of OpenTTD.
EnumIndexArray< std::string, Searchpath, Searchpath::End > _searchpaths
The search paths OpenTTD could search through.
std::unique_ptr< char[]> ReadFileToMem(const std::string &filename, size_t &lenp, size_t maxsize)
Load a file into memory.
Functions for standard in/out file operations.
@ WorkingDir
Search in the working directory.
@ ApplicationBundleDir
Search within the application bundle.
@ InstallationDir
Search in the installation directory.
@ AutodownloadPersonalDir
Search within the autodownload directory located in the personal directory.
@ SharedDir
Search in the shared directory, like 'Shared Files' under Windows.
@ TransportTycoonDeluxeDir
Search within the Transport Tycoon Deluxe data directory (if installed).
@ BinaryDir
Search in the directory where the binary resides.
@ PersonalDir
Search in the personal directory.
Declarations for savegames operations.
ControlInputs _input_pressed
Control inputs that are currently pressed.
ControlInputs _input_clicked
Control inputs that have been actioned.
Functions related to the gfx engine.
@ Left
Left mouse button is pressed.
Information about languages and their files.
const LanguageMetadata * _current_language
The currently loaded language.
Functions/types related to loading libraries dynamically.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
#define lengthof(array)
Return the length of an fixed size array.
Functions related to low-level strings.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Functions related to OTTD's strings.
Deals with finding savegames.
Stuff related to the text buffer GUI.
void SetCurrentThreadName(const std::string &name)
Name the thread this function is called on for the debugger.
std::optional< std::string > GetClipboardContents()
Try to retrieve the current clipboard contents.
std::string_view convert_from_fs(const std::wstring_view src, std::span< char > dst_buf)
Convert to OpenTTD's encoding from that of the environment in UNICODE.
std::wstring OTTD2FS(std::string_view name)
Convert from OpenTTD's encoding to a wide string.
int Win32StringContains(std::string_view str, std::string_view value, bool case_insensitive)
Search if a string is contained in another string using the current locale.
static std::string ConvertLfToCrLf(std::string_view msg)
Replace linefeeds with carriage-return and linefeed.
static INT_PTR HelpDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
Callback function to handle the window.
std::string FS2OTTD(std::wstring_view name)
Convert to OpenTTD's encoding from a wide string.
void ShowOSErrorBox(std::string_view buf, bool)
Show an error message.
wchar_t * convert_to_fs(std::string_view src, std::span< wchar_t > dst_buf)
Convert from OpenTTD's encoding to that of the environment in UNICODE.
void OSOpenBrowser(const std::string &url)
Opens browser on MacOS.
std::optional< std::string > GetCurrentLocale(const char *)
Determine the current user's locale.
Declarations of functions for MS windows systems.