OpenTTD Source 20260721-master-g25ec12c62d
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();
225
226 old = MyShowCursor(true);
227 std::wstring native_str = OTTD2FS(ConvertLfToCrLf(str));
228 if (native_str.size() > 2048) {
229 /* The minimum length of the help message is 2048. Other messages sent via
230 * ShowInfo are much shorter, or so long they need this way of displaying
231 * them anyway. */
232 DialogBoxParam(GetModuleHandle(nullptr), MAKEINTRESOURCE(101), nullptr, HelpDialogFunc, reinterpret_cast<LPARAM>(&native_str));
233 } else {
234 MessageBox(GetActiveWindow(), native_str.c_str(), L"OpenTTD", MB_ICONINFORMATION | MB_OK);
235 }
236 MyShowCursor(old);
237 }
238}
239
240char *getcwd(char *buf, size_t size)
241{
242 wchar_t path[MAX_PATH];
243 GetCurrentDirectory(MAX_PATH - 1, path);
244 convert_from_fs(path, {buf, size});
245 return buf;
246}
247
248extern std::string _config_file;
249
250void DetermineBasePaths(std::string_view exe)
251{
253
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));
259 tmp += PERSONAL_DIR;
262
263 tmp += "content_download";
266 } else {
268 }
269
270 if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_COMMON_DOCUMENTS, nullptr, SHGFP_TYPE_CURRENT, path))) {
271 std::string tmp(FS2OTTD(path));
273 tmp += PERSONAL_DIR;
276 } else {
278 }
279#else
282#endif
283
284 if (_config_file.empty()) {
285 char cwd[MAX_PATH];
286 getcwd(cwd, lengthof(cwd));
287 std::string cwd_s(cwd);
288 AppendPathSeparator(cwd_s);
290 } else {
291 /* Use the folder of the config file as working directory. */
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());
297 } else {
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);
301
303 }
304 }
305
306 if (!GetModuleFileName(nullptr, path, static_cast<DWORD>(std::size(path)))) {
307 Debug(misc, 0, "GetModuleFileName failed ({})", GetLastError());
309 } else {
310 wchar_t exec_dir[MAX_PATH];
311 convert_to_fs(exe, path);
312 if (!GetFullPathName(path, static_cast<DWORD>(std::size(exec_dir)), exec_dir, nullptr)) {
313 Debug(misc, 0, "GetFullPathName failed ({})", GetLastError());
315 } else {
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);
319
321 }
322 }
323
327
328 if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, path))) {
329 std::string config_file_path(FS2OTTD(path));
330 AppendPathSeparator(config_file_path);
331 config_file_path += "Atari\\Transport Tycoon Deluxe\\installpath.ini";
332
333 size_t installpath_len;
334 std::unique_ptr<char[]> installpath = ReadFileToMem(config_file_path, installpath_len, MAX_PATH);
335
336 if (installpath != nullptr && installpath_len > 0) {
337 std::string ttd_path = installpath.get();
338 AppendPathSeparator(ttd_path);
339 ttd_path += "CD";
340 AppendPathSeparator(ttd_path);
341
343 }
344 }
345}
346
347
348std::optional<std::string> GetClipboardContents()
349{
350 if (!IsClipboardFormatAvailable(CF_UNICODETEXT)) return std::nullopt;
351
352 OpenClipboard(nullptr);
353 HGLOBAL cbuf = GetClipboardData(CF_UNICODETEXT);
354
355 std::string result = FS2OTTD(static_cast<LPCWSTR>(GlobalLock(cbuf)));
356 GlobalUnlock(cbuf);
357 CloseClipboard();
358
359 if (result.empty()) return std::nullopt;
360 return result;
361}
362
363
372std::string FS2OTTD(std::wstring_view name)
373{
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'); // len includes terminating null
378 WideCharToMultiByte(CP_UTF8, 0, name.data(), name_len, utf8_buf.data(), len, nullptr, nullptr);
379 return utf8_buf;
380}
381
388std::wstring OTTD2FS(std::string_view name)
389{
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'); // len includes terminating null
394 MultiByteToWideChar(CP_UTF8, 0, name.data(), name_len, system_buf.data(), len);
395 return system_buf;
396}
397
398
406std::string_view convert_from_fs(const std::wstring_view src, std::span<char> dst_buf)
407{
408 /* Convert UTF-16 string to UTF-8. */
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);
410 dst_buf[len] = '\0';
411
412 return std::string_view(dst_buf.data(), len);
413}
414
415
423wchar_t *convert_to_fs(std::string_view src, std::span<wchar_t> dst_buf)
424{
425 int len = MultiByteToWideChar(CP_UTF8, 0, src.data(), static_cast<int>(src.size()), dst_buf.data(), static_cast<int>(dst_buf.size() - 1U));
426 dst_buf[len] = '\0';
427
428 return dst_buf.data();
429}
430
435std::optional<std::string> GetCurrentLocale(const char *)
436{
437 const LANGID userUiLang = GetUserDefaultUILanguage();
438 const LCID userUiLocale = MAKELCID(userUiLang, SORT_DEFAULT);
439
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) {
443 /* Unable to retrieve the locale. */
444 return std::nullopt;
445 }
446 /* Format it as 'en_us'. */
447 return fmt::format("{}_{}", std::string_view{lang, 2}, std::string_view{country, 2});
448}
449
450
451static WCHAR _cur_iso_locale[16] = L"";
452
453void Win32SetCurrentLocaleName(std::string iso_code)
454{
455 /* Convert the iso code into the format that windows expects. */
456 if (iso_code == "zh_TW") {
457 iso_code = "zh-Hant";
458 } else if (iso_code == "zh_CN") {
459 iso_code = "zh-Hans";
460 } else {
461 /* Windows expects a '-' between language and country code, but we use a '_'. */
462 for (char &c : iso_code) {
463 if (c == '_') c = '-';
464 }
465 }
466
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)));
468}
469
470static LibraryLoader::Function GetKernel32Function(const std::string &symbol_name)
471{
472 static LibraryLoader _kernel32("Kernel32.dll");
473 return _kernel32.GetFunction(symbol_name);
474}
475
476int OTTDStringCompare(std::string_view s1, std::string_view s2)
477{
478 typedef int (WINAPI *PFNCOMPARESTRINGEX)(LPCWSTR, DWORD, LPCWCH, int, LPCWCH, int, LPVOID, LPVOID, LPARAM);
479 static const PFNCOMPARESTRINGEX _CompareStringEx = GetKernel32Function("CompareStringEx");
480
481#ifndef SORT_DIGITSASNUMBERS
482# define SORT_DIGITSASNUMBERS 0x00000008
483#endif
484#ifndef LINGUISTIC_IGNORECASE
485# define LINGUISTIC_IGNORECASE 0x00000010
486#endif
487
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);
490
491 std::wstring str_s1(len_s1, L'\0');
492 std::wstring str_s2(len_s2, L'\0');
493
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);
496
497 /* CompareStringEx takes UTF-16 strings, even in ANSI-builds. */
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;
501 }
502
503 return CompareString(MAKELCID(_current_language->winlangid, SORT_DEFAULT), NORM_IGNORECASE, str_s1.data(), len_s1, str_s2.data(), len_s2);
504}
505
514int Win32StringContains(std::string_view str, std::string_view value, bool case_insensitive)
515{
516 typedef int (WINAPI *PFNFINDNLSSTRINGEX)(LPCWSTR, DWORD, LPCWSTR, int, LPCWSTR, int, LPINT, LPNLSVERSIONINFO, LPVOID, LPARAM);
517 static const PFNFINDNLSSTRINGEX _FindNLSStringEx = GetKernel32Function("FindNLSStringEx");
518
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);
522
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');
526
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);
529
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;
531 }
532 }
533
534 return -1; // Failure indication.
535}
536
537void SetCurrentThreadName(const std::string &name)
538{
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());
542}
List of file information.
Definition fios.h:86
A function loaded from a library.
Functions related to debugging.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
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:762
void AppendPathSeparator(std::string &buf)
Appends, if necessary, the path separator character to the end of the string.
Definition fileio.cpp:354
bool FileExists(std::string_view filename)
Test whether the given filename exists.
Definition fileio.cpp:134
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:65
std::unique_ptr< char[]> ReadFileToMem(const std::string &filename, size_t &lenp, size_t maxsize)
Load a file into memory.
Definition fileio.cpp:1079
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?
Definition gfx.cpp:42
bool _left_button_clicked
Is left mouse button clicked?
Definition gfx.cpp:43
Functions related to the gfx engine.
Information about languages and their files.
const LanguageMetadata * _current_language
The currently loaded language.
Definition strings.cpp:54
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:90
Functions related to OTTD's strings.
Deals with finding savegames.
Definition fios.h:78
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:537
std::optional< std::string > GetClipboardContents()
Try to retrieve the current clipboard contents.
Definition win32.cpp:348
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:406
std::wstring OTTD2FS(std::string_view name)
Convert from OpenTTD's encoding to a wide string.
Definition win32.cpp:388
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:514
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:372
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:423
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:435
Declarations of functions for MS windows systems.