00001
00002
00003
00004
00005
00006
00007
00008
00009
00012 #include "../../stdafx.h"
00013 #include "../../debug.h"
00014 #include "../../gfx_func.h"
00015 #include "../../textbuf_gui.h"
00016 #include "../../fileio_func.h"
00017 #include "../../fios.h"
00018 #include <windows.h>
00019 #include <fcntl.h>
00020 #include <shlobj.h>
00021 #include "win32.h"
00022 #include "../../core/alloc_func.hpp"
00023 #include "../../functions.h"
00024 #include "../../core/random_func.hpp"
00025 #include "../../string_func.h"
00026 #include "../../crashlog.h"
00027 #include <errno.h>
00028 #include <sys/stat.h>
00029
00030 static bool _has_console;
00031
00032 static bool cursor_visible = true;
00033
00034 bool MyShowCursor(bool show)
00035 {
00036 if (cursor_visible == show) return show;
00037
00038 cursor_visible = show;
00039 ShowCursor(show);
00040
00041 return !show;
00042 }
00043
00049 bool LoadLibraryList(Function proc[], const char *dll)
00050 {
00051 while (*dll != '\0') {
00052 HMODULE lib;
00053 lib = LoadLibrary(MB_TO_WIDE(dll));
00054
00055 if (lib == NULL) return false;
00056 for (;;) {
00057 FARPROC p;
00058
00059 while (*dll++ != '\0') { }
00060 if (*dll == '\0') break;
00061 #if defined(WINCE)
00062 p = GetProcAddress(lib, MB_TO_WIDE(dll));
00063 #else
00064 p = GetProcAddress(lib, dll);
00065 #endif
00066 if (p == NULL) return false;
00067 *proc++ = (Function)p;
00068 }
00069 dll++;
00070 }
00071 return true;
00072 }
00073
00074 void ShowOSErrorBox(const char *buf, bool system)
00075 {
00076 MyShowCursor(true);
00077 MessageBox(GetActiveWindow(), MB_TO_WIDE(buf), _T("Error!"), MB_ICONSTOP);
00078 }
00079
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089 static DIR _global_dir;
00090 static LONG _global_dir_is_in_use = false;
00091
00092 static inline DIR *dir_calloc()
00093 {
00094 DIR *d;
00095
00096 if (InterlockedExchange(&_global_dir_is_in_use, true) == (LONG)true) {
00097 d = CallocT<DIR>(1);
00098 } else {
00099 d = &_global_dir;
00100 memset(d, 0, sizeof(*d));
00101 }
00102 return d;
00103 }
00104
00105 static inline void dir_free(DIR *d)
00106 {
00107 if (d == &_global_dir) {
00108 _global_dir_is_in_use = (LONG)false;
00109 } else {
00110 free(d);
00111 }
00112 }
00113
00114 DIR *opendir(const TCHAR *path)
00115 {
00116 DIR *d;
00117 UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS);
00118 DWORD fa = GetFileAttributes(path);
00119
00120 if ((fa != INVALID_FILE_ATTRIBUTES) && (fa & FILE_ATTRIBUTE_DIRECTORY)) {
00121 d = dir_calloc();
00122 if (d != NULL) {
00123 TCHAR search_path[MAX_PATH];
00124 bool slash = path[_tcslen(path) - 1] == '\\';
00125
00126
00127
00128 _sntprintf(search_path, lengthof(search_path), _T("%s%s*"), path, slash ? _T("") : _T("\\"));
00129 *lastof(search_path) = '\0';
00130 d->hFind = FindFirstFile(search_path, &d->fd);
00131
00132 if (d->hFind != INVALID_HANDLE_VALUE ||
00133 GetLastError() == ERROR_NO_MORE_FILES) {
00134 d->ent.dir = d;
00135 d->at_first_entry = true;
00136 } else {
00137 dir_free(d);
00138 d = NULL;
00139 }
00140 } else {
00141 errno = ENOMEM;
00142 }
00143 } else {
00144
00145 d = NULL;
00146 errno = ENOENT;
00147 }
00148
00149 SetErrorMode(sem);
00150 return d;
00151 }
00152
00153 struct dirent *readdir(DIR *d)
00154 {
00155 DWORD prev_err = GetLastError();
00156
00157 if (d->at_first_entry) {
00158
00159 if (d->hFind == INVALID_HANDLE_VALUE) return NULL;
00160 d->at_first_entry = false;
00161 } else if (!FindNextFile(d->hFind, &d->fd)) {
00162 if (GetLastError() == ERROR_NO_MORE_FILES) SetLastError(prev_err);
00163 return NULL;
00164 }
00165
00166
00167
00168 d->ent.d_name = d->fd.cFileName;
00169 return &d->ent;
00170 }
00171
00172 int closedir(DIR *d)
00173 {
00174 FindClose(d->hFind);
00175 dir_free(d);
00176 return 0;
00177 }
00178
00179 bool FiosIsRoot(const char *file)
00180 {
00181 return file[3] == '\0';
00182 }
00183
00184 void FiosGetDrives()
00185 {
00186 #if defined(WINCE)
00187
00188 FiosItem *fios = _fios_items.Append();
00189 fios->type = FIOS_TYPE_DRIVE;
00190 fios->mtime = 0;
00191 snprintf(fios->name, lengthof(fios->name), PATHSEP "");
00192 strecpy(fios->title, fios->name, lastof(fios->title));
00193 #else
00194 TCHAR drives[256];
00195 const TCHAR *s;
00196
00197 GetLogicalDriveStrings(lengthof(drives), drives);
00198 for (s = drives; *s != '\0';) {
00199 FiosItem *fios = _fios_items.Append();
00200 fios->type = FIOS_TYPE_DRIVE;
00201 fios->mtime = 0;
00202 snprintf(fios->name, lengthof(fios->name), "%c:", s[0] & 0xFF);
00203 strecpy(fios->title, fios->name, lastof(fios->title));
00204 while (*s++ != '\0') { }
00205 }
00206 #endif
00207 }
00208
00209 bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb)
00210 {
00211
00212 static const int64 posix_epoch_hns = 0x019DB1DED53E8000LL;
00213 const WIN32_FIND_DATA *fd = &ent->dir->fd;
00214
00215 sb->st_size = ((uint64) fd->nFileSizeHigh << 32) + fd->nFileSizeLow;
00216
00217
00218
00219
00220
00221 sb->st_mtime = (time_t)((*(uint64*)&fd->ftLastWriteTime - posix_epoch_hns) / 1E7);
00222 sb->st_mode = (fd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)? S_IFDIR : S_IFREG;
00223
00224 return true;
00225 }
00226
00227 bool FiosIsHiddenFile(const struct dirent *ent)
00228 {
00229 return (ent->dir->fd.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) != 0;
00230 }
00231
00232 bool FiosGetDiskFreeSpace(const char *path, uint64 *tot)
00233 {
00234 UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS);
00235 bool retval = false;
00236 TCHAR root[4];
00237 DWORD spc, bps, nfc, tnc;
00238
00239 _sntprintf(root, lengthof(root), _T("%c:") _T(PATHSEP), path[0]);
00240 if (tot != NULL && GetDiskFreeSpace(root, &spc, &bps, &nfc, &tnc)) {
00241 *tot = ((spc * bps) * (uint64)nfc);
00242 retval = true;
00243 }
00244
00245 SetErrorMode(sem);
00246 return retval;
00247 }
00248
00249 static int ParseCommandLine(char *line, char **argv, int max_argc)
00250 {
00251 int n = 0;
00252
00253 do {
00254
00255 while (*line == ' ' || *line == '\t') line++;
00256
00257
00258 if (*line == '\0') break;
00259
00260
00261 if (*line == '"') {
00262 argv[n++] = ++line;
00263 while (*line != '"') {
00264 if (*line == '\0') return n;
00265 line++;
00266 }
00267 } else {
00268 argv[n++] = line;
00269 while (*line != ' ' && *line != '\t') {
00270 if (*line == '\0') return n;
00271 line++;
00272 }
00273 }
00274 *line++ = '\0';
00275 } while (n != max_argc);
00276
00277 return n;
00278 }
00279
00280 void CreateConsole()
00281 {
00282 #if defined(WINCE)
00283
00284 #else
00285 HANDLE hand;
00286 CONSOLE_SCREEN_BUFFER_INFO coninfo;
00287
00288 if (_has_console) return;
00289 _has_console = true;
00290
00291 AllocConsole();
00292
00293 hand = GetStdHandle(STD_OUTPUT_HANDLE);
00294 GetConsoleScreenBufferInfo(hand, &coninfo);
00295 coninfo.dwSize.Y = 500;
00296 SetConsoleScreenBufferSize(hand, coninfo.dwSize);
00297
00298
00299 #if !defined(__CYGWIN__)
00300 *stdout = *_fdopen( _open_osfhandle((intptr_t)hand, _O_TEXT), "w" );
00301 *stdin = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT), "r" );
00302 *stderr = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT), "w" );
00303 #else
00304
00305 *stdout = *fdopen(1, "w" );
00306 *stdin = *fdopen(0, "r" );
00307 *stderr = *fdopen(2, "w" );
00308 #endif
00309
00310 setvbuf(stdin, NULL, _IONBF, 0);
00311 setvbuf(stdout, NULL, _IONBF, 0);
00312 setvbuf(stderr, NULL, _IONBF, 0);
00313 #endif
00314 }
00315
00317 static const char *_help_msg;
00318
00320 static INT_PTR CALLBACK HelpDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
00321 {
00322 switch (msg) {
00323 case WM_INITDIALOG: {
00324 char help_msg[8192];
00325 const char *p = _help_msg;
00326 char *q = help_msg;
00327 while (q != lastof(help_msg) && *p != '\0') {
00328 if (*p == '\n') {
00329 *q++ = '\r';
00330 if (q == lastof(help_msg)) {
00331 q[-1] = '\0';
00332 break;
00333 }
00334 }
00335 *q++ = *p++;
00336 }
00337 *q = '\0';
00338 #if defined(UNICODE)
00339
00340
00341 wchar_t help_msgW[8192];
00342 #endif
00343 SetDlgItemText(wnd, 11, MB_TO_WIDE_BUFFER(help_msg, help_msgW, lengthof(help_msgW)));
00344 SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE);
00345 } return TRUE;
00346
00347 case WM_COMMAND:
00348 if (wParam == 12) ExitProcess(0);
00349 return TRUE;
00350 case WM_CLOSE:
00351 ExitProcess(0);
00352 }
00353
00354 return FALSE;
00355 }
00356
00357 void ShowInfo(const char *str)
00358 {
00359 if (_has_console) {
00360 fprintf(stderr, "%s\n", str);
00361 } else {
00362 bool old;
00363 ReleaseCapture();
00364 _left_button_clicked = _left_button_down = false;
00365
00366 old = MyShowCursor(true);
00367 if (strlen(str) > 2048) {
00368
00369
00370
00371 _help_msg = str;
00372 DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(101), NULL, HelpDialogFunc);
00373 } else {
00374 #if defined(UNICODE)
00375
00376
00377 wchar_t help_msgW[8192];
00378 #endif
00379 if (MessageBox(GetActiveWindow(), MB_TO_WIDE_BUFFER(str, help_msgW, lengthof(help_msgW)), _T("OpenTTD"), MB_ICONINFORMATION | MB_OKCANCEL) == IDCANCEL) {
00380 CreateConsole();
00381 }
00382 }
00383 MyShowCursor(old);
00384 }
00385 }
00386
00387 #if defined(WINCE)
00388 int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
00389 #else
00390 int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
00391 #endif
00392 {
00393 int argc;
00394 char *argv[64];
00395 char *cmdline;
00396
00397 #if !defined(UNICODE)
00398 _codepage = GetACP();
00399 #endif
00400
00401 CrashLog::InitialiseCrashLog();
00402
00403 #if defined(UNICODE)
00404
00405 #if !defined(WINCE)
00406
00407 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.");
00408 #endif
00409
00410
00411
00412
00413 char cmdlinebuf[MAX_PATH];
00414 #endif
00415
00416 cmdline = WIDE_TO_MB_BUFFER(GetCommandLine(), cmdlinebuf, lengthof(cmdlinebuf));
00417
00418 #if defined(_DEBUG)
00419 CreateConsole();
00420 #endif
00421
00422 #if !defined(WINCE)
00423 _set_error_mode(_OUT_TO_MSGBOX);
00424 #endif
00425
00426
00427 SetRandomSeed(GetTickCount());
00428
00429 argc = ParseCommandLine(cmdline, argv, lengthof(argv));
00430
00431 ttd_main(argc, argv);
00432 return 0;
00433 }
00434
00435 #if defined(WINCE)
00436 void GetCurrentDirectoryW(int length, wchar_t *path)
00437 {
00438
00439 GetModuleFileName(NULL, path, length);
00440
00441
00442 wchar_t *pDest = wcsrchr(path, '\\');
00443 if (pDest != NULL) {
00444 int result = pDest - path + 1;
00445 path[result] = '\0';
00446 }
00447 }
00448 #endif
00449
00450 char *getcwd(char *buf, size_t size)
00451 {
00452 #if defined(WINCE)
00453 TCHAR path[MAX_PATH];
00454 GetModuleFileName(NULL, path, MAX_PATH);
00455 convert_from_fs(path, buf, size);
00456
00457 char *p = strrchr(buf, '\\');
00458 if (p != NULL) *p = '\0';
00459 #elif defined(UNICODE)
00460 TCHAR path[MAX_PATH];
00461 GetCurrentDirectory(MAX_PATH - 1, path);
00462 convert_from_fs(path, buf, size);
00463 #else
00464 GetCurrentDirectory(size, buf);
00465 #endif
00466 return buf;
00467 }
00468
00469
00470 void DetermineBasePaths(const char *exe)
00471 {
00472 char tmp[MAX_PATH];
00473 TCHAR path[MAX_PATH];
00474 #ifdef WITH_PERSONAL_DIR
00475 SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, path);
00476 strecpy(tmp, WIDE_TO_MB_BUFFER(path, tmp, lengthof(tmp)), lastof(tmp));
00477 AppendPathSeparator(tmp, MAX_PATH);
00478 ttd_strlcat(tmp, PERSONAL_DIR, MAX_PATH);
00479 AppendPathSeparator(tmp, MAX_PATH);
00480 _searchpaths[SP_PERSONAL_DIR] = strdup(tmp);
00481
00482 SHGetFolderPath(NULL, CSIDL_COMMON_DOCUMENTS, NULL, SHGFP_TYPE_CURRENT, path);
00483 strecpy(tmp, WIDE_TO_MB_BUFFER(path, tmp, lengthof(tmp)), lastof(tmp));
00484 AppendPathSeparator(tmp, MAX_PATH);
00485 ttd_strlcat(tmp, PERSONAL_DIR, MAX_PATH);
00486 AppendPathSeparator(tmp, MAX_PATH);
00487 _searchpaths[SP_SHARED_DIR] = strdup(tmp);
00488 #else
00489 _searchpaths[SP_PERSONAL_DIR] = NULL;
00490 _searchpaths[SP_SHARED_DIR] = NULL;
00491 #endif
00492
00493
00494 getcwd(tmp, lengthof(tmp));
00495 AppendPathSeparator(tmp, MAX_PATH);
00496 _searchpaths[SP_WORKING_DIR] = strdup(tmp);
00497
00498 if (!GetModuleFileName(NULL, path, lengthof(path))) {
00499 DEBUG(misc, 0, "GetModuleFileName failed (%lu)\n", GetLastError());
00500 _searchpaths[SP_BINARY_DIR] = NULL;
00501 } else {
00502 TCHAR exec_dir[MAX_PATH];
00503 _tcsncpy(path, MB_TO_WIDE_BUFFER(exe, path, lengthof(path)), lengthof(path));
00504 if (!GetFullPathName(path, lengthof(exec_dir), exec_dir, NULL)) {
00505 DEBUG(misc, 0, "GetFullPathName failed (%lu)\n", GetLastError());
00506 _searchpaths[SP_BINARY_DIR] = NULL;
00507 } else {
00508 strecpy(tmp, WIDE_TO_MB_BUFFER(exec_dir, tmp, lengthof(tmp)), lastof(tmp));
00509 char *s = strrchr(tmp, PATHSEPCHAR);
00510 *(s + 1) = '\0';
00511 _searchpaths[SP_BINARY_DIR] = strdup(tmp);
00512 }
00513 }
00514
00515 _searchpaths[SP_INSTALLATION_DIR] = NULL;
00516 _searchpaths[SP_APPLICATION_BUNDLE_DIR] = NULL;
00517 }
00518
00519
00520 bool GetClipboardContents(char *buffer, size_t buff_len)
00521 {
00522 HGLOBAL cbuf;
00523 const char *ptr;
00524
00525 if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
00526 OpenClipboard(NULL);
00527 cbuf = GetClipboardData(CF_UNICODETEXT);
00528
00529 ptr = (const char*)GlobalLock(cbuf);
00530 const char *ret = convert_from_fs((wchar_t*)ptr, buffer, buff_len);
00531 GlobalUnlock(cbuf);
00532 CloseClipboard();
00533
00534 if (*ret == '\0') return false;
00535 #if !defined(UNICODE)
00536 } else if (IsClipboardFormatAvailable(CF_TEXT)) {
00537 OpenClipboard(NULL);
00538 cbuf = GetClipboardData(CF_TEXT);
00539
00540 ptr = (const char*)GlobalLock(cbuf);
00541 ttd_strlcpy(buffer, FS2OTTD(ptr), buff_len);
00542
00543 GlobalUnlock(cbuf);
00544 CloseClipboard();
00545 #endif
00546 } else {
00547 return false;
00548 }
00549
00550 return true;
00551 }
00552
00553
00554 void CSleep(int milliseconds)
00555 {
00556 Sleep(milliseconds);
00557 }
00558
00559
00573 const char *FS2OTTD(const TCHAR *name)
00574 {
00575 static char utf8_buf[512];
00576 #if defined(UNICODE)
00577 return convert_from_fs(name, utf8_buf, lengthof(utf8_buf));
00578 #else
00579 char *s = utf8_buf;
00580
00581 for (; *name != '\0'; name++) {
00582 wchar_t w;
00583 int len = MultiByteToWideChar(_codepage, 0, name, 1, &w, 1);
00584 if (len != 1) {
00585 DEBUG(misc, 0, "[utf8] M2W error converting '%c'. Errno %lu", *name, GetLastError());
00586 continue;
00587 }
00588
00589 if (s + Utf8CharLen(w) >= lastof(utf8_buf)) break;
00590 s += Utf8Encode(s, w);
00591 }
00592
00593 *s = '\0';
00594 return utf8_buf;
00595 #endif
00596 }
00597
00611 const TCHAR *OTTD2FS(const char *name)
00612 {
00613 static TCHAR system_buf[512];
00614 #if defined(UNICODE)
00615 return convert_to_fs(name, system_buf, lengthof(system_buf));
00616 #else
00617 char *s = system_buf;
00618
00619 for (WChar c; (c = Utf8Consume(&name)) != '\0';) {
00620 if (s >= lastof(system_buf)) break;
00621
00622 char mb;
00623 int len = WideCharToMultiByte(_codepage, 0, (wchar_t*)&c, 1, &mb, 1, NULL, NULL);
00624 if (len != 1) {
00625 DEBUG(misc, 0, "[utf8] W2M error converting '0x%X'. Errno %lu", c, GetLastError());
00626 continue;
00627 }
00628
00629 *s++ = mb;
00630 }
00631
00632 *s = '\0';
00633 return system_buf;
00634 #endif
00635 }
00636
00637
00646 char *convert_from_fs(const wchar_t *name, char *utf8_buf, size_t buflen)
00647 {
00648 int len = WideCharToMultiByte(CP_UTF8, 0, name, -1, utf8_buf, (int)buflen, NULL, NULL);
00649 if (len == 0) {
00650 DEBUG(misc, 0, "[utf8] W2M error converting wide-string. Errno %lu", GetLastError());
00651 utf8_buf[0] = '\0';
00652 }
00653
00654 return utf8_buf;
00655 }
00656
00657
00667 wchar_t *convert_to_fs(const char *name, wchar_t *utf16_buf, size_t buflen)
00668 {
00669 int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, utf16_buf, (int)buflen);
00670 if (len == 0) {
00671 DEBUG(misc, 0, "[utf8] M2W error converting '%s'. Errno %lu", name, GetLastError());
00672 utf16_buf[0] = '\0';
00673 }
00674
00675 return utf16_buf;
00676 }
00677
00684 HRESULT OTTDSHGetFolderPath(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPTSTR pszPath)
00685 {
00686 static HRESULT (WINAPI *SHGetFolderPath)(HWND, int, HANDLE, DWORD, LPTSTR) = NULL;
00687 static bool first_time = true;
00688
00689
00690 if (first_time) {
00691 #if defined(UNICODE)
00692 # define W(x) x "W"
00693 #else
00694 # define W(x) x "A"
00695 #endif
00696 if (!LoadLibraryList((Function*)&SHGetFolderPath, "SHFolder.dll\0" W("SHGetFolderPath") "\0\0")) {
00697 DEBUG(misc, 0, "Unable to load " W("SHGetFolderPath") "from SHFolder.dll");
00698 }
00699 #undef W
00700 first_time = false;
00701 }
00702
00703 if (SHGetFolderPath != NULL) return SHGetFolderPath(hwnd, csidl, hToken, dwFlags, pszPath);
00704
00705
00706
00707
00708
00709
00710
00711
00712 {
00713 DWORD ret;
00714 switch (csidl) {
00715 case CSIDL_FONTS:
00716 ret = GetEnvironmentVariable(_T("WINDIR"), pszPath, MAX_PATH);
00717 if (ret == 0) break;
00718 _tcsncat(pszPath, _T("\\Fonts"), MAX_PATH);
00719
00720 return (HRESULT)0;
00721
00722
00723 }
00724 }
00725
00726 return E_INVALIDARG;
00727 }
00728
00730 const char *GetCurrentLocale(const char *)
00731 {
00732 char lang[9], country[9];
00733 if (GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, lang, lengthof(lang)) == 0 ||
00734 GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, country, lengthof(country)) == 0) {
00735
00736 return NULL;
00737 }
00738
00739 static char retbuf[6] = {lang[0], lang[1], '_', country[0], country[1], 0};
00740 return retbuf;
00741 }