OpenTTD Source 20250524-master-gc366e6a48e
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 <http://www.gnu.org/licenses/>.
6 */
7
10#include "../../stdafx.h"
11#include "../../debug.h"
12#include "../../gfx_func.h"
13#include "../../textbuf_gui.h"
14#include "../../fileio_func.h"
15#include <windows.h>
16#include <fcntl.h>
17#include <mmsystem.h>
18#include <regstr.h>
19#define NO_SHOBJIDL_SORTDIRECTION // Avoid multiple definition of SORT_ASCENDING
20#include <shlobj.h> /* SHGetFolderPath */
21#include <shellapi.h>
22#include <winnls.h>
23#include <io.h>
24#include "win32.h"
25#include "../../fios.h"
26#include "../../string_func.h"
27#include <sys/stat.h>
28#include "../../language.h"
29#include "../../thread.h"
30#include "../../library_loader.h"
31
32#include "../../safeguards.h"
33
34static bool _has_console;
35static bool _cursor_disable = true;
36static bool _cursor_visible = true;
37
38bool MyShowCursor(bool show, bool toggle)
39{
40 if (toggle) _cursor_disable = !_cursor_disable;
41 if (_cursor_disable) return show;
42 if (_cursor_visible == show) return show;
43
44 _cursor_visible = show;
45 ShowCursor(show);
46
47 return !show;
48}
49
50void ShowOSErrorBox(std::string_view buf, bool)
51{
52 MyShowCursor(true);
53 MessageBox(GetActiveWindow(), OTTD2FS(buf).c_str(), L"Error!", MB_ICONSTOP | MB_TASKMODAL);
54}
55
56void OSOpenBrowser(const std::string &url)
57{
58 ShellExecute(GetActiveWindow(), L"open", OTTD2FS(url).c_str(), nullptr, nullptr, SW_SHOWNORMAL);
59}
60
61bool FiosIsRoot(const std::string &file)
62{
63 return file.size() == 3; // C:\...
64}
65
66void FiosGetDrives(FileList &file_list)
67{
68 wchar_t drives[256];
69 const wchar_t *s;
70
71 GetLogicalDriveStrings(static_cast<DWORD>(std::size(drives)), drives);
72 for (s = drives; *s != '\0';) {
73 FiosItem *fios = &file_list.emplace_back();
74 fios->type = FIOS_TYPE_DRIVE;
75 fios->mtime = 0;
76 fios->name += (char)(s[0] & 0xFF);
77 fios->name += ':';
78 fios->title = fios->name;
79 while (*s++ != '\0') { /* Nothing */ }
80 }
81}
82
83bool FiosIsHiddenFile(const std::filesystem::path &path)
84{
85 UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // Disable 'no-disk' message box.
86
87 DWORD attributes = GetFileAttributes(path.c_str());
88
89 SetErrorMode(sem); // Restore previous setting.
90
91 return (attributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) != 0;
92}
93
94std::optional<uint64_t> FiosGetDiskFreeSpace(const std::string &path)
95{
96 UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // disable 'no-disk' message box
97
98 ULARGE_INTEGER bytes_free;
99 bool retval = GetDiskFreeSpaceEx(OTTD2FS(path).c_str(), &bytes_free, nullptr, nullptr);
100
101 SetErrorMode(sem); // reset previous setting
102
103 if (retval) return bytes_free.QuadPart;
104 return std::nullopt;
105}
106
107void CreateConsole()
108{
109 HANDLE hand;
110 CONSOLE_SCREEN_BUFFER_INFO coninfo;
111
112 if (_has_console) return;
113 _has_console = true;
114
115 if (!AllocConsole()) return;
116
117 hand = GetStdHandle(STD_OUTPUT_HANDLE);
118 GetConsoleScreenBufferInfo(hand, &coninfo);
119 coninfo.dwSize.Y = 500;
120 SetConsoleScreenBufferSize(hand, coninfo.dwSize);
121
122 /* redirect unbuffered STDIN, STDOUT, STDERR to the console */
123#if !defined(__CYGWIN__)
124
125 /* Check if we can open a handle to STDOUT. */
126 int fd = _open_osfhandle((intptr_t)hand, _O_TEXT);
127 if (fd == -1) {
128 /* Free everything related to the console. */
129 FreeConsole();
130 _has_console = false;
131 _close(fd);
132 CloseHandle(hand);
133
134 ShowInfo("Unable to open an output handle to the console. Check known-bugs.md for details.");
135 return;
136 }
137
138#if defined(_MSC_VER)
139 freopen("CONOUT$", "a", stdout);
140 freopen("CONIN$", "r", stdin);
141 freopen("CONOUT$", "a", stderr);
142#else
143 *stdout = *_fdopen(fd, "w");
144 *stdin = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT), "r" );
145 *stderr = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT), "w" );
146#endif
147
148#else
149 /* open_osfhandle is not in cygwin */
150 *stdout = *fdopen(1, "w" );
151 *stdin = *fdopen(0, "r" );
152 *stderr = *fdopen(2, "w" );
153#endif
154
155 setvbuf(stdin, nullptr, _IONBF, 0);
156 setvbuf(stdout, nullptr, _IONBF, 0);
157 setvbuf(stderr, nullptr, _IONBF, 0);
158}
159
165static std::string ConvertLfToCrLf(std::string_view msg)
166{
167 std::string output;
168
169 size_t last = 0;
170 size_t next = 0;
171 while ((next = msg.find('\n', last)) != std::string_view::npos) {
172 output += msg.substr(last, next - last);
173 output += "\r\n";
174 last = next + 1;
175 }
176 output += msg.substr(last);
177
178 return output;
179}
180
182static INT_PTR CALLBACK HelpDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
183{
184 switch (msg) {
185 case WM_INITDIALOG: {
186 std::wstring &msg = *reinterpret_cast<std::wstring *>(lParam);
187 SetDlgItemText(wnd, 11, msg.c_str());
188 SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE);
189 } return TRUE;
190
191 case WM_COMMAND:
192 if (wParam == 12) ExitProcess(0);
193 return TRUE;
194 case WM_CLOSE:
195 ExitProcess(0);
196 }
197
198 return FALSE;
199}
200
201void ShowInfoI(std::string_view str)
202{
203 if (_has_console) {
204 fmt::print(stderr, "{}\n", str);
205 } else {
206 bool old;
207 ReleaseCapture();
209
210 old = MyShowCursor(true);
211 std::wstring native_str = OTTD2FS(ConvertLfToCrLf(str));
212 if (native_str.size() > 2048) {
213 /* The minimum length of the help message is 2048. Other messages sent via
214 * ShowInfo are much shorter, or so long they need this way of displaying
215 * them anyway. */
216 DialogBoxParam(GetModuleHandle(nullptr), MAKEINTRESOURCE(101), nullptr, HelpDialogFunc, reinterpret_cast<LPARAM>(&native_str));
217 } else {
218 MessageBox(GetActiveWindow(), native_str.c_str(), L"OpenTTD", MB_ICONINFORMATION | MB_OK);
219 }
220 MyShowCursor(old);
221 }
222}
223
224char *getcwd(char *buf, size_t size)
225{
226 wchar_t path[MAX_PATH];
227 GetCurrentDirectory(MAX_PATH - 1, path);
228 convert_from_fs(path, {buf, size});
229 return buf;
230}
231
232extern std::string _config_file;
233
234void DetermineBasePaths(std::string_view exe)
235{
236 extern std::array<std::string, NUM_SEARCHPATHS> _searchpaths;
237
238 wchar_t path[MAX_PATH];
239#ifdef WITH_PERSONAL_DIR
240 if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_PERSONAL, nullptr, SHGFP_TYPE_CURRENT, path))) {
241 std::string tmp(FS2OTTD(path));
243 tmp += PERSONAL_DIR;
246
247 tmp += "content_download";
250 } else {
252 }
253
254 if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_COMMON_DOCUMENTS, nullptr, SHGFP_TYPE_CURRENT, path))) {
255 std::string tmp(FS2OTTD(path));
257 tmp += PERSONAL_DIR;
260 } else {
262 }
263#else
266#endif
267
268 if (_config_file.empty()) {
269 char cwd[MAX_PATH];
270 getcwd(cwd, lengthof(cwd));
271 std::string cwd_s(cwd);
272 AppendPathSeparator(cwd_s);
274 } else {
275 /* Use the folder of the config file as working directory. */
276 wchar_t config_dir[MAX_PATH];
278 if (!GetFullPathName(path, static_cast<DWORD>(std::size(config_dir)), config_dir, nullptr)) {
279 Debug(misc, 0, "GetFullPathName failed ({})", GetLastError());
281 } else {
282 std::string tmp(FS2OTTD(config_dir));
283 auto pos = tmp.find_last_of(PATHSEPCHAR);
284 if (pos != std::string::npos) tmp.erase(pos + 1);
285
287 }
288 }
289
290 if (!GetModuleFileName(nullptr, path, static_cast<DWORD>(std::size(path)))) {
291 Debug(misc, 0, "GetModuleFileName failed ({})", GetLastError());
293 } else {
294 wchar_t exec_dir[MAX_PATH];
295 convert_to_fs(exe, path);
296 if (!GetFullPathName(path, static_cast<DWORD>(std::size(exec_dir)), exec_dir, nullptr)) {
297 Debug(misc, 0, "GetFullPathName failed ({})", GetLastError());
299 } else {
300 std::string tmp(FS2OTTD(exec_dir));
301 auto pos = tmp.find_last_of(PATHSEPCHAR);
302 if (pos != std::string::npos) tmp.erase(pos + 1);
303
305 }
306 }
307
310}
311
312
313std::optional<std::string> GetClipboardContents()
314{
315 if (!IsClipboardFormatAvailable(CF_UNICODETEXT)) return std::nullopt;
316
317 OpenClipboard(nullptr);
318 HGLOBAL cbuf = GetClipboardData(CF_UNICODETEXT);
319
320 std::string result = FS2OTTD(static_cast<LPCWSTR>(GlobalLock(cbuf)));
321 GlobalUnlock(cbuf);
322 CloseClipboard();
323
324 if (result.empty()) return std::nullopt;
325 return result;
326}
327
328
337std::string FS2OTTD(std::wstring_view name)
338{
339 int name_len = (name.length() >= INT_MAX) ? INT_MAX : static_cast<int>(name.length());
340 int len = WideCharToMultiByte(CP_UTF8, 0, name.data(), name_len, nullptr, 0, nullptr, nullptr);
341 if (len <= 0) return std::string();
342 std::string utf8_buf(len, '\0'); // len includes terminating null
343 WideCharToMultiByte(CP_UTF8, 0, name.data(), name_len, utf8_buf.data(), len, nullptr, nullptr);
344 return utf8_buf;
345}
346
354std::wstring OTTD2FS(std::string_view name)
355{
356 int name_len = (name.length() >= INT_MAX) ? INT_MAX : static_cast<int>(name.length());
357 int len = MultiByteToWideChar(CP_UTF8, 0, name.data(), name_len, nullptr, 0);
358 if (len <= 0) return std::wstring();
359 std::wstring system_buf(len, L'\0'); // len includes terminating null
360 MultiByteToWideChar(CP_UTF8, 0, name.data(), name_len, system_buf.data(), len);
361 return system_buf;
362}
363
364
372std::string_view convert_from_fs(const std::wstring_view src, std::span<char> dst_buf)
373{
374 /* Convert UTF-16 string to UTF-8. */
375 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);
376 dst_buf[len] = '\0';
377
378 return std::string_view(dst_buf.data(), len);
379}
380
381
389wchar_t *convert_to_fs(std::string_view src, std::span<wchar_t> dst_buf)
390{
391 int len = MultiByteToWideChar(CP_UTF8, 0, src.data(), static_cast<int>(src.size()), dst_buf.data(), static_cast<int>(dst_buf.size() - 1U));
392 dst_buf[len] = '\0';
393
394 return dst_buf.data();
395}
396
398std::optional<std::string> GetCurrentLocale(const char *)
399{
400 const LANGID userUiLang = GetUserDefaultUILanguage();
401 const LCID userUiLocale = MAKELCID(userUiLang, SORT_DEFAULT);
402
403 char lang[9], country[9];
404 if (GetLocaleInfoA(userUiLocale, LOCALE_SISO639LANGNAME, lang, static_cast<int>(std::size(lang))) == 0 ||
405 GetLocaleInfoA(userUiLocale, LOCALE_SISO3166CTRYNAME, country, static_cast<int>(std::size(country))) == 0) {
406 /* Unable to retrieve the locale. */
407 return nullptr;
408 }
409 /* Format it as 'en_us'. */
410 return fmt::format("{}_{}", std::string_view{lang, 2}, std::string_view{country, 2});
411}
412
413
414static WCHAR _cur_iso_locale[16] = L"";
415
416void Win32SetCurrentLocaleName(std::string iso_code)
417{
418 /* Convert the iso code into the format that windows expects. */
419 if (iso_code == "zh_TW") {
420 iso_code = "zh-Hant";
421 } else if (iso_code == "zh_CN") {
422 iso_code = "zh-Hans";
423 } else {
424 /* Windows expects a '-' between language and country code, but we use a '_'. */
425 for (char &c : iso_code) {
426 if (c == '_') c = '-';
427 }
428 }
429
430 MultiByteToWideChar(CP_UTF8, 0, iso_code.data(), static_cast<int>(iso_code.size()), _cur_iso_locale, static_cast<int>(std::size(_cur_iso_locale)));
431}
432
433static LibraryLoader::Function GetKernel32Function(const std::string &symbol_name)
434{
435 static LibraryLoader _kernel32("Kernel32.dll");
436 return _kernel32.GetFunction(symbol_name);
437}
438
439int OTTDStringCompare(std::string_view s1, std::string_view s2)
440{
441 typedef int (WINAPI *PFNCOMPARESTRINGEX)(LPCWSTR, DWORD, LPCWCH, int, LPCWCH, int, LPVOID, LPVOID, LPARAM);
442 static const PFNCOMPARESTRINGEX _CompareStringEx = GetKernel32Function("CompareStringEx");
443
444#ifndef SORT_DIGITSASNUMBERS
445# define SORT_DIGITSASNUMBERS 0x00000008 // use digits as numbers sort method
446#endif
447#ifndef LINGUISTIC_IGNORECASE
448# define LINGUISTIC_IGNORECASE 0x00000010 // linguistically appropriate 'ignore case'
449#endif
450
451 int len_s1 = MultiByteToWideChar(CP_UTF8, 0, s1.data(), (int)s1.size(), nullptr, 0);
452 int len_s2 = MultiByteToWideChar(CP_UTF8, 0, s2.data(), (int)s2.size(), nullptr, 0);
453
454 std::wstring str_s1(len_s1, L'\0');
455 std::wstring str_s2(len_s2, L'\0');
456
457 if (len_s1 != 0) MultiByteToWideChar(CP_UTF8, 0, s1.data(), (int)s1.size(), str_s1.data(), len_s1);
458 if (len_s2 != 0) MultiByteToWideChar(CP_UTF8, 0, s2.data(), (int)s2.size(), str_s2.data(), len_s2);
459
460 /* CompareStringEx takes UTF-16 strings, even in ANSI-builds. */
461 if (_CompareStringEx != nullptr) {
462 int result = _CompareStringEx(_cur_iso_locale, LINGUISTIC_IGNORECASE | SORT_DIGITSASNUMBERS, str_s1.data(), len_s1, str_s2.data(), len_s2, nullptr, nullptr, 0);
463 if (result != 0) return result;
464 }
465
466 return CompareString(MAKELCID(_current_language->winlangid, SORT_DEFAULT), NORM_IGNORECASE, str_s1.data(), len_s1, str_s2.data(), len_s2);
467}
468
477int Win32StringContains(std::string_view str, std::string_view value, bool case_insensitive)
478{
479 typedef int (WINAPI *PFNFINDNLSSTRINGEX)(LPCWSTR, DWORD, LPCWSTR, int, LPCWSTR, int, LPINT, LPNLSVERSIONINFO, LPVOID, LPARAM);
480 static const PFNFINDNLSSTRINGEX _FindNLSStringEx = GetKernel32Function("FindNLSStringEx");
481
482 if (_FindNLSStringEx != nullptr) {
483 int len_str = MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), nullptr, 0);
484 int len_value = MultiByteToWideChar(CP_UTF8, 0, value.data(), (int)value.size(), nullptr, 0);
485
486 if (len_str != 0 && len_value != 0) {
487 std::wstring str_str(len_str, L'\0');
488 std::wstring str_value(len_value, L'\0');
489
490 MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), str_str.data(), len_str);
491 MultiByteToWideChar(CP_UTF8, 0, value.data(), (int)value.size(), str_value.data(), len_value);
492
493 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;
494 }
495 }
496
497 return -1; // Failure indication.
498}
499
500#ifdef _MSC_VER
501/* Based on code from MSDN: https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx */
502const DWORD MS_VC_EXCEPTION = 0x406D1388;
503
504PACK_N(struct THREADNAME_INFO {
505 DWORD dwType;
506 LPCSTR szName;
507 DWORD dwThreadID;
508 DWORD dwFlags;
509}, 8);
510
514void SetCurrentThreadName(const std::string &thread_name)
515{
516 THREADNAME_INFO info;
517 info.dwType = 0x1000;
518 info.szName = thread_name.c_str();
519 info.dwThreadID = -1;
520 info.dwFlags = 0;
521
522#pragma warning(push)
523#pragma warning(disable: 6320 6322)
524 __try {
525 RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
526 } __except (EXCEPTION_EXECUTE_HANDLER) {
527 }
528#pragma warning(pop)
529}
530#else
531void SetCurrentThreadName(const std::string &) {}
532#endif
List of file information.
Definition fios.h:87
A function loaded from a library.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
void DetermineBasePaths(std::string_view exe)
Determine the base (personal dir and game data dir) paths.
Definition fileio.cpp:750
void AppendPathSeparator(std::string &buf)
Appends, if necessary, the path separator character to the end of the string.
Definition fileio.cpp:345
std::array< std::string, NUM_SEARCHPATHS > _searchpaths
The search paths OpenTTD could search through.
Definition fileio.cpp:65
@ SP_SHARED_DIR
Search in the shared directory, like 'Shared Files' under Windows.
@ SP_INSTALLATION_DIR
Search in the installation directory.
@ SP_BINARY_DIR
Search in the directory where the binary resides.
@ SP_AUTODOWNLOAD_PERSONAL_DIR
Search within the autodownload directory located in the personal directory.
@ SP_PERSONAL_DIR
Search in the personal directory.
@ SP_WORKING_DIR
Search in the working directory.
@ SP_APPLICATION_BUNDLE_DIR
Search within the application bundle.
bool _left_button_down
Is left mouse button pressed?
Definition gfx.cpp:41
bool _left_button_clicked
Is left mouse button clicked?
Definition gfx.cpp:42
const LanguageMetadata * _current_language
The currently loaded language.
Definition strings.cpp:55
#define lengthof(array)
Return the length of an fixed size array.
Definition stdafx.h:271
Deals with finding savegames.
Definition fios.h:78
uint16_t winlangid
Windows language ID: Windows cannot and will not convert isocodes to something it can use to determin...
Definition language.h:51
std::optional< std::string > GetClipboardContents()
Try to retrieve the current clipboard contents.
Definition win32.cpp:313
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:372
std::wstring OTTD2FS(std::string_view name)
Convert from OpenTTD's encoding to a wide string.
Definition win32.cpp:354
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:477
static std::string ConvertLfToCrLf(std::string_view msg)
Replace linefeeds with carriage-return and linefeed.
Definition win32.cpp:165
void SetCurrentThreadName(const std::string &)
Name the thread this function is called on for the debugger.
Definition win32.cpp:531
static INT_PTR CALLBACK HelpDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
Callback function to handle the window.
Definition win32.cpp:182
std::string FS2OTTD(std::wstring_view name)
Convert to OpenTTD's encoding from a wide string.
Definition win32.cpp:337
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:389
std::string _config_file
Configuration file of OpenTTD.
Definition settings.cpp:63
std::optional< std::string > GetCurrentLocale(const char *)
Determine the current user's locale.
Definition win32.cpp:398
declarations of functions for MS windows systems