OpenTTD Source 20261112-master-gbcbec5e63f
win32.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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "../../stdafx.h"
11#include "../../debug.h"
12#include "../../gfx_func.h"
13#include "../../strings_func.h"
14#include "../../textbuf_gui.h"
15#include "../../fileio_func.h"
16#include <windows.h>
17#include <fcntl.h>
18#include <mmsystem.h>
19#include <processthreadsapi.h>
20#include <regstr.h>
21#define NO_SHOBJIDL_SORTDIRECTION
22#include <shlobj.h> /* SHGetFolderPath */
23#include <shellapi.h>
24#include <winnls.h>
25#include <io.h>
26#include "win32.h"
27#include "../../fios.h"
28#include "../../string_func.h"
29#include <sys/stat.h>
30#include "../../language.h"
31#include "../../thread.h"
33
34#include "table/strings.h"
35
36#include "../../safeguards.h"
37
38static bool _has_console;
39static bool _cursor_disable = true;
40static bool _cursor_visible = true;
41
42bool MyShowCursor(bool show, bool toggle)
43{
44 if (toggle) _cursor_disable = !_cursor_disable;
45 if (_cursor_disable) return show;
46 if (_cursor_visible == show) return show;
47
48 _cursor_visible = show;
49 ShowCursor(show);
50
51 return !show;
52}
53
54void ShowOSErrorBox(std::string_view buf, bool)
55{
56 MyShowCursor(true);
57 MessageBox(GetActiveWindow(), OTTD2FS(buf).c_str(), L"Error!", MB_ICONSTOP | MB_TASKMODAL);
58}
59
60void OSOpenBrowser(const std::string &url)
61{
62 ShellExecute(GetActiveWindow(), L"open", OTTD2FS(url).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
63}
64
65bool FiosIsRoot(const std::string &file)
66{
67 return file.size() == 3; // C:\...
68}
69
70void FiosGetDrives(FileList &file_list)
71{
72 wchar_t drives[256];
73 const wchar_t *s;
74
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;
79 fios->mtime = 0;
80 fios->name += (char)(s[0] & 0xFF);
81 fios->name += ':';
82 fios->title = GetEncodedString(STR_JUST_RAW_STRING, fios->name);
83 while (*s++ != '\0') { /* Nothing */ }
84 }
85}
86
87bool FiosIsHiddenFile(const std::filesystem::path &path)
88{
89 UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // Disable 'no-disk' message box.
90
91 DWORD attributes = GetFileAttributes(path.c_str());
92
93 SetErrorMode(sem); // Restore previous setting.
94
95 return (attributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) != 0;
96}
97
98std::optional<uint64_t> FiosGetDiskFreeSpace(const std::string &path)
99{
100 UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // disable 'no-disk' message box
101
102 ULARGE_INTEGER bytes_free;
103 bool retval = GetDiskFreeSpaceEx(OTTD2FS(path).c_str(), &bytes_free, nullptr, nullptr);
104
105 SetErrorMode(sem); // reset previous setting
106
107 if (retval) return bytes_free.QuadPart;
108 return std::nullopt;
109}
110
111void CreateConsole()
112{
113 HANDLE hand;
114 CONSOLE_SCREEN_BUFFER_INFO coninfo;
115
116 if (_has_console) return;
117 _has_console = true;
118
119 if (!AllocConsole()) return;
120
121 hand = GetStdHandle(STD_OUTPUT_HANDLE);
122 GetConsoleScreenBufferInfo(hand, &coninfo);
123 coninfo.dwSize.Y = 500;
124 SetConsoleScreenBufferSize(hand, coninfo.dwSize);
125
126 /* redirect unbuffered STDIN, STDOUT, STDERR to the console */
127#if !defined(__CYGWIN__)
128
129 /* Check if we can open a handle to STDOUT. */
130 int fd = _open_osfhandle((intptr_t)hand, _O_TEXT);
131 if (fd == -1) {
132 /* Free everything related to the console. */
133 FreeConsole();
134 _has_console = false;
135 _close(fd);
136 CloseHandle(hand);
137
138 ShowInfo("Unable to open an output handle to the console. Check known-bugs.md for details.");
139 return;
140 }
141
142#if defined(_MSC_VER)
143 freopen("CONOUT$", "a", stdout);
144 freopen("CONIN$", "r", stdin);
145 freopen("CONOUT$", "a", stderr);
146#else
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" );
150#endif
151
152#else
153 /* open_osfhandle is not in cygwin */
154 *stdout = *fdopen(1, "w" );
155 *stdin = *fdopen(0, "r" );
156 *stderr = *fdopen(2, "w" );
157#endif
158
159 setvbuf(stdin, nullptr, _IONBF, 0);
160 setvbuf(stdout, nullptr, _IONBF, 0);
161 setvbuf(stderr, nullptr, _IONBF, 0);
162}
163
169static std::string ConvertLfToCrLf(std::string_view msg)
170{
171 std::string output;
172
173 size_t last = 0;
174 size_t next = 0;
175 while ((next = msg.find('\n', last)) != std::string_view::npos) {
176 output += msg.substr(last, next - last);
177 output += "\r\n";
178 last = next + 1;
179 }
180 output += msg.substr(last);
181
182 return output;
183}
184
195static INT_PTR CALLBACK HelpDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
196{
197 static constexpr int TEXT_CONTROL = 11;
198 static constexpr int OK_BUTTON = 12;
199
200 switch (msg) {
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);
205 } return TRUE;
206
207 case WM_COMMAND:
208 if (wParam == OK_BUTTON) ExitProcess(0);
209 return TRUE;
210 case WM_CLOSE:
211 ExitProcess(0);
212 }
213
214 return FALSE;
215}
216
217void ShowInfoI(std::string_view str)
218{
219 if (_has_console) {
220 fmt::print(stderr, "{}\n", str);
221 } else {
222 bool old;
223 ReleaseCapture();
226
227 old = MyShowCursor(true);
228 std::wstring native_str = OTTD2FS(ConvertLfToCrLf(str));
229 if (native_str.size() > 2048) {
230 /* The minimum length of the help message is 2048. Other messages sent via
231 * ShowInfo are much shorter, or so long they need this way of displaying
232 * them anyway. */
233 DialogBoxParam(GetModuleHandle(nullptr), MAKEINTRESOURCE(101), nullptr, HelpDialogFunc, reinterpret_cast<LPARAM>(&native_str));
234 } else {
235 MessageBox(GetActiveWindow(), native_str.c_str(), L"OpenTTD", MB_ICONINFORMATION | MB_OK);
236 }
237 MyShowCursor(old);
238 }
239}
240
241char *getcwd(char *buf, size_t size)
242{
243 wchar_t path[MAX_PATH];
244 GetCurrentDirectory(MAX_PATH - 1, path);
245 convert_from_fs(path, {buf, size});
246 return buf;
247}
248
249extern std::string _config_file;
250
251void DetermineBasePaths(std::string_view exe)
252{
254
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));
260 tmp += PERSONAL_DIR;
263
264 tmp += "content_download";
267 } else {
269 }
270
271 if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_COMMON_DOCUMENTS, nullptr, SHGFP_TYPE_CURRENT, path))) {
272 std::string tmp(FS2OTTD(path));
274 tmp += PERSONAL_DIR;
277 } else {
279 }
280#else
283#endif
284
285 if (_config_file.empty()) {
286 char cwd[MAX_PATH];
287 getcwd(cwd, lengthof(cwd));
288 std::string cwd_s(cwd);
289 AppendPathSeparator(cwd_s);
291 } else {
292 /* Use the folder of the config file as working directory. */
293 wchar_t config_dir[MAX_PATH];
295 if (!GetFullPathName(path, static_cast<DWORD>(std::size(config_dir)), config_dir, nullptr)) {
296 Debug(Facility::Misc, Severity::Critical, "GetFullPathName failed ({})", GetLastError());
298 } else {
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);
302
304 }
305 }
306
307 if (!GetModuleFileName(nullptr, path, static_cast<DWORD>(std::size(path)))) {
308 Debug(Facility::Misc, Severity::Critical, "GetModuleFileName failed ({})", GetLastError());
310 } else {
311 wchar_t exec_dir[MAX_PATH];
312 convert_to_fs(exe, path);
313 if (!GetFullPathName(path, static_cast<DWORD>(std::size(exec_dir)), exec_dir, nullptr)) {
314 Debug(Facility::Misc, Severity::Critical, "GetFullPathName failed ({})", GetLastError());
316 } else {
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);
320
322 }
323 }
324
328
329 if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, path))) {
330 std::string config_file_path(FS2OTTD(path));
331 AppendPathSeparator(config_file_path);
332 config_file_path += "Atari\\Transport Tycoon Deluxe\\installpath.ini";
333
334 size_t installpath_len;
335 std::unique_ptr<char[]> installpath = ReadFileToMem(config_file_path, installpath_len, MAX_PATH);
336
337 if (installpath != nullptr && installpath_len > 0) {
338 std::string ttd_path = installpath.get();
339 AppendPathSeparator(ttd_path);
340 ttd_path += "CD";
341 AppendPathSeparator(ttd_path);
342
344 }
345 }
346}
347
348
349std::optional<std::string> GetClipboardContents()
350{
351 if (!IsClipboardFormatAvailable(CF_UNICODETEXT)) return std::nullopt;
352
353 OpenClipboard(nullptr);
354 HGLOBAL cbuf = GetClipboardData(CF_UNICODETEXT);
355
356 std::string result = FS2OTTD(static_cast<LPCWSTR>(GlobalLock(cbuf)));
357 GlobalUnlock(cbuf);
358 CloseClipboard();
359
360 if (result.empty()) return std::nullopt;
361 return result;
362}
363
364
373std::string FS2OTTD(std::wstring_view name)
374{
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'); // len includes terminating null
379 WideCharToMultiByte(CP_UTF8, 0, name.data(), name_len, utf8_buf.data(), len, nullptr, nullptr);
380 return utf8_buf;
381}
382
389std::wstring OTTD2FS(std::string_view name)
390{
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'); // len includes terminating null
395 MultiByteToWideChar(CP_UTF8, 0, name.data(), name_len, system_buf.data(), len);
396 return system_buf;
397}
398
399
407std::string_view convert_from_fs(const std::wstring_view src, std::span<char> dst_buf)
408{
409 /* Convert UTF-16 string to UTF-8. */
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);
411 dst_buf[len] = '\0';
412
413 return std::string_view(dst_buf.data(), len);
414}
415
416
424wchar_t *convert_to_fs(std::string_view src, std::span<wchar_t> dst_buf)
425{
426 int len = MultiByteToWideChar(CP_UTF8, 0, src.data(), static_cast<int>(src.size()), dst_buf.data(), static_cast<int>(dst_buf.size() - 1U));
427 dst_buf[len] = '\0';
428
429 return dst_buf.data();
430}
431
436std::optional<std::string> GetCurrentLocale(const char *)
437{
438 const LANGID userUiLang = GetUserDefaultUILanguage();
439 const LCID userUiLocale = MAKELCID(userUiLang, SORT_DEFAULT);
440
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) {
444 /* Unable to retrieve the locale. */
445 return std::nullopt;
446 }
447 /* Format it as 'en_us'. */
448 return fmt::format("{}_{}", std::string_view{lang, 2}, std::string_view{country, 2});
449}
450
451
452static WCHAR _cur_iso_locale[16] = L"";
453
454void Win32SetCurrentLocaleName(std::string iso_code)
455{
456 /* Convert the iso code into the format that windows expects. */
457 if (iso_code == "zh_TW") {
458 iso_code = "zh-Hant";
459 } else if (iso_code == "zh_CN") {
460 iso_code = "zh-Hans";
461 } else {
462 /* Windows expects a '-' between language and country code, but we use a '_'. */
463 for (char &c : iso_code) {
464 if (c == '_') c = '-';
465 }
466 }
467
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)));
469}
470
471static LibraryLoader::Function GetKernel32Function(const std::string &symbol_name)
472{
473 static LibraryLoader _kernel32("Kernel32.dll");
474 return _kernel32.GetFunction(symbol_name);
475}
476
477int OTTDStringCompare(std::string_view s1, std::string_view s2)
478{
479 typedef int (WINAPI *PFNCOMPARESTRINGEX)(LPCWSTR, DWORD, LPCWCH, int, LPCWCH, int, LPVOID, LPVOID, LPARAM);
480 static const PFNCOMPARESTRINGEX _CompareStringEx = GetKernel32Function("CompareStringEx");
481
482#ifndef SORT_DIGITSASNUMBERS
483# define SORT_DIGITSASNUMBERS 0x00000008
484#endif
485#ifndef LINGUISTIC_IGNORECASE
486# define LINGUISTIC_IGNORECASE 0x00000010
487#endif
488
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);
491
492 std::wstring str_s1(len_s1, L'\0');
493 std::wstring str_s2(len_s2, L'\0');
494
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);
497
498 /* CompareStringEx takes UTF-16 strings, even in ANSI-builds. */
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;
502 }
503
504 return CompareString(MAKELCID(_current_language->winlangid, SORT_DEFAULT), NORM_IGNORECASE, str_s1.data(), len_s1, str_s2.data(), len_s2);
505}
506
515int Win32StringContains(std::string_view str, std::string_view value, bool case_insensitive)
516{
517 typedef int (WINAPI *PFNFINDNLSSTRINGEX)(LPCWSTR, DWORD, LPCWSTR, int, LPCWSTR, int, LPINT, LPNLSVERSIONINFO, LPVOID, LPARAM);
518 static const PFNFINDNLSSTRINGEX _FindNLSStringEx = GetKernel32Function("FindNLSStringEx");
519
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);
523
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');
527
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);
530
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;
532 }
533 }
534
535 return -1; // Failure indication.
536}
537
538void SetCurrentThreadName(const std::string &name)
539{
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());
543}
List of file information.
Definition fios.h:93
A function loaded from a library.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Misc
Misc message facility.
Definition debug_type.h:32
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
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.
Definition fileio.cpp:761
void AppendPathSeparator(std::string &buf)
Appends, if necessary, the path separator character to the end of the string.
Definition fileio.cpp:353
bool FileExists(std::string_view filename)
Test whether the given filename exists.
Definition fileio.cpp:133
std::string _config_file
Configuration file of OpenTTD.
Definition settings.cpp:64
EnumIndexArray< std::string, Searchpath, Searchpath::End > _searchpaths
The search paths OpenTTD could search through.
Definition fileio.cpp:64
std::unique_ptr< char[]> ReadFileToMem(const std::string &filename, size_t &lenp, size_t maxsize)
Load a file into memory.
Definition fileio.cpp:1078
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.
Definition gfx.cpp:34
ControlInputs _input_clicked
Control inputs that have been actioned.
Definition gfx.cpp:35
Functions related to the gfx engine.
@ Left
Left mouse button is pressed.
Definition gfx_type.h:444
Information about languages and their files.
const LanguageMetadata * _current_language
The currently loaded language.
Definition strings.cpp:53
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.
Definition stdafx.h:261
Functions related to low-level strings.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
Functions related to OTTD's strings.
Deals with finding savegames.
Definition fios.h:85
Stuff related to the text buffer GUI.
Base of all threads.
void SetCurrentThreadName(const std::string &name)
Name the thread this function is called on for the debugger.
Definition win32.cpp:538
std::optional< std::string > GetClipboardContents()
Try to retrieve the current clipboard contents.
Definition win32.cpp:349
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.
Definition win32.cpp:407
std::wstring OTTD2FS(std::string_view name)
Convert from OpenTTD's encoding to a wide string.
Definition win32.cpp:389
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.
Definition win32.cpp:515
static std::string ConvertLfToCrLf(std::string_view msg)
Replace linefeeds with carriage-return and linefeed.
Definition win32.cpp:169
static INT_PTR HelpDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
Callback function to handle the window.
Definition win32.cpp:195
std::string FS2OTTD(std::wstring_view name)
Convert to OpenTTD's encoding from a wide string.
Definition win32.cpp:373
void ShowOSErrorBox(std::string_view buf, bool)
Show an error message.
Definition win32.cpp:54
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.
Definition win32.cpp:424
void OSOpenBrowser(const std::string &url)
Opens browser on MacOS.
Definition win32.cpp:60
std::optional< std::string > GetCurrentLocale(const char *)
Determine the current user's locale.
Definition win32.cpp:436
Declarations of functions for MS windows systems.