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);
226 old = MyShowCursor(
true);
228 if (native_str.size() > 2048) {
232 DialogBoxParam(GetModuleHandle(
nullptr), MAKEINTRESOURCE(101),
nullptr,
HelpDialogFunc,
reinterpret_cast<LPARAM
>(&native_str));
234 MessageBox(GetActiveWindow(), native_str.c_str(), L
"OpenTTD", MB_ICONINFORMATION | MB_OK);
240char *getcwd(
char *buf,
size_t size)
242 wchar_t path[MAX_PATH];
243 GetCurrentDirectory(MAX_PATH - 1, path);
254 wchar_t path[MAX_PATH];
255#ifdef WITH_PERSONAL_DIR
256 if (SUCCEEDED(SHGetFolderPath(
nullptr, CSIDL_PERSONAL,
nullptr, SHGFP_TYPE_CURRENT, path))) {
257 std::string tmp(
FS2OTTD(path));
263 tmp +=
"content_download";
270 if (SUCCEEDED(SHGetFolderPath(
nullptr, CSIDL_COMMON_DOCUMENTS,
nullptr, SHGFP_TYPE_CURRENT, path))) {
271 std::string tmp(
FS2OTTD(path));
287 std::string cwd_s(cwd);
292 wchar_t config_dir[MAX_PATH];
294 if (!GetFullPathName(path,
static_cast<DWORD
>(std::size(config_dir)), config_dir,
nullptr)) {
295 Debug(misc, 0,
"GetFullPathName failed ({})", GetLastError());
298 std::string tmp(
FS2OTTD(config_dir));
299 auto pos = tmp.find_last_of(PATHSEPCHAR);
300 if (pos != std::string::npos) tmp.erase(pos + 1);
306 if (!GetModuleFileName(
nullptr, path,
static_cast<DWORD
>(std::size(path)))) {
307 Debug(misc, 0,
"GetModuleFileName failed ({})", GetLastError());
310 wchar_t exec_dir[MAX_PATH];
312 if (!GetFullPathName(path,
static_cast<DWORD
>(std::size(exec_dir)), exec_dir,
nullptr)) {
313 Debug(misc, 0,
"GetFullPathName failed ({})", GetLastError());
316 std::string tmp(
FS2OTTD(exec_dir));
317 auto pos = tmp.find_last_of(PATHSEPCHAR);
318 if (pos != std::string::npos) tmp.erase(pos + 1);
328 if (SUCCEEDED(SHGetFolderPath(
nullptr, CSIDL_APPDATA,
nullptr, SHGFP_TYPE_CURRENT, path))) {
329 std::string config_file_path(
FS2OTTD(path));
331 config_file_path +=
"Atari\\Transport Tycoon Deluxe\\installpath.ini";
333 size_t installpath_len;
334 std::unique_ptr<char[]> installpath =
ReadFileToMem(config_file_path, installpath_len, MAX_PATH);
336 if (installpath !=
nullptr && installpath_len > 0) {
337 std::string ttd_path = installpath.get();
350 if (!IsClipboardFormatAvailable(CF_UNICODETEXT))
return std::nullopt;
352 OpenClipboard(
nullptr);
353 HGLOBAL cbuf = GetClipboardData(CF_UNICODETEXT);
355 std::string result =
FS2OTTD(
static_cast<LPCWSTR
>(GlobalLock(cbuf)));
359 if (result.empty())
return std::nullopt;
374 int name_len = (name.length() >= INT_MAX) ? INT_MAX :
static_cast<int>(name.length());
375 int len = WideCharToMultiByte(CP_UTF8, 0, name.data(), name_len,
nullptr, 0,
nullptr,
nullptr);
376 if (len <= 0)
return std::string();
377 std::string utf8_buf(len,
'\0');
378 WideCharToMultiByte(CP_UTF8, 0, name.data(), name_len, utf8_buf.data(), len,
nullptr,
nullptr);
390 int name_len = (name.length() >= INT_MAX) ? INT_MAX :
static_cast<int>(name.length());
391 int len = MultiByteToWideChar(CP_UTF8, 0, name.data(), name_len,
nullptr, 0);
392 if (len <= 0)
return std::wstring();
393 std::wstring system_buf(len, L
'\0');
394 MultiByteToWideChar(CP_UTF8, 0, name.data(), name_len, system_buf.data(), len);
409 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);
412 return std::string_view(dst_buf.data(), len);
425 int len = MultiByteToWideChar(CP_UTF8, 0, src.data(),
static_cast<int>(src.size()), dst_buf.data(),
static_cast<int>(dst_buf.size() - 1U));
428 return dst_buf.data();
437 const LANGID userUiLang = GetUserDefaultUILanguage();
438 const LCID userUiLocale = MAKELCID(userUiLang, SORT_DEFAULT);
440 char lang[9], country[9];
441 if (GetLocaleInfoA(userUiLocale, LOCALE_SISO639LANGNAME, lang,
static_cast<int>(std::size(lang))) == 0 ||
442 GetLocaleInfoA(userUiLocale, LOCALE_SISO3166CTRYNAME, country,
static_cast<int>(std::size(country))) == 0) {
447 return fmt::format(
"{}_{}", std::string_view{lang, 2}, std::string_view{country, 2});
451static WCHAR _cur_iso_locale[16] = L
"";
453void Win32SetCurrentLocaleName(std::string iso_code)
456 if (iso_code ==
"zh_TW") {
457 iso_code =
"zh-Hant";
458 }
else if (iso_code ==
"zh_CN") {
459 iso_code =
"zh-Hans";
462 for (
char &c : iso_code) {
463 if (c ==
'_') c =
'-';
467 MultiByteToWideChar(CP_UTF8, 0, iso_code.data(),
static_cast<int>(iso_code.size()), _cur_iso_locale,
static_cast<int>(std::size(_cur_iso_locale)));
473 return _kernel32.GetFunction(symbol_name);
476int OTTDStringCompare(std::string_view s1, std::string_view s2)
478 typedef int (WINAPI *PFNCOMPARESTRINGEX)(LPCWSTR, DWORD, LPCWCH, int, LPCWCH, int, LPVOID, LPVOID, LPARAM);
479 static const PFNCOMPARESTRINGEX _CompareStringEx = GetKernel32Function(
"CompareStringEx");
481#ifndef SORT_DIGITSASNUMBERS
482# define SORT_DIGITSASNUMBERS 0x00000008
484#ifndef LINGUISTIC_IGNORECASE
485# define LINGUISTIC_IGNORECASE 0x00000010
488 int len_s1 = MultiByteToWideChar(CP_UTF8, 0, s1.data(), (
int)s1.size(),
nullptr, 0);
489 int len_s2 = MultiByteToWideChar(CP_UTF8, 0, s2.data(), (
int)s2.size(),
nullptr, 0);
491 std::wstring str_s1(len_s1, L
'\0');
492 std::wstring str_s2(len_s2, L
'\0');
494 if (len_s1 != 0) MultiByteToWideChar(CP_UTF8, 0, s1.data(), (
int)s1.size(), str_s1.data(), len_s1);
495 if (len_s2 != 0) MultiByteToWideChar(CP_UTF8, 0, s2.data(), (
int)s2.size(), str_s2.data(), len_s2);
498 if (_CompareStringEx !=
nullptr) {
499 int result = _CompareStringEx(_cur_iso_locale, LINGUISTIC_IGNORECASE | SORT_DIGITSASNUMBERS, str_s1.data(), len_s1, str_s2.data(), len_s2,
nullptr,
nullptr, 0);
500 if (result != 0)
return result;
503 return CompareString(MAKELCID(
_current_language->winlangid, SORT_DEFAULT), NORM_IGNORECASE, str_s1.data(), len_s1, str_s2.data(), len_s2);
516 typedef int (WINAPI *PFNFINDNLSSTRINGEX)(LPCWSTR, DWORD, LPCWSTR, int, LPCWSTR, int, LPINT, LPNLSVERSIONINFO, LPVOID, LPARAM);
517 static const PFNFINDNLSSTRINGEX _FindNLSStringEx = GetKernel32Function(
"FindNLSStringEx");
519 if (_FindNLSStringEx !=
nullptr) {
520 int len_str = MultiByteToWideChar(CP_UTF8, 0, str.data(), (
int)str.size(),
nullptr, 0);
521 int len_value = MultiByteToWideChar(CP_UTF8, 0, value.data(), (
int)value.size(),
nullptr, 0);
523 if (len_str != 0 && len_value != 0) {
524 std::wstring str_str(len_str, L
'\0');
525 std::wstring str_value(len_value, L
'\0');
527 MultiByteToWideChar(CP_UTF8, 0, str.data(), (
int)str.size(), str_str.data(), len_str);
528 MultiByteToWideChar(CP_UTF8, 0, value.data(), (
int)value.size(), str_value.data(), len_value);
530 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;
539 using SetThreadDescriptionProc = HRESULT(WINAPI *)(HANDLE, PCWSTR);
540 static const SetThreadDescriptionProc std_proc = GetKernel32Function(
"SetThreadDescription");
541 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(category, level, format_string,...)
Output a line of debugging information.
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.
bool _left_button_down
Is left mouse button pressed?
bool _left_button_clicked
Is left mouse button clicked?
Functions related to the gfx engine.
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.