OpenTTD
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 <regstr.h>
18 #define NO_SHOBJIDL_SORTDIRECTION // Avoid multiple definition of SORT_ASCENDING
19 #include <shlobj.h> /* SHGetFolderPath */
20 #include <shellapi.h>
21 #include "win32.h"
22 #include "../../fios.h"
23 #include "../../core/alloc_func.hpp"
24 #include "../../openttd.h"
25 #include "../../core/random_func.hpp"
26 #include "../../string_func.h"
27 #include "../../crashlog.h"
28 #include <errno.h>
29 #include <sys/stat.h>
30 #include "../../language.h"
31 #include "../../thread.h"
32 
33 #include "../../safeguards.h"
34 
35 static bool _has_console;
36 static bool _cursor_disable = true;
37 static bool _cursor_visible = true;
38 
39 bool MyShowCursor(bool show, bool toggle)
40 {
41  if (toggle) _cursor_disable = !_cursor_disable;
42  if (_cursor_disable) return show;
43  if (_cursor_visible == show) return show;
44 
45  _cursor_visible = show;
46  ShowCursor(show);
47 
48  return !show;
49 }
50 
56 bool LoadLibraryList(Function proc[], const char *dll)
57 {
58  while (*dll != '\0') {
59  HMODULE lib;
60  lib = LoadLibrary(MB_TO_WIDE(dll));
61 
62  if (lib == nullptr) return false;
63  for (;;) {
64  FARPROC p;
65 
66  while (*dll++ != '\0') { /* Nothing */ }
67  if (*dll == '\0') break;
68  p = GetProcAddress(lib, dll);
69  if (p == nullptr) return false;
70  *proc++ = (Function)p;
71  }
72  dll++;
73  }
74  return true;
75 }
76 
77 void ShowOSErrorBox(const char *buf, bool system)
78 {
79  MyShowCursor(true);
80  MessageBox(GetActiveWindow(), OTTD2FS(buf), _T("Error!"), MB_ICONSTOP | MB_TASKMODAL);
81 }
82 
83 void OSOpenBrowser(const char *url)
84 {
85  ShellExecute(GetActiveWindow(), _T("open"), OTTD2FS(url), nullptr, nullptr, SW_SHOWNORMAL);
86 }
87 
88 /* Code below for windows version of opendir/readdir/closedir copied and
89  * modified from Jan Wassenberg's GPL implementation posted over at
90  * http://www.gamedev.net/community/forums/topic.asp?topic_id=364584&whichpage=1&#2398903 */
91 
92 struct DIR {
93  HANDLE hFind;
94  /* the dirent returned by readdir.
95  * note: having only one global instance is not possible because
96  * multiple independent opendir/readdir sequences must be supported. */
97  dirent ent;
98  WIN32_FIND_DATA fd;
99  /* since opendir calls FindFirstFile, we need a means of telling the
100  * first call to readdir that we already have a file.
101  * that's the case iff this is true */
102  bool at_first_entry;
103 };
104 
105 /* suballocator - satisfies most requests with a reusable static instance.
106  * this avoids hundreds of alloc/free which would fragment the heap.
107  * To guarantee concurrency, we fall back to malloc if the instance is
108  * already in use (it's important to avoid surprises since this is such a
109  * low-level routine). */
110 static DIR _global_dir;
111 static LONG _global_dir_is_in_use = false;
112 
113 static inline DIR *dir_calloc()
114 {
115  DIR *d;
116 
117  if (InterlockedExchange(&_global_dir_is_in_use, true) == (LONG)true) {
118  d = CallocT<DIR>(1);
119  } else {
120  d = &_global_dir;
121  memset(d, 0, sizeof(*d));
122  }
123  return d;
124 }
125 
126 static inline void dir_free(DIR *d)
127 {
128  if (d == &_global_dir) {
129  _global_dir_is_in_use = (LONG)false;
130  } else {
131  free(d);
132  }
133 }
134 
135 DIR *opendir(const TCHAR *path)
136 {
137  DIR *d;
138  UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // disable 'no-disk' message box
139  DWORD fa = GetFileAttributes(path);
140 
141  if ((fa != INVALID_FILE_ATTRIBUTES) && (fa & FILE_ATTRIBUTE_DIRECTORY)) {
142  d = dir_calloc();
143  if (d != nullptr) {
144  TCHAR search_path[MAX_PATH];
145  bool slash = path[_tcslen(path) - 1] == '\\';
146 
147  /* build search path for FindFirstFile, try not to append additional slashes
148  * as it throws Win9x off its groove for root directories */
149  _sntprintf(search_path, lengthof(search_path), _T("%s%s*"), path, slash ? _T("") : _T("\\"));
150  *lastof(search_path) = '\0';
151  d->hFind = FindFirstFile(search_path, &d->fd);
152 
153  if (d->hFind != INVALID_HANDLE_VALUE ||
154  GetLastError() == ERROR_NO_MORE_FILES) { // the directory is empty
155  d->ent.dir = d;
156  d->at_first_entry = true;
157  } else {
158  dir_free(d);
159  d = nullptr;
160  }
161  } else {
162  errno = ENOMEM;
163  }
164  } else {
165  /* path not found or not a directory */
166  d = nullptr;
167  errno = ENOENT;
168  }
169 
170  SetErrorMode(sem); // restore previous setting
171  return d;
172 }
173 
174 struct dirent *readdir(DIR *d)
175 {
176  DWORD prev_err = GetLastError(); // avoid polluting last error
177 
178  if (d->at_first_entry) {
179  /* the directory was empty when opened */
180  if (d->hFind == INVALID_HANDLE_VALUE) return nullptr;
181  d->at_first_entry = false;
182  } else if (!FindNextFile(d->hFind, &d->fd)) { // determine cause and bail
183  if (GetLastError() == ERROR_NO_MORE_FILES) SetLastError(prev_err);
184  return nullptr;
185  }
186 
187  /* This entry has passed all checks; return information about it.
188  * (note: d_name is a pointer; see struct dirent definition) */
189  d->ent.d_name = d->fd.cFileName;
190  return &d->ent;
191 }
192 
193 int closedir(DIR *d)
194 {
195  FindClose(d->hFind);
196  dir_free(d);
197  return 0;
198 }
199 
200 bool FiosIsRoot(const char *file)
201 {
202  return file[3] == '\0'; // C:\...
203 }
204 
205 void FiosGetDrives(FileList &file_list)
206 {
207  TCHAR drives[256];
208  const TCHAR *s;
209 
210  GetLogicalDriveStrings(lengthof(drives), drives);
211  for (s = drives; *s != '\0';) {
212  FiosItem *fios = file_list.Append();
213  fios->type = FIOS_TYPE_DRIVE;
214  fios->mtime = 0;
215  seprintf(fios->name, lastof(fios->name), "%c:", s[0] & 0xFF);
216  strecpy(fios->title, fios->name, lastof(fios->title));
217  while (*s++ != '\0') { /* Nothing */ }
218  }
219 }
220 
221 bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb)
222 {
223  /* hectonanoseconds between Windows and POSIX epoch */
224  static const int64 posix_epoch_hns = 0x019DB1DED53E8000LL;
225  const WIN32_FIND_DATA *fd = &ent->dir->fd;
226 
227  sb->st_size = ((uint64) fd->nFileSizeHigh << 32) + fd->nFileSizeLow;
228  /* UTC FILETIME to seconds-since-1970 UTC
229  * we just have to subtract POSIX epoch and scale down to units of seconds.
230  * http://www.gamedev.net/community/forums/topic.asp?topic_id=294070&whichpage=1&#1860504
231  * XXX - not entirely correct, since filetimes on FAT aren't UTC but local,
232  * this won't entirely be correct, but we use the time only for comparison. */
233  sb->st_mtime = (time_t)((*(const uint64*)&fd->ftLastWriteTime - posix_epoch_hns) / 1E7);
234  sb->st_mode = (fd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)? S_IFDIR : S_IFREG;
235 
236  return true;
237 }
238 
239 bool FiosIsHiddenFile(const struct dirent *ent)
240 {
241  return (ent->dir->fd.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) != 0;
242 }
243 
244 bool FiosGetDiskFreeSpace(const char *path, uint64 *tot)
245 {
246  UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // disable 'no-disk' message box
247  bool retval = false;
248  TCHAR root[4];
249  DWORD spc, bps, nfc, tnc;
250 
251  _sntprintf(root, lengthof(root), _T("%c:") _T(PATHSEP), path[0]);
252  if (tot != nullptr && GetDiskFreeSpace(root, &spc, &bps, &nfc, &tnc)) {
253  *tot = ((spc * bps) * (uint64)nfc);
254  retval = true;
255  }
256 
257  SetErrorMode(sem); // reset previous setting
258  return retval;
259 }
260 
261 static int ParseCommandLine(char *line, char **argv, int max_argc)
262 {
263  int n = 0;
264 
265  do {
266  /* skip whitespace */
267  while (*line == ' ' || *line == '\t') line++;
268 
269  /* end? */
270  if (*line == '\0') break;
271 
272  /* special handling when quoted */
273  if (*line == '"') {
274  argv[n++] = ++line;
275  while (*line != '"') {
276  if (*line == '\0') return n;
277  line++;
278  }
279  } else {
280  argv[n++] = line;
281  while (*line != ' ' && *line != '\t') {
282  if (*line == '\0') return n;
283  line++;
284  }
285  }
286  *line++ = '\0';
287  } while (n != max_argc);
288 
289  return n;
290 }
291 
292 void CreateConsole()
293 {
294  HANDLE hand;
295  CONSOLE_SCREEN_BUFFER_INFO coninfo;
296 
297  if (_has_console) return;
298  _has_console = true;
299 
300  if (!AllocConsole()) return;
301 
302  hand = GetStdHandle(STD_OUTPUT_HANDLE);
303  GetConsoleScreenBufferInfo(hand, &coninfo);
304  coninfo.dwSize.Y = 500;
305  SetConsoleScreenBufferSize(hand, coninfo.dwSize);
306 
307  /* redirect unbuffered STDIN, STDOUT, STDERR to the console */
308 #if !defined(__CYGWIN__)
309 
310  /* Check if we can open a handle to STDOUT. */
311  int fd = _open_osfhandle((intptr_t)hand, _O_TEXT);
312  if (fd == -1) {
313  /* Free everything related to the console. */
314  FreeConsole();
315  _has_console = false;
316  _close(fd);
317  CloseHandle(hand);
318 
319  ShowInfo("Unable to open an output handle to the console. Check known-bugs.txt for details.");
320  return;
321  }
322 
323 #if defined(_MSC_VER) && _MSC_VER >= 1900
324  freopen("CONOUT$", "a", stdout);
325  freopen("CONIN$", "r", stdin);
326  freopen("CONOUT$", "a", stderr);
327 #else
328  *stdout = *_fdopen(fd, "w");
329  *stdin = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT), "r" );
330  *stderr = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT), "w" );
331 #endif
332 
333 #else
334  /* open_osfhandle is not in cygwin */
335  *stdout = *fdopen(1, "w" );
336  *stdin = *fdopen(0, "r" );
337  *stderr = *fdopen(2, "w" );
338 #endif
339 
340  setvbuf(stdin, nullptr, _IONBF, 0);
341  setvbuf(stdout, nullptr, _IONBF, 0);
342  setvbuf(stderr, nullptr, _IONBF, 0);
343 }
344 
346 static const char *_help_msg;
347 
349 static INT_PTR CALLBACK HelpDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
350 {
351  switch (msg) {
352  case WM_INITDIALOG: {
353  char help_msg[8192];
354  const char *p = _help_msg;
355  char *q = help_msg;
356  while (q != lastof(help_msg) && *p != '\0') {
357  if (*p == '\n') {
358  *q++ = '\r';
359  if (q == lastof(help_msg)) {
360  q[-1] = '\0';
361  break;
362  }
363  }
364  *q++ = *p++;
365  }
366  *q = '\0';
367  /* We need to put the text in a separate buffer because the default
368  * buffer in OTTD2FS might not be large enough (512 chars). */
369  TCHAR help_msg_buf[8192];
370  SetDlgItemText(wnd, 11, convert_to_fs(help_msg, help_msg_buf, lengthof(help_msg_buf)));
371  SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE);
372  } return TRUE;
373 
374  case WM_COMMAND:
375  if (wParam == 12) ExitProcess(0);
376  return TRUE;
377  case WM_CLOSE:
378  ExitProcess(0);
379  }
380 
381  return FALSE;
382 }
383 
384 void ShowInfo(const char *str)
385 {
386  if (_has_console) {
387  fprintf(stderr, "%s\n", str);
388  } else {
389  bool old;
390  ReleaseCapture();
392 
393  old = MyShowCursor(true);
394  if (strlen(str) > 2048) {
395  /* The minimum length of the help message is 2048. Other messages sent via
396  * ShowInfo are much shorter, or so long they need this way of displaying
397  * them anyway. */
398  _help_msg = str;
399  DialogBox(GetModuleHandle(nullptr), MAKEINTRESOURCE(101), nullptr, HelpDialogFunc);
400  } else {
401  /* We need to put the text in a separate buffer because the default
402  * buffer in OTTD2FS might not be large enough (512 chars). */
403  TCHAR help_msg_buf[8192];
404  MessageBox(GetActiveWindow(), convert_to_fs(str, help_msg_buf, lengthof(help_msg_buf)), _T("OpenTTD"), MB_ICONINFORMATION | MB_OK);
405  }
406  MyShowCursor(old);
407  }
408 }
409 
410 int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
411 {
412  int argc;
413  char *argv[64]; // max 64 command line arguments
414 
416 
417 #if defined(UNICODE)
418  /* Check if a win9x user started the win32 version */
419  if (HasBit(GetVersion(), 31)) usererror("This version of OpenTTD doesn't run on windows 95/98/ME.\nPlease download the win9x binary and try again.");
420 #endif
421 
422  /* Convert the command line to UTF-8. We need a dedicated buffer
423  * for this because argv[] points into this buffer and this needs to
424  * be available between subsequent calls to FS2OTTD(). */
425  char *cmdline = stredup(FS2OTTD(GetCommandLine()));
426 
427 #if defined(_DEBUG)
428  CreateConsole();
429 #endif
430 
431  _set_error_mode(_OUT_TO_MSGBOX); // force assertion output to messagebox
432 
433  /* setup random seed to something quite random */
434  SetRandomSeed(GetTickCount());
435 
436  argc = ParseCommandLine(cmdline, argv, lengthof(argv));
437 
438  /* Make sure our arguments contain only valid UTF-8 characters. */
439  for (int i = 0; i < argc; i++) ValidateString(argv[i]);
440 
441  openttd_main(argc, argv);
442  free(cmdline);
443  return 0;
444 }
445 
446 char *getcwd(char *buf, size_t size)
447 {
448  TCHAR path[MAX_PATH];
449  GetCurrentDirectory(MAX_PATH - 1, path);
450  convert_from_fs(path, buf, size);
451  return buf;
452 }
453 
454 
455 void DetermineBasePaths(const char *exe)
456 {
457  char tmp[MAX_PATH];
458  TCHAR path[MAX_PATH];
459 #ifdef WITH_PERSONAL_DIR
460  if (SUCCEEDED(OTTDSHGetFolderPath(nullptr, CSIDL_PERSONAL, nullptr, SHGFP_TYPE_CURRENT, path))) {
461  strecpy(tmp, FS2OTTD(path), lastof(tmp));
462  AppendPathSeparator(tmp, lastof(tmp));
463  strecat(tmp, PERSONAL_DIR, lastof(tmp));
464  AppendPathSeparator(tmp, lastof(tmp));
466  } else {
467  _searchpaths[SP_PERSONAL_DIR] = nullptr;
468  }
469 
470  if (SUCCEEDED(OTTDSHGetFolderPath(nullptr, CSIDL_COMMON_DOCUMENTS, nullptr, SHGFP_TYPE_CURRENT, path))) {
471  strecpy(tmp, FS2OTTD(path), lastof(tmp));
472  AppendPathSeparator(tmp, lastof(tmp));
473  strecat(tmp, PERSONAL_DIR, lastof(tmp));
474  AppendPathSeparator(tmp, lastof(tmp));
476  } else {
477  _searchpaths[SP_SHARED_DIR] = nullptr;
478  }
479 #else
480  _searchpaths[SP_PERSONAL_DIR] = nullptr;
481  _searchpaths[SP_SHARED_DIR] = nullptr;
482 #endif
483 
484  /* Get the path to working directory of OpenTTD */
485  getcwd(tmp, lengthof(tmp));
486  AppendPathSeparator(tmp, lastof(tmp));
488 
489  if (!GetModuleFileName(nullptr, path, lengthof(path))) {
490  DEBUG(misc, 0, "GetModuleFileName failed (%lu)\n", GetLastError());
491  _searchpaths[SP_BINARY_DIR] = nullptr;
492  } else {
493  TCHAR exec_dir[MAX_PATH];
494  _tcsncpy(path, convert_to_fs(exe, path, lengthof(path)), lengthof(path));
495  if (!GetFullPathName(path, lengthof(exec_dir), exec_dir, nullptr)) {
496  DEBUG(misc, 0, "GetFullPathName failed (%lu)\n", GetLastError());
497  _searchpaths[SP_BINARY_DIR] = nullptr;
498  } else {
499  strecpy(tmp, convert_from_fs(exec_dir, tmp, lengthof(tmp)), lastof(tmp));
500  char *s = strrchr(tmp, PATHSEPCHAR);
501  *(s + 1) = '\0';
503  }
504  }
505 
508 }
509 
510 
511 bool GetClipboardContents(char *buffer, const char *last)
512 {
513  HGLOBAL cbuf;
514  const char *ptr;
515 
516  if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
517  OpenClipboard(nullptr);
518  cbuf = GetClipboardData(CF_UNICODETEXT);
519 
520  ptr = (const char*)GlobalLock(cbuf);
521  int out_len = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)ptr, -1, buffer, (last - buffer) + 1, nullptr, nullptr);
522  GlobalUnlock(cbuf);
523  CloseClipboard();
524 
525  if (out_len == 0) return false;
526 #if !defined(UNICODE)
527  } else if (IsClipboardFormatAvailable(CF_TEXT)) {
528  OpenClipboard(nullptr);
529  cbuf = GetClipboardData(CF_TEXT);
530 
531  ptr = (const char*)GlobalLock(cbuf);
532  strecpy(buffer, FS2OTTD(ptr), last);
533 
534  GlobalUnlock(cbuf);
535  CloseClipboard();
536 #endif /* UNICODE */
537  } else {
538  return false;
539  }
540 
541  return true;
542 }
543 
544 
558 const char *FS2OTTD(const TCHAR *name)
559 {
560  static char utf8_buf[512];
561  return convert_from_fs(name, utf8_buf, lengthof(utf8_buf));
562 }
563 
576 const TCHAR *OTTD2FS(const char *name, bool console_cp)
577 {
578  static TCHAR system_buf[512];
579  return convert_to_fs(name, system_buf, lengthof(system_buf), console_cp);
580 }
581 
582 
591 char *convert_from_fs(const TCHAR *name, char *utf8_buf, size_t buflen)
592 {
593 #if defined(UNICODE)
594  const WCHAR *wide_buf = name;
595 #else
596  /* Convert string from the local codepage to UTF-16. */
597  int wide_len = MultiByteToWideChar(CP_ACP, 0, name, -1, nullptr, 0);
598  if (wide_len == 0) {
599  utf8_buf[0] = '\0';
600  return utf8_buf;
601  }
602 
603  WCHAR *wide_buf = AllocaM(WCHAR, wide_len);
604  MultiByteToWideChar(CP_ACP, 0, name, -1, wide_buf, wide_len);
605 #endif
606 
607  /* Convert UTF-16 string to UTF-8. */
608  int len = WideCharToMultiByte(CP_UTF8, 0, wide_buf, -1, utf8_buf, (int)buflen, nullptr, nullptr);
609  if (len == 0) utf8_buf[0] = '\0';
610 
611  return utf8_buf;
612 }
613 
614 
625 TCHAR *convert_to_fs(const char *name, TCHAR *system_buf, size_t buflen, bool console_cp)
626 {
627 #if defined(UNICODE)
628  int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, system_buf, (int)buflen);
629  if (len == 0) system_buf[0] = '\0';
630 #else
631  int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, nullptr, 0);
632  if (len == 0) {
633  system_buf[0] = '\0';
634  return system_buf;
635  }
636 
637  WCHAR *wide_buf = AllocaM(WCHAR, len);
638  MultiByteToWideChar(CP_UTF8, 0, name, -1, wide_buf, len);
639 
640  len = WideCharToMultiByte(console_cp ? CP_OEMCP : CP_ACP, 0, wide_buf, len, system_buf, (int)buflen, nullptr, nullptr);
641  if (len == 0) system_buf[0] = '\0';
642 #endif
643 
644  return system_buf;
645 }
646 
653 HRESULT OTTDSHGetFolderPath(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPTSTR pszPath)
654 {
655  static HRESULT (WINAPI *SHGetFolderPath)(HWND, int, HANDLE, DWORD, LPTSTR) = nullptr;
656  static bool first_time = true;
657 
658  /* We only try to load the library one time; if it fails, it fails */
659  if (first_time) {
660 #if defined(UNICODE)
661 # define W(x) x "W"
662 #else
663 # define W(x) x "A"
664 #endif
665  /* The function lives in shell32.dll for all current Windows versions, but it first started to appear in SHFolder.dll. */
666  if (!LoadLibraryList((Function*)&SHGetFolderPath, "shell32.dll\0" W("SHGetFolderPath") "\0\0")) {
667  if (!LoadLibraryList((Function*)&SHGetFolderPath, "SHFolder.dll\0" W("SHGetFolderPath") "\0\0")) {
668  DEBUG(misc, 0, "Unable to load " W("SHGetFolderPath") "from either shell32.dll or SHFolder.dll");
669  }
670  }
671 #undef W
672  first_time = false;
673  }
674 
675  if (SHGetFolderPath != nullptr) return SHGetFolderPath(hwnd, csidl, hToken, dwFlags, pszPath);
676 
677  /* SHGetFolderPath doesn't exist, try a more conservative approach,
678  * eg environment variables. This is only included for legacy modes
679  * MSDN says: that 'pszPath' is a "Pointer to a null-terminated string of
680  * length MAX_PATH which will receive the path" so let's assume that
681  * Windows 95 with Internet Explorer 5.0, Windows 98 with Internet Explorer 5.0,
682  * Windows 98 Second Edition (SE), Windows NT 4.0 with Internet Explorer 5.0,
683  * Windows NT 4.0 with Service Pack 4 (SP4) */
684  {
685  DWORD ret;
686  switch (csidl) {
687  case CSIDL_FONTS: // Get the system font path, eg %WINDIR%\Fonts
688  ret = GetEnvironmentVariable(_T("WINDIR"), pszPath, MAX_PATH);
689  if (ret == 0) break;
690  _tcsncat(pszPath, _T("\\Fonts"), MAX_PATH);
691 
692  return (HRESULT)0;
693 
694  case CSIDL_PERSONAL:
695  case CSIDL_COMMON_DOCUMENTS: {
696  HKEY key;
697  if (RegOpenKeyEx(csidl == CSIDL_PERSONAL ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, REGSTR_PATH_SPECIAL_FOLDERS, 0, KEY_READ, &key) != ERROR_SUCCESS) break;
698  DWORD len = MAX_PATH;
699  ret = RegQueryValueEx(key, csidl == CSIDL_PERSONAL ? _T("Personal") : _T("Common Documents"), nullptr, nullptr, (LPBYTE)pszPath, &len);
700  RegCloseKey(key);
701  if (ret == ERROR_SUCCESS) return (HRESULT)0;
702  break;
703  }
704 
705  /* XXX - other types to go here when needed... */
706  }
707  }
708 
709  return E_INVALIDARG;
710 }
711 
713 const char *GetCurrentLocale(const char *)
714 {
715  char lang[9], country[9];
716  if (GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, lang, lengthof(lang)) == 0 ||
717  GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, country, lengthof(country)) == 0) {
718  /* Unable to retrieve the locale. */
719  return nullptr;
720  }
721  /* Format it as 'en_us'. */
722  static char retbuf[6] = {lang[0], lang[1], '_', country[0], country[1], 0};
723  return retbuf;
724 }
725 
726 
727 static WCHAR _cur_iso_locale[16] = L"";
728 
729 void Win32SetCurrentLocaleName(const char *iso_code)
730 {
731  /* Convert the iso code into the format that windows expects. */
732  char iso[16];
733  if (strcmp(iso_code, "zh_TW") == 0) {
734  strecpy(iso, "zh-Hant", lastof(iso));
735  } else if (strcmp(iso_code, "zh_CN") == 0) {
736  strecpy(iso, "zh-Hans", lastof(iso));
737  } else {
738  /* Windows expects a '-' between language and country code, but we use a '_'. */
739  strecpy(iso, iso_code, lastof(iso));
740  for (char *c = iso; *c != '\0'; c++) {
741  if (*c == '_') *c = '-';
742  }
743  }
744 
745  MultiByteToWideChar(CP_UTF8, 0, iso, -1, _cur_iso_locale, lengthof(_cur_iso_locale));
746 }
747 
748 int OTTDStringCompare(const char *s1, const char *s2)
749 {
750  typedef int (WINAPI *PFNCOMPARESTRINGEX)(LPCWSTR, DWORD, LPCWCH, int, LPCWCH, int, LPVOID, LPVOID, LPARAM);
751  static PFNCOMPARESTRINGEX _CompareStringEx = nullptr;
752  static bool first_time = true;
753 
754 #ifndef SORT_DIGITSASNUMBERS
755 # define SORT_DIGITSASNUMBERS 0x00000008 // use digits as numbers sort method
756 #endif
757 #ifndef LINGUISTIC_IGNORECASE
758 # define LINGUISTIC_IGNORECASE 0x00000010 // linguistically appropriate 'ignore case'
759 #endif
760 
761  if (first_time) {
762  _CompareStringEx = (PFNCOMPARESTRINGEX)GetProcAddress(GetModuleHandle(_T("Kernel32")), "CompareStringEx");
763  first_time = false;
764  }
765 
766  if (_CompareStringEx != nullptr) {
767  /* CompareStringEx takes UTF-16 strings, even in ANSI-builds. */
768  int len_s1 = MultiByteToWideChar(CP_UTF8, 0, s1, -1, nullptr, 0);
769  int len_s2 = MultiByteToWideChar(CP_UTF8, 0, s2, -1, nullptr, 0);
770 
771  if (len_s1 != 0 && len_s2 != 0) {
772  LPWSTR str_s1 = AllocaM(WCHAR, len_s1);
773  LPWSTR str_s2 = AllocaM(WCHAR, len_s2);
774 
775  MultiByteToWideChar(CP_UTF8, 0, s1, -1, str_s1, len_s1);
776  MultiByteToWideChar(CP_UTF8, 0, s2, -1, str_s2, len_s2);
777 
778  int result = _CompareStringEx(_cur_iso_locale, LINGUISTIC_IGNORECASE | SORT_DIGITSASNUMBERS, str_s1, -1, str_s2, -1, nullptr, nullptr, 0);
779  if (result != 0) return result;
780  }
781  }
782 
783  TCHAR s1_buf[512], s2_buf[512];
784  convert_to_fs(s1, s1_buf, lengthof(s1_buf));
785  convert_to_fs(s2, s2_buf, lengthof(s2_buf));
786 
787  return CompareString(MAKELCID(_current_language->winlangid, SORT_DEFAULT), NORM_IGNORECASE, s1_buf, -1, s2_buf, -1);
788 }
789 
790 #ifdef _MSC_VER
791 /* Based on code from MSDN: https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx */
792 const DWORD MS_VC_EXCEPTION = 0x406D1388;
793 
794 PACK_N(struct THREADNAME_INFO {
795  DWORD dwType;
796  LPCSTR szName;
797  DWORD dwThreadID;
798  DWORD dwFlags;
799 }, 8);
800 
804 void SetCurrentThreadName(const char *threadName)
805 {
806  THREADNAME_INFO info;
807  info.dwType = 0x1000;
808  info.szName = threadName;
809  info.dwThreadID = -1;
810  info.dwFlags = 0;
811 
812 #pragma warning(push)
813 #pragma warning(disable: 6320 6322)
814  __try {
815  RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
816  } __except (EXCEPTION_EXECUTE_HANDLER) {
817  }
818 #pragma warning(pop)
819 }
820 #else
821 void SetCurrentThreadName(const char *) {}
822 #endif
int openttd_main(int argc, char *argv[])
Main entry point for this lovely game.
Definition: openttd.cpp:533
static char * strecat(char *dst, const char *src, const char *last)
Appends characters from one string to another.
Definition: depend.cpp:97
TCHAR * convert_to_fs(const char *name, TCHAR *system_buf, size_t buflen, bool console_cp)
Convert from OpenTTD&#39;s encoding to that of the environment in UNICODE.
Definition: win32.cpp:625
const char * FS2OTTD(const TCHAR *name)
Convert to OpenTTD&#39;s encoding from that of the local environment.
Definition: win32.cpp:558
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:407
Search in the directory where the binary resides.
Definition: fileio_type.h:139
HRESULT OTTDSHGetFolderPath(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPTSTR pszPath)
Our very own SHGetFolderPath function for support of windows operating systems that don&#39;t have this f...
Definition: win32.cpp:653
void SetRandomSeed(uint32 seed)
(Re)set the state of the random number generators.
Definition: random_func.cpp:65
const LanguageMetadata * _current_language
The currently loaded language.
Definition: strings.cpp:46
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:48
static void InitialiseCrashLog()
Initialiser for crash logs; do the appropriate things so crashes are handled by our crash handler ins...
#define AllocaM(T, num_elements)
alloca() has to be called in the parent function, so define AllocaM() as a macro
Definition: alloc_func.hpp:132
char * convert_from_fs(const TCHAR *name, char *utf8_buf, size_t buflen)
Convert to OpenTTD&#39;s encoding from that of the environment in UNICODE.
Definition: win32.cpp:591
const char * GetCurrentLocale(const char *)
Determine the current user&#39;s locale.
Definition: win32.cpp:713
uint16 winlangid
Windows language ID: Windows cannot and will not convert isocodes to something it can use to determin...
Definition: language.h:51
Deals with finding savegames.
Definition: fios.h:103
bool _left_button_clicked
Is left mouse button clicked?
Definition: gfx.cpp:39
void SetCurrentThreadName(const char *)
Name the thread this function is called on for the debugger.
Definition: win32.cpp:821
bool AppendPathSeparator(char *buf, const char *last)
Appends, if necessary, the path separator character to the end of the string.
Definition: fileio.cpp:552
Definition: win32.cpp:92
bool LoadLibraryList(Function proc[], const char *dll)
Helper function needed by dynamically loading libraries XXX: Hurray for MS only having an ANSI GetPro...
Definition: win32.cpp:56
bool _left_button_down
Is left mouse button pressed?
Definition: gfx.cpp:38
static const char * _help_msg
Temporary pointer to get the help message to the window.
Definition: win32.cpp:346
static INT_PTR CALLBACK HelpDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
Callback function to handle the window.
Definition: win32.cpp:349
void CDECL usererror(const char *s,...)
Error handling for fatal user errors.
Definition: openttd.cpp:92
char * stredup(const char *s, const char *last)
Create a duplicate of the given string.
Definition: string.cpp:136
bool GetClipboardContents(char *buffer, const char *last)
Try to retrieve the current clipboard contents.
Definition: win32.cpp:511
#define lengthof(x)
Return the length of an fixed size array.
Definition: depend.cpp:40
void DetermineBasePaths(const char *exe)
Determine the base (personal dir and game data dir) paths.
Definition: fileio.cpp:1024
const TCHAR * OTTD2FS(const char *name, bool console_cp)
Convert from OpenTTD&#39;s encoding to that of the local environment.
Definition: win32.cpp:576
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
Search in the personal directory.
Definition: fileio_type.h:137
List of file information.
Definition: fios.h:112
const char * _searchpaths[NUM_SEARCHPATHS]
The search paths OpenTTD could search through.
Definition: fileio.cpp:297
char * strecpy(char *dst, const char *src, const char *last)
Copies characters from one buffer to another.
Definition: depend.cpp:66
Search in the working directory.
Definition: fileio_type.h:133
Search in the installation directory.
Definition: fileio_type.h:140
Search within the application bundle.
Definition: fileio_type.h:141
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: depend.cpp:129
static bool HasBit(const T x, const uint8 y)
Checks if a bit in a value is set.
void ValidateString(const char *str)
Scans the string for valid characters and if it finds invalid ones, replaces them with a question mar...
Definition: string.cpp:243
FiosItem * Append()
Construct a new entry in the file list.
Definition: fios.h:120
declarations of functions for MS windows systems
Search in the shared directory, like &#39;Shared Files&#39; under Windows.
Definition: fileio_type.h:138