|
1 /* $Id$ */ |
|
2 |
|
3 #include "stdafx.h" |
|
4 #include "openttd.h" |
|
5 #include "debug.h" |
|
6 #include "functions.h" |
|
7 #include "macros.h" |
|
8 #include "saveload.h" |
|
9 #include "string.h" |
|
10 #include "gfx.h" |
|
11 #include "window.h" |
|
12 #include <windows.h> |
|
13 #include <winnt.h> |
|
14 #include <wininet.h> |
|
15 #include <io.h> |
|
16 #include <fcntl.h> |
|
17 #include <shlobj.h> // SHGetFolderPath |
|
18 #include "variables.h" |
|
19 #include "win32.h" |
|
20 #include "fios.h" // opendir/readdir/closedir |
|
21 #include <ctype.h> |
|
22 #include <tchar.h> |
|
23 #include <errno.h> |
|
24 #include <sys/types.h> |
|
25 #include <sys/stat.h> |
|
26 |
|
27 static bool _has_console; |
|
28 |
|
29 #if defined(__MINGW32__) |
|
30 #include <stdint.h> |
|
31 #endif |
|
32 |
|
33 static bool cursor_visible = true; |
|
34 |
|
35 bool MyShowCursor(bool show) |
|
36 { |
|
37 if (cursor_visible == show) return show; |
|
38 |
|
39 cursor_visible = show; |
|
40 ShowCursor(show); |
|
41 |
|
42 return !show; |
|
43 } |
|
44 |
|
45 /** Helper function needed by dynamically loading libraries |
|
46 * XXX: Hurray for MS only having an ANSI GetProcAddress function |
|
47 * on normal windows and no Wide version except for in Windows Mobile/CE */ |
|
48 bool LoadLibraryList(Function proc[], const char *dll) |
|
49 { |
|
50 while (*dll != '\0') { |
|
51 HMODULE lib; |
|
52 lib = LoadLibrary(MB_TO_WIDE(dll)); |
|
53 |
|
54 if (lib == NULL) return false; |
|
55 for (;;) { |
|
56 FARPROC p; |
|
57 |
|
58 while (*dll++ != '\0'); |
|
59 if (*dll == '\0') break; |
|
60 #if defined(WINCE) |
|
61 p = GetProcAddress(lib, MB_TO_WIDE(dll); |
|
62 #else |
|
63 p = GetProcAddress(lib, dll); |
|
64 #endif |
|
65 if (p == NULL) return false; |
|
66 *proc++ = (Function)p; |
|
67 } |
|
68 dll++; |
|
69 } |
|
70 return true; |
|
71 } |
|
72 |
|
73 #ifdef _MSC_VER |
|
74 static const char *_exception_string = NULL; |
|
75 #endif |
|
76 |
|
77 void ShowOSErrorBox(const char *buf) |
|
78 { |
|
79 MyShowCursor(true); |
|
80 MessageBox(GetActiveWindow(), MB_TO_WIDE(buf), _T("Error!"), MB_ICONSTOP); |
|
81 |
|
82 // if exception tracker is enabled, we crash here to let the exception handler handle it. |
|
83 #if defined(WIN32_EXCEPTION_TRACKER) && !defined(_DEBUG) |
|
84 if (*buf == '!') { |
|
85 _exception_string = buf; |
|
86 *(byte*)0 = 0; |
|
87 } |
|
88 #endif |
|
89 } |
|
90 |
|
91 #ifdef _MSC_VER |
|
92 |
|
93 static void *_safe_esp; |
|
94 static char *_crash_msg; |
|
95 static bool _expanded; |
|
96 static bool _did_emerg_save; |
|
97 static int _ident; |
|
98 |
|
99 typedef struct DebugFileInfo { |
|
100 uint32 size; |
|
101 uint32 crc32; |
|
102 SYSTEMTIME file_time; |
|
103 } DebugFileInfo; |
|
104 |
|
105 static uint32 *_crc_table; |
|
106 |
|
107 static void MakeCRCTable(uint32 *table) { |
|
108 uint32 crc, poly = 0xEDB88320L; |
|
109 int i; |
|
110 int j; |
|
111 |
|
112 _crc_table = table; |
|
113 |
|
114 for (i = 0; i != 256; i++) { |
|
115 crc = i; |
|
116 for (j = 8; j != 0; j--) { |
|
117 crc = (crc & 1 ? (crc >> 1) ^ poly : crc >> 1); |
|
118 } |
|
119 table[i] = crc; |
|
120 } |
|
121 } |
|
122 |
|
123 static uint32 CalcCRC(byte *data, uint size, uint32 crc) { |
|
124 for (; size > 0; size--) { |
|
125 crc = ((crc >> 8) & 0x00FFFFFF) ^ _crc_table[(crc ^ *data++) & 0xFF]; |
|
126 } |
|
127 return crc; |
|
128 } |
|
129 |
|
130 static void GetFileInfo(DebugFileInfo *dfi, const TCHAR *filename) |
|
131 { |
|
132 HANDLE file; |
|
133 memset(dfi, 0, sizeof(dfi)); |
|
134 |
|
135 file = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0); |
|
136 if (file != INVALID_HANDLE_VALUE) { |
|
137 byte buffer[1024]; |
|
138 DWORD numread; |
|
139 uint32 filesize = 0; |
|
140 FILETIME write_time; |
|
141 uint32 crc = (uint32)-1; |
|
142 |
|
143 for (;;) { |
|
144 if (ReadFile(file, buffer, sizeof(buffer), &numread, NULL) == 0 || numread == 0) |
|
145 break; |
|
146 filesize += numread; |
|
147 crc = CalcCRC(buffer, numread, crc); |
|
148 } |
|
149 dfi->size = filesize; |
|
150 dfi->crc32 = crc ^ (uint32)-1; |
|
151 |
|
152 if (GetFileTime(file, NULL, NULL, &write_time)) { |
|
153 FileTimeToSystemTime(&write_time, &dfi->file_time); |
|
154 } |
|
155 CloseHandle(file); |
|
156 } |
|
157 } |
|
158 |
|
159 |
|
160 static char *PrintModuleInfo(char *output, HMODULE mod) |
|
161 { |
|
162 TCHAR buffer[MAX_PATH]; |
|
163 DebugFileInfo dfi; |
|
164 |
|
165 GetModuleFileName(mod, buffer, MAX_PATH); |
|
166 GetFileInfo(&dfi, buffer); |
|
167 output += sprintf(output, " %-20s handle: %p size: %d crc: %.8X date: %d-%.2d-%.2d %.2d:%.2d:%.2d\r\n", |
|
168 WIDE_TO_MB(buffer), |
|
169 mod, |
|
170 dfi.size, |
|
171 dfi.crc32, |
|
172 dfi.file_time.wYear, |
|
173 dfi.file_time.wMonth, |
|
174 dfi.file_time.wDay, |
|
175 dfi.file_time.wHour, |
|
176 dfi.file_time.wMinute, |
|
177 dfi.file_time.wSecond |
|
178 ); |
|
179 return output; |
|
180 } |
|
181 |
|
182 static char *PrintModuleList(char *output) |
|
183 { |
|
184 BOOL (WINAPI *EnumProcessModules)(HANDLE, HMODULE*, DWORD, LPDWORD); |
|
185 |
|
186 if (LoadLibraryList((Function*)&EnumProcessModules, "psapi.dll\0EnumProcessModules\0\0")) { |
|
187 HMODULE modules[100]; |
|
188 DWORD needed; |
|
189 BOOL res; |
|
190 int count, i; |
|
191 |
|
192 HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId()); |
|
193 if (proc != NULL) { |
|
194 res = EnumProcessModules(proc, modules, sizeof(modules), &needed); |
|
195 CloseHandle(proc); |
|
196 if (res) { |
|
197 count = min(needed / sizeof(HMODULE), lengthof(modules)); |
|
198 |
|
199 for (i = 0; i != count; i++) output = PrintModuleInfo(output, modules[i]); |
|
200 return output; |
|
201 } |
|
202 } |
|
203 } |
|
204 output = PrintModuleInfo(output, NULL); |
|
205 return output; |
|
206 } |
|
207 |
|
208 static const TCHAR _crash_desc[] = |
|
209 _T("A serious fault condition occured in the game. The game will shut down.\n") |
|
210 _T("Please send the crash information and the crash.dmp file (if any) to the developers.\n") |
|
211 _T("This will greatly help debugging. The correct place to do this is http://bugs.openttd.org. ") |
|
212 _T("The information contained in the report is displayed below.\n") |
|
213 _T("Press \"Emergency save\" to attempt saving the game."); |
|
214 |
|
215 static const TCHAR _save_succeeded[] = |
|
216 _T("Emergency save succeeded.\n") |
|
217 _T("Be aware that critical parts of the internal game state may have become ") |
|
218 _T("corrupted. The saved game is not guaranteed to work."); |
|
219 |
|
220 static bool EmergencySave(void) |
|
221 { |
|
222 SaveOrLoad("crash.sav", SL_SAVE); |
|
223 return true; |
|
224 } |
|
225 |
|
226 /* Disable the crash-save submit code as it's not used */ |
|
227 #if 0 |
|
228 |
|
229 typedef struct { |
|
230 HINTERNET (WINAPI *InternetOpen)(LPCTSTR,DWORD, LPCTSTR, LPCTSTR, DWORD); |
|
231 HINTERNET (WINAPI *InternetConnect)(HINTERNET, LPCTSTR, INTERNET_PORT, LPCTSTR, LPCTSTR, DWORD, DWORD, DWORD); |
|
232 HINTERNET (WINAPI *HttpOpenRequest)(HINTERNET, LPCTSTR, LPCTSTR, LPCTSTR, LPCTSTR, LPCTSTR *, DWORD, DWORD); |
|
233 BOOL (WINAPI *HttpSendRequest)(HINTERNET, LPCTSTR, DWORD, LPVOID, DWORD); |
|
234 BOOL (WINAPI *InternetCloseHandle)(HINTERNET); |
|
235 BOOL (WINAPI *HttpQueryInfo)(HINTERNET, DWORD, LPVOID, LPDWORD, LPDWORD); |
|
236 } WinInetProcs; |
|
237 |
|
238 #define M(x) x "\0" |
|
239 #if defined(UNICODE) |
|
240 # define W(x) x "W" |
|
241 #else |
|
242 # define W(x) x "A" |
|
243 #endif |
|
244 static const char wininet_files[] = |
|
245 M("wininet.dll") |
|
246 M(W("InternetOpen")) |
|
247 M(W("InternetConnect")) |
|
248 M(W("HttpOpenRequest")) |
|
249 M(W("HttpSendRequest")) |
|
250 M("InternetCloseHandle") |
|
251 M(W("HttpQueryInfo")) |
|
252 M(""); |
|
253 #undef W |
|
254 #undef M |
|
255 |
|
256 static WinInetProcs _wininet; |
|
257 |
|
258 static const TCHAR *SubmitCrashReport(HWND wnd, void *msg, size_t msglen, const TCHAR *arg) |
|
259 { |
|
260 HINTERNET inet, conn, http; |
|
261 const TCHAR *err = NULL; |
|
262 DWORD code, len; |
|
263 static TCHAR buf[100]; |
|
264 TCHAR buff[100]; |
|
265 |
|
266 if (_wininet.InternetOpen == NULL && !LoadLibraryList((Function*)&_wininet, wininet_files)) return _T("can't load wininet.dll"); |
|
267 |
|
268 inet = _wininet.InternetOpen(_T("OTTD"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 ); |
|
269 if (inet == NULL) { err = _T("internetopen failed"); goto error1; } |
|
270 |
|
271 conn = _wininet.InternetConnect(inet, _T("www.openttd.org"), INTERNET_DEFAULT_HTTP_PORT, _T(""), _T(""), INTERNET_SERVICE_HTTP, 0, 0); |
|
272 if (conn == NULL) { err = _T("internetconnect failed"); goto error2; } |
|
273 |
|
274 _sntprintf(buff, lengthof(buff), _T("/crash.php?file=%s&ident=%d"), arg, _ident); |
|
275 |
|
276 http = _wininet.HttpOpenRequest(conn, _T("POST"), buff, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE , 0); |
|
277 if (http == NULL) { err = _T("httpopenrequest failed"); goto error3; } |
|
278 |
|
279 if (!_wininet.HttpSendRequest(http, _T("Content-type: application/binary"), -1, msg, (DWORD)msglen)) { err = _T("httpsendrequest failed"); goto error4; } |
|
280 |
|
281 len = sizeof(code); |
|
282 if (!_wininet.HttpQueryInfo(http, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &code, &len, 0)) { err = _T("httpqueryinfo failed"); goto error4; } |
|
283 |
|
284 if (code != 200) { |
|
285 int l = _sntprintf(buf, lengthof(buf), _T("Server said: %d "), code); |
|
286 len = sizeof(buf) - l; |
|
287 _wininet.HttpQueryInfo(http, HTTP_QUERY_STATUS_TEXT, buf + l, &len, 0); |
|
288 err = buf; |
|
289 } |
|
290 |
|
291 error4: |
|
292 _wininet.InternetCloseHandle(http); |
|
293 error3: |
|
294 _wininet.InternetCloseHandle(conn); |
|
295 error2: |
|
296 _wininet.InternetCloseHandle(inet); |
|
297 error1: |
|
298 return err; |
|
299 } |
|
300 |
|
301 static void SubmitFile(HWND wnd, const TCHAR *file) |
|
302 { |
|
303 HANDLE h; |
|
304 unsigned long size; |
|
305 unsigned long read; |
|
306 void *mem; |
|
307 |
|
308 h = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); |
|
309 if (h == NULL) return; |
|
310 |
|
311 size = GetFileSize(h, NULL); |
|
312 if (size > 500000) goto error1; |
|
313 |
|
314 mem = malloc(size); |
|
315 if (mem == NULL) goto error1; |
|
316 |
|
317 if (!ReadFile(h, mem, size, &read, NULL) || read != size) goto error2; |
|
318 |
|
319 SubmitCrashReport(wnd, mem, size, file); |
|
320 |
|
321 error2: |
|
322 free(mem); |
|
323 error1: |
|
324 CloseHandle(h); |
|
325 } |
|
326 |
|
327 #endif /* Disabled crash-submit procedures */ |
|
328 |
|
329 static const TCHAR * const _expand_texts[] = {_T("S&how report >>"), _T("&Hide report <<") }; |
|
330 |
|
331 static void SetWndSize(HWND wnd, int mode) |
|
332 { |
|
333 RECT r,r2; |
|
334 int offs; |
|
335 |
|
336 GetWindowRect(wnd, &r); |
|
337 |
|
338 SetDlgItemText(wnd, 15, _expand_texts[mode == 1]); |
|
339 |
|
340 if (mode >= 0) { |
|
341 GetWindowRect(GetDlgItem(wnd, 11), &r2); |
|
342 offs = r2.bottom - r2.top + 10; |
|
343 if (!mode) offs = -offs; |
|
344 SetWindowPos(wnd, HWND_TOPMOST, 0, 0, |
|
345 r.right - r.left, r.bottom - r.top + offs, SWP_NOMOVE | SWP_NOZORDER); |
|
346 } else { |
|
347 SetWindowPos(wnd, HWND_TOPMOST, |
|
348 (GetSystemMetrics(SM_CXSCREEN) - (r.right - r.left)) / 2, |
|
349 (GetSystemMetrics(SM_CYSCREEN) - (r.bottom - r.top)) / 2, |
|
350 0, 0, SWP_NOSIZE); |
|
351 } |
|
352 } |
|
353 |
|
354 static bool DoEmergencySave(HWND wnd) |
|
355 { |
|
356 bool b = false; |
|
357 |
|
358 EnableWindow(GetDlgItem(wnd, 13), FALSE); |
|
359 _did_emerg_save = true; |
|
360 __try { |
|
361 b = EmergencySave(); |
|
362 } __except (1) {} |
|
363 return b; |
|
364 } |
|
365 |
|
366 static INT_PTR CALLBACK CrashDialogFunc(HWND wnd,UINT msg,WPARAM wParam,LPARAM lParam) |
|
367 { |
|
368 switch (msg) { |
|
369 case WM_INITDIALOG: { |
|
370 #if defined(UNICODE) |
|
371 /* We need to put the crash-log in a seperate buffer because the default |
|
372 * buffer in MB_TO_WIDE is not large enough (256 chars) */ |
|
373 wchar_t crash_msgW[8096]; |
|
374 #endif |
|
375 SetDlgItemText(wnd, 10, _crash_desc); |
|
376 SetDlgItemText(wnd, 11, MB_TO_WIDE_BUFFER(_crash_msg, crash_msgW, lengthof(crash_msgW))); |
|
377 SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE); |
|
378 SetWndSize(wnd, -1); |
|
379 } return TRUE; |
|
380 case WM_COMMAND: |
|
381 switch (wParam) { |
|
382 case 12: /* Close */ |
|
383 ExitProcess(0); |
|
384 case 13: /* Emergency save */ |
|
385 if (DoEmergencySave(wnd)) { |
|
386 MessageBox(wnd, _save_succeeded, _T("Save successful"), MB_ICONINFORMATION); |
|
387 } else { |
|
388 MessageBox(wnd, _T("Save failed"), _T("Save failed"), MB_ICONINFORMATION); |
|
389 } |
|
390 break; |
|
391 /* Disable the crash-save submit code as it's not used */ |
|
392 #if 0 |
|
393 case 14: { /* Submit crash report */ |
|
394 const TCHAR *s; |
|
395 |
|
396 SetCursor(LoadCursor(NULL, IDC_WAIT)); |
|
397 |
|
398 s = SubmitCrashReport(wnd, _crash_msg, strlen(_crash_msg), _T("")); |
|
399 if (s != NULL) { |
|
400 MessageBox(wnd, s, _T("Error"), MB_ICONSTOP); |
|
401 break; |
|
402 } |
|
403 |
|
404 // try to submit emergency savegame |
|
405 if (_did_emerg_save || DoEmergencySave(wnd)) SubmitFile(wnd, _T("crash.sav")); |
|
406 |
|
407 // try to submit the autosaved game |
|
408 if (_opt.autosave) { |
|
409 TCHAR buf[40]; |
|
410 _sntprintf(buf, lengthof(buf), _T("autosave%d.sav"), (_autosave_ctr - 1) & 3); |
|
411 SubmitFile(wnd, buf); |
|
412 } |
|
413 EnableWindow(GetDlgItem(wnd, 14), FALSE); |
|
414 SetCursor(LoadCursor(NULL, IDC_ARROW)); |
|
415 MessageBox(wnd, _T("Crash report submitted. Thank you."), _T("Crash Report"), MB_ICONINFORMATION); |
|
416 } break; |
|
417 #endif /* Disabled crash-submit procedures */ |
|
418 case 15: /* Expand window to show crash-message */ |
|
419 _expanded ^= 1; |
|
420 SetWndSize(wnd, _expanded); |
|
421 break; |
|
422 } |
|
423 return TRUE; |
|
424 case WM_CLOSE: ExitProcess(0); |
|
425 } |
|
426 |
|
427 return FALSE; |
|
428 } |
|
429 |
|
430 static void Handler2(void) |
|
431 { |
|
432 ShowCursor(TRUE); |
|
433 ShowWindow(GetActiveWindow(), FALSE); |
|
434 DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(100), NULL, CrashDialogFunc); |
|
435 } |
|
436 |
|
437 extern bool CloseConsoleLogIfActive(void); |
|
438 |
|
439 static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep) |
|
440 { |
|
441 extern const char _openttd_revision[]; |
|
442 char *output; |
|
443 static bool had_exception = false; |
|
444 |
|
445 if (had_exception) ExitProcess(0); |
|
446 had_exception = true; |
|
447 |
|
448 _ident = GetTickCount(); // something pretty unique |
|
449 |
|
450 MakeCRCTable(alloca(256 * sizeof(uint32))); |
|
451 _crash_msg = output = LocalAlloc(LMEM_FIXED, 8192); |
|
452 |
|
453 { |
|
454 SYSTEMTIME time; |
|
455 GetLocalTime(&time); |
|
456 output += sprintf(output, |
|
457 "*** OpenTTD Crash Report ***\r\n" |
|
458 "Date: %d-%.2d-%.2d %.2d:%.2d:%.2d\r\n" |
|
459 "Build: %s built on " __DATE__ " " __TIME__ "\r\n", |
|
460 time.wYear, |
|
461 time.wMonth, |
|
462 time.wDay, |
|
463 time.wHour, |
|
464 time.wMinute, |
|
465 time.wSecond, |
|
466 _openttd_revision |
|
467 ); |
|
468 } |
|
469 |
|
470 if (_exception_string) |
|
471 output += sprintf(output, "Reason: %s\r\n", _exception_string); |
|
472 |
|
473 #ifdef _M_AMD64 |
|
474 output += sprintf(output, "Exception %.8X at %.16IX\r\n" |
|
475 "Registers:\r\n" |
|
476 "RAX: %.16llX RBX: %.16llX RCX: %.16llX RDX: %.16llX\r\n" |
|
477 "RSI: %.16llX RDI: %.16llX RBP: %.16llX RSP: %.16llX\r\n" |
|
478 "R8: %.16llX R9: %.16llX R10: %.16llX R11: %.16llX\r\n" |
|
479 "R12: %.16llX R13: %.16llX R14: %.16llX R15: %.16llX\r\n" |
|
480 "RIP: %.16llX EFLAGS: %.8X\r\n" |
|
481 "\r\nBytes at CS:RIP:\r\n", |
|
482 ep->ExceptionRecord->ExceptionCode, |
|
483 ep->ExceptionRecord->ExceptionAddress, |
|
484 ep->ContextRecord->Rax, |
|
485 ep->ContextRecord->Rbx, |
|
486 ep->ContextRecord->Rcx, |
|
487 ep->ContextRecord->Rdx, |
|
488 ep->ContextRecord->Rsi, |
|
489 ep->ContextRecord->Rdi, |
|
490 ep->ContextRecord->Rbp, |
|
491 ep->ContextRecord->Rsp, |
|
492 ep->ContextRecord->R8, |
|
493 ep->ContextRecord->R9, |
|
494 ep->ContextRecord->R10, |
|
495 ep->ContextRecord->R11, |
|
496 ep->ContextRecord->R12, |
|
497 ep->ContextRecord->R13, |
|
498 ep->ContextRecord->R14, |
|
499 ep->ContextRecord->R15, |
|
500 ep->ContextRecord->Rip, |
|
501 ep->ContextRecord->EFlags |
|
502 ); |
|
503 #else |
|
504 output += sprintf(output, "Exception %.8X at %.8X\r\n" |
|
505 "Registers:\r\n" |
|
506 " EAX: %.8X EBX: %.8X ECX: %.8X EDX: %.8X\r\n" |
|
507 " ESI: %.8X EDI: %.8X EBP: %.8X ESP: %.8X\r\n" |
|
508 " EIP: %.8X EFLAGS: %.8X\r\n" |
|
509 "\r\nBytes at CS:EIP:\r\n", |
|
510 ep->ExceptionRecord->ExceptionCode, |
|
511 ep->ExceptionRecord->ExceptionAddress, |
|
512 ep->ContextRecord->Eax, |
|
513 ep->ContextRecord->Ebx, |
|
514 ep->ContextRecord->Ecx, |
|
515 ep->ContextRecord->Edx, |
|
516 ep->ContextRecord->Esi, |
|
517 ep->ContextRecord->Edi, |
|
518 ep->ContextRecord->Ebp, |
|
519 ep->ContextRecord->Esp, |
|
520 ep->ContextRecord->Eip, |
|
521 ep->ContextRecord->EFlags |
|
522 ); |
|
523 #endif |
|
524 |
|
525 { |
|
526 #ifdef _M_AMD64 |
|
527 byte *b = (byte*)ep->ContextRecord->Rip; |
|
528 #else |
|
529 byte *b = (byte*)ep->ContextRecord->Eip; |
|
530 #endif |
|
531 int i; |
|
532 for (i = 0; i != 24; i++) { |
|
533 if (IsBadReadPtr(b, 1)) { |
|
534 output += sprintf(output, " ??"); // OCR: WAS: , 0); |
|
535 } else { |
|
536 output += sprintf(output, " %.2X", *b); |
|
537 } |
|
538 b++; |
|
539 } |
|
540 output += sprintf(output, |
|
541 "\r\n" |
|
542 "\r\nStack trace: \r\n" |
|
543 ); |
|
544 } |
|
545 |
|
546 { |
|
547 int i,j; |
|
548 #ifdef _M_AMD64 |
|
549 uint32 *b = (uint32*)ep->ContextRecord->Rsp; |
|
550 #else |
|
551 uint32 *b = (uint32*)ep->ContextRecord->Esp; |
|
552 #endif |
|
553 for (j = 0; j != 24; j++) { |
|
554 for (i = 0; i != 8; i++) { |
|
555 if (IsBadReadPtr(b,sizeof(uint32))) { |
|
556 output += sprintf(output, " ????????"); //OCR: WAS - , 0); |
|
557 } else { |
|
558 output += sprintf(output, " %.8X", *b); |
|
559 } |
|
560 b++; |
|
561 } |
|
562 output += sprintf(output, "\r\n"); |
|
563 } |
|
564 } |
|
565 |
|
566 output += sprintf(output, "\r\nModule information:\r\n"); |
|
567 output = PrintModuleList(output); |
|
568 |
|
569 { |
|
570 OSVERSIONINFO os; |
|
571 os.dwOSVersionInfoSize = sizeof(os); |
|
572 GetVersionEx(&os); |
|
573 output += sprintf(output, "\r\nSystem information:\r\n" |
|
574 " Windows version %d.%d %d %s\r\n", |
|
575 os.dwMajorVersion, os.dwMinorVersion, os.dwBuildNumber, os.szCSDVersion); |
|
576 } |
|
577 |
|
578 { |
|
579 HANDLE file = CreateFile(_T("crash.log"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0); |
|
580 DWORD num_written; |
|
581 if (file != INVALID_HANDLE_VALUE) { |
|
582 WriteFile(file, _crash_msg, output - _crash_msg, &num_written, NULL); |
|
583 CloseHandle(file); |
|
584 } |
|
585 } |
|
586 |
|
587 /* Close any possible log files */ |
|
588 CloseConsoleLogIfActive(); |
|
589 |
|
590 if (_safe_esp) { |
|
591 #ifdef _M_AMD64 |
|
592 ep->ContextRecord->Rip = (DWORD64)Handler2; |
|
593 ep->ContextRecord->Rsp = (DWORD64)_safe_esp; |
|
594 #else |
|
595 ep->ContextRecord->Eip = (DWORD)Handler2; |
|
596 ep->ContextRecord->Esp = (DWORD)_safe_esp; |
|
597 #endif |
|
598 return EXCEPTION_CONTINUE_EXECUTION; |
|
599 } |
|
600 |
|
601 |
|
602 return EXCEPTION_EXECUTE_HANDLER; |
|
603 } |
|
604 |
|
605 static void Win32InitializeExceptions(void) |
|
606 { |
|
607 #ifdef _M_AMD64 |
|
608 extern void *_get_save_esp(void); |
|
609 _safe_esp = _get_save_esp(); |
|
610 #else |
|
611 _asm { |
|
612 mov _safe_esp, esp |
|
613 } |
|
614 #endif |
|
615 |
|
616 SetUnhandledExceptionFilter(ExceptionHandler); |
|
617 } |
|
618 #endif /* _MSC_VER */ |
|
619 |
|
620 /* Code below for windows version of opendir/readdir/closedir copied and |
|
621 * modified from Jan Wassenberg's GPL implementation posted over at |
|
622 * http://www.gamedev.net/community/forums/topic.asp?topic_id=364584&whichpage=1� */ |
|
623 |
|
624 /* suballocator - satisfies most requests with a reusable static instance. |
|
625 * this avoids hundreds of alloc/free which would fragment the heap. |
|
626 * To guarantee reentrancy, we fall back to malloc if the instance is |
|
627 * already in use (it's important to avoid suprises since this is such a |
|
628 * low-level routine). */ |
|
629 static DIR _global_dir; |
|
630 static bool _global_dir_is_in_use = false; |
|
631 |
|
632 static inline DIR *dir_calloc(void) |
|
633 { |
|
634 DIR *d; |
|
635 |
|
636 if (_global_dir_is_in_use) { |
|
637 d = calloc(1, sizeof(*d)); |
|
638 } else { |
|
639 _global_dir_is_in_use = true; |
|
640 d = &_global_dir; |
|
641 memset(d, 0, sizeof(*d)); |
|
642 } |
|
643 return d; |
|
644 } |
|
645 |
|
646 static inline void dir_free(DIR *d) |
|
647 { |
|
648 if (d == &_global_dir) { |
|
649 _global_dir_is_in_use = false; |
|
650 } else { |
|
651 free(d); |
|
652 } |
|
653 } |
|
654 |
|
655 DIR *opendir(const char *path) |
|
656 { |
|
657 DIR *d; |
|
658 UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // disable 'no-disk' message box |
|
659 DWORD fa = GetFileAttributesW(OTTD2FS(path)); |
|
660 |
|
661 if ((fa != INVALID_FILE_ATTRIBUTES) && (fa & FILE_ATTRIBUTE_DIRECTORY)) { |
|
662 d = dir_calloc(); |
|
663 if (d != NULL) { |
|
664 char search_path[MAX_PATH]; |
|
665 /* build search path for FindFirstFile */ |
|
666 snprintf(search_path, lengthof(search_path), "%s" PATHSEP "*", path); |
|
667 d->hFind = FindFirstFileW(OTTD2FS(search_path), &d->fd); |
|
668 |
|
669 if (d->hFind != INVALID_HANDLE_VALUE || |
|
670 GetLastError() == ERROR_NO_MORE_FILES) { // the directory is empty |
|
671 d->ent.dir = d; |
|
672 d->at_first_entry = true; |
|
673 } else { |
|
674 dir_free(d); |
|
675 d = NULL; |
|
676 } |
|
677 } else { |
|
678 errno = ENOMEM; |
|
679 } |
|
680 } else { |
|
681 /* path not found or not a directory */ |
|
682 d = NULL; |
|
683 errno = ENOENT; |
|
684 } |
|
685 |
|
686 SetErrorMode(sem); // restore previous setting |
|
687 return d; |
|
688 } |
|
689 |
|
690 struct dirent *readdir(DIR *d) |
|
691 { |
|
692 DWORD prev_err = GetLastError(); // avoid polluting last error |
|
693 |
|
694 if (d->at_first_entry) { |
|
695 /* the directory was empty when opened */ |
|
696 if (d->hFind == INVALID_HANDLE_VALUE) return NULL; |
|
697 d->at_first_entry = false; |
|
698 } else if (!FindNextFileW(d->hFind, &d->fd)) { // determine cause and bail |
|
699 if (GetLastError() == ERROR_NO_MORE_FILES) SetLastError(prev_err); |
|
700 return NULL; |
|
701 } |
|
702 |
|
703 /* This entry has passed all checks; return information about it. |
|
704 * (note: d_name is a pointer; see struct dirent definition) */ |
|
705 d->ent.d_name = d->fd.cFileName; |
|
706 return &d->ent; |
|
707 } |
|
708 |
|
709 int closedir(DIR *d) |
|
710 { |
|
711 FindClose(d->hFind); |
|
712 dir_free(d); |
|
713 return 0; |
|
714 } |
|
715 |
|
716 bool FiosIsRoot(const char *file) |
|
717 { |
|
718 return file[3] == '\0'; // C:\... |
|
719 } |
|
720 |
|
721 void FiosGetDrives(void) |
|
722 { |
|
723 TCHAR drives[256]; |
|
724 const TCHAR *s; |
|
725 |
|
726 GetLogicalDriveStrings(sizeof(drives), drives); |
|
727 for (s = drives; *s != '\0';) { |
|
728 FiosItem *fios = FiosAlloc(); |
|
729 fios->type = FIOS_TYPE_DRIVE; |
|
730 fios->mtime = 0; |
|
731 snprintf(fios->name, lengthof(fios->name), "%c:", s[0] & 0xFF); |
|
732 ttd_strlcpy(fios->title, fios->name, lengthof(fios->title)); |
|
733 while (*s++ != '\0'); |
|
734 } |
|
735 } |
|
736 |
|
737 bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb) |
|
738 { |
|
739 // hectonanoseconds between Windows and POSIX epoch |
|
740 static const int64 posix_epoch_hns = 0x019DB1DED53E8000LL; |
|
741 const WIN32_FIND_DATAW *fd = &ent->dir->fd; |
|
742 if (fd->dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) return false; |
|
743 |
|
744 sb->st_size = ((uint64) fd->nFileSizeHigh << 32) + fd->nFileSizeLow; |
|
745 /* UTC FILETIME to seconds-since-1970 UTC |
|
746 * we just have to subtract POSIX epoch and scale down to units of seconds. |
|
747 * http://www.gamedev.net/community/forums/topic.asp?topic_id=294070&whichpage=1� |
|
748 * XXX - not entirely correct, since filetimes on FAT aren't UTC but local, |
|
749 * this won't entirely be correct, but we use the time only for comparsion. */ |
|
750 sb->st_mtime = (time_t)((*(uint64*)&fd->ftLastWriteTime - posix_epoch_hns) / 1E7); |
|
751 sb->st_mode = (fd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)? S_IFDIR : S_IFREG; |
|
752 |
|
753 return true; |
|
754 } |
|
755 |
|
756 bool FiosGetDiskFreeSpace(const char *path, uint32 *tot) |
|
757 { |
|
758 UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // disable 'no-disk' message box |
|
759 bool retval = false; |
|
760 TCHAR root[4]; |
|
761 DWORD spc, bps, nfc, tnc; |
|
762 |
|
763 _sntprintf(root, lengthof(root), _T("%c:") _T(PATHSEP), path[0]); |
|
764 if (tot != NULL && GetDiskFreeSpace(root, &spc, &bps, &nfc, &tnc)) { |
|
765 *tot = ((spc * bps) * (uint64)nfc) >> 20; |
|
766 retval = true; |
|
767 } |
|
768 |
|
769 SetErrorMode(sem); // reset previous setting |
|
770 return retval; |
|
771 } |
|
772 |
|
773 static int ParseCommandLine(char *line, char **argv, int max_argc) |
|
774 { |
|
775 int n = 0; |
|
776 |
|
777 do { |
|
778 // skip whitespace |
|
779 while (*line == ' ' || *line == '\t') line++; |
|
780 |
|
781 // end? |
|
782 if (*line == '\0') break; |
|
783 |
|
784 // special handling when quoted |
|
785 if (*line == '"') { |
|
786 argv[n++] = ++line; |
|
787 while (*line != '"') { |
|
788 if (*line == '\0') return n; |
|
789 line++; |
|
790 } |
|
791 } else { |
|
792 argv[n++] = line; |
|
793 while (*line != ' ' && *line != '\t') { |
|
794 if (*line == '\0') return n; |
|
795 line++; |
|
796 } |
|
797 } |
|
798 *line++ = '\0'; |
|
799 } while (n != max_argc); |
|
800 |
|
801 return n; |
|
802 } |
|
803 |
|
804 void CreateConsole(void) |
|
805 { |
|
806 HANDLE hand; |
|
807 CONSOLE_SCREEN_BUFFER_INFO coninfo; |
|
808 |
|
809 if (_has_console) return; |
|
810 _has_console = true; |
|
811 |
|
812 AllocConsole(); |
|
813 |
|
814 hand = GetStdHandle(STD_OUTPUT_HANDLE); |
|
815 GetConsoleScreenBufferInfo(hand, &coninfo); |
|
816 coninfo.dwSize.Y = 500; |
|
817 SetConsoleScreenBufferSize(hand, coninfo.dwSize); |
|
818 |
|
819 // redirect unbuffered STDIN, STDOUT, STDERR to the console |
|
820 #if !defined(__CYGWIN__) |
|
821 *stdout = *_fdopen( _open_osfhandle((intptr_t)hand, _O_TEXT), "w" ); |
|
822 *stdin = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT), "r" ); |
|
823 *stderr = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT), "w" ); |
|
824 #else |
|
825 // open_osfhandle is not in cygwin |
|
826 *stdout = *fdopen(1, "w" ); |
|
827 *stdin = *fdopen(0, "r" ); |
|
828 *stderr = *fdopen(2, "w" ); |
|
829 #endif |
|
830 |
|
831 setvbuf(stdin, NULL, _IONBF, 0); |
|
832 setvbuf(stdout, NULL, _IONBF, 0); |
|
833 setvbuf(stderr, NULL, _IONBF, 0); |
|
834 } |
|
835 |
|
836 void ShowInfo(const char *str) |
|
837 { |
|
838 if (_has_console) { |
|
839 fprintf(stderr, str); |
|
840 } else { |
|
841 bool old; |
|
842 |
|
843 ReleaseCapture(); |
|
844 _left_button_clicked =_left_button_down = false; |
|
845 |
|
846 old = MyShowCursor(true); |
|
847 if (MessageBox(GetActiveWindow(), MB_TO_WIDE(str), _T("OpenTTD"), MB_ICONINFORMATION | MB_OKCANCEL) == IDCANCEL) { |
|
848 CreateConsole(); |
|
849 } |
|
850 MyShowCursor(old); |
|
851 } |
|
852 } |
|
853 |
|
854 #ifdef __MINGW32__ |
|
855 /* _set_error_mode() constants&function (do not exist in mingw headers) */ |
|
856 #define _OUT_TO_DEFAULT 0 |
|
857 #define _OUT_TO_STDERR 1 |
|
858 #define _OUT_TO_MSGBOX 2 |
|
859 #define _REPORT_ERRMODE 3 |
|
860 int _set_error_mode(int); |
|
861 #endif |
|
862 |
|
863 int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, |
|
864 LPTSTR lpCmdLine, int nCmdShow) |
|
865 { |
|
866 int argc; |
|
867 char *argv[64]; // max 64 command line arguments |
|
868 char *cmdline; |
|
869 |
|
870 #if defined(UNICODE) |
|
871 /* For UNICODE we need to convert the commandline to char* _AND_ |
|
872 * save it because argv[] points into this buffer and thus needs to |
|
873 * be available between subsequent calls to FS2OTTD() */ |
|
874 char cmdlinebuf[MAX_PATH]; |
|
875 #endif |
|
876 |
|
877 cmdline = WIDE_TO_MB_BUFFER(GetCommandLine(), cmdlinebuf, lengthof(cmdlinebuf)); |
|
878 |
|
879 #if defined(_DEBUG) |
|
880 CreateConsole(); |
|
881 #endif |
|
882 |
|
883 _set_error_mode(_OUT_TO_MSGBOX); // force assertion output to messagebox |
|
884 |
|
885 /* setup random seed to something quite random */ |
|
886 _random_seeds[1][0] = _random_seeds[0][0] = GetTickCount(); |
|
887 _random_seeds[1][1] = _random_seeds[0][1] = _random_seeds[0][0] * 0x1234567; |
|
888 SeedMT(_random_seeds[0][0]); |
|
889 |
|
890 argc = ParseCommandLine(cmdline, argv, lengthof(argv)); |
|
891 |
|
892 #if defined(WIN32_EXCEPTION_TRACKER) |
|
893 Win32InitializeExceptions(); |
|
894 #endif |
|
895 |
|
896 #if defined(WIN32_EXCEPTION_TRACKER_DEBUG) |
|
897 _try { |
|
898 LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep); |
|
899 #endif |
|
900 ttd_main(argc, argv); |
|
901 |
|
902 #if defined(WIN32_EXCEPTION_TRACKER_DEBUG) |
|
903 } _except (ExceptionHandler(_exception_info())) {} |
|
904 #endif |
|
905 |
|
906 return 0; |
|
907 } |
|
908 |
|
909 void DeterminePaths(void) |
|
910 { |
|
911 char *s, *cfg; |
|
912 wchar_t path[MAX_PATH]; |
|
913 |
|
914 _paths.personal_dir = _paths.game_data_dir = cfg = malloc(MAX_PATH); |
|
915 GetCurrentDirectoryW(MAX_PATH - 1, path); |
|
916 convert_from_fs(path, cfg, MAX_PATH); |
|
917 |
|
918 cfg[0] = toupper(cfg[0]); |
|
919 s = strchr(cfg, '\0'); |
|
920 if (s[-1] != '\\') strcpy(s, "\\"); |
|
921 |
|
922 _paths.save_dir = str_fmt("%ssave", cfg); |
|
923 _paths.autosave_dir = str_fmt("%s\\autosave", _paths.save_dir); |
|
924 _paths.scenario_dir = str_fmt("%sscenario", cfg); |
|
925 _paths.heightmap_dir = str_fmt("%sscenario\\heightmap", cfg); |
|
926 _paths.gm_dir = str_fmt("%sgm\\", cfg); |
|
927 _paths.data_dir = str_fmt("%sdata\\", cfg); |
|
928 _paths.lang_dir = str_fmt("%slang\\", cfg); |
|
929 |
|
930 if (_config_file == NULL) |
|
931 _config_file = str_fmt("%sopenttd.cfg", _paths.personal_dir); |
|
932 |
|
933 _highscore_file = str_fmt("%shs.dat", _paths.personal_dir); |
|
934 _log_file = str_fmt("%sopenttd.log", _paths.personal_dir); |
|
935 |
|
936 // make (auto)save and scenario folder |
|
937 CreateDirectoryW(OTTD2FS(_paths.save_dir), NULL); |
|
938 CreateDirectoryW(OTTD2FS(_paths.autosave_dir), NULL); |
|
939 CreateDirectoryW(OTTD2FS(_paths.scenario_dir), NULL); |
|
940 CreateDirectoryW(OTTD2FS(_paths.heightmap_dir), NULL); |
|
941 } |
|
942 |
|
943 /** |
|
944 * Insert a chunk of text from the clipboard onto the textbuffer. Get TEXT clipboard |
|
945 * and append this up to the maximum length (either absolute or screenlength). If maxlength |
|
946 * is zero, we don't care about the screenlength but only about the physical length of the string |
|
947 * @param tb @Textbuf type to be changed |
|
948 * @return Return true on successfull change of Textbuf, or false otherwise |
|
949 */ |
|
950 bool InsertTextBufferClipboard(Textbuf *tb) |
|
951 { |
|
952 HGLOBAL cbuf; |
|
953 char utf8_buf[512]; |
|
954 const char *ptr; |
|
955 |
|
956 WChar c; |
|
957 uint16 width, length; |
|
958 |
|
959 if (IsClipboardFormatAvailable(CF_UNICODETEXT)) { |
|
960 const char *ret; |
|
961 |
|
962 OpenClipboard(NULL); |
|
963 cbuf = GetClipboardData(CF_UNICODETEXT); |
|
964 |
|
965 ptr = GlobalLock(cbuf); |
|
966 ret = convert_from_fs((wchar_t*)ptr, utf8_buf, lengthof(utf8_buf)); |
|
967 GlobalUnlock(cbuf); |
|
968 CloseClipboard(); |
|
969 |
|
970 if (*ret == '\0') return false; |
|
971 } else if (IsClipboardFormatAvailable(CF_TEXT)) { |
|
972 OpenClipboard(NULL); |
|
973 cbuf = GetClipboardData(CF_TEXT); |
|
974 |
|
975 ptr = GlobalLock(cbuf); |
|
976 ttd_strlcpy(utf8_buf, ptr, lengthof(utf8_buf)); |
|
977 GlobalUnlock(cbuf); |
|
978 CloseClipboard(); |
|
979 } else { |
|
980 return false; |
|
981 } |
|
982 |
|
983 width = length = 0; |
|
984 |
|
985 for (ptr = utf8_buf; (c = Utf8Consume(&ptr)) != '\0';) { |
|
986 byte charwidth; |
|
987 |
|
988 if (!IsPrintable(c)) break; |
|
989 if (tb->length + length >= tb->maxlength - 1) break; |
|
990 charwidth = GetCharacterWidth(FS_NORMAL, c); |
|
991 |
|
992 if (tb->maxwidth != 0 && width + tb->width + charwidth > tb->maxwidth) break; |
|
993 |
|
994 width += charwidth; |
|
995 length += Utf8CharLen(c); |
|
996 } |
|
997 |
|
998 if (length == 0) return false; |
|
999 |
|
1000 memmove(tb->buf + tb->caretpos + length, tb->buf + tb->caretpos, tb->length - tb->caretpos); |
|
1001 memcpy(tb->buf + tb->caretpos, utf8_buf, length); |
|
1002 tb->width += width; |
|
1003 tb->caretxoffs += width; |
|
1004 |
|
1005 tb->length += length; |
|
1006 tb->caretpos += length; |
|
1007 tb->buf[tb->length] = '\0'; // terminating zero |
|
1008 |
|
1009 return true; |
|
1010 } |
|
1011 |
|
1012 |
|
1013 void CSleep(int milliseconds) |
|
1014 { |
|
1015 Sleep(milliseconds); |
|
1016 } |
|
1017 |
|
1018 |
|
1019 // Utility function to get the current timestamp in milliseconds |
|
1020 // Useful for profiling |
|
1021 int64 GetTS(void) |
|
1022 { |
|
1023 static double freq; |
|
1024 __int64 value; |
|
1025 if (!freq) { |
|
1026 QueryPerformanceFrequency((LARGE_INTEGER*)&value); |
|
1027 freq = (double)1000000 / value; |
|
1028 } |
|
1029 QueryPerformanceCounter((LARGE_INTEGER*)&value); |
|
1030 return (__int64)(value * freq); |
|
1031 } |
|
1032 |
|
1033 /** Convert from OpenTTD's encoding to that of the local environment in |
|
1034 * UNICODE. OpenTTD encoding is UTF8, local is wide-char |
|
1035 * @param name pointer to a valid string that will be converted |
|
1036 * @param utf16_buf pointer to a valid wide-char buffer that will receive the |
|
1037 * converted string |
|
1038 * @param buflen length in wide characters of the receiving buffer |
|
1039 * @return pointer to utf16_buf. If conversion fails the string is of zero-length */ |
|
1040 wchar_t *convert_to_fs(const char *name, wchar_t *utf16_buf, size_t buflen) |
|
1041 { |
|
1042 int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, utf16_buf, buflen); |
|
1043 if (len == 0) { |
|
1044 DEBUG(misc, 0, "[utf8] error converting '%s'. Errno %d", name, GetLastError()); |
|
1045 utf16_buf[0] = '\0'; |
|
1046 } |
|
1047 |
|
1048 return utf16_buf; |
|
1049 } |
|
1050 |
|
1051 /** Convert from OpenTTD's encoding to that of the local environment in |
|
1052 * UNICODE. OpenTTD encoding is UTF8, local is wide-char. |
|
1053 * The returned value's contents can only be guaranteed until the next call to |
|
1054 * this function. So if the value is needed for anything else, use convert_from_fs |
|
1055 * @param name pointer to a valid string that will be converted |
|
1056 * @return pointer to the converted string; if failed string is of zero-length */ |
|
1057 const wchar_t *OTTD2FS(const char *name) |
|
1058 { |
|
1059 static wchar_t utf16_buf[512]; |
|
1060 return convert_to_fs(name, utf16_buf, lengthof(utf16_buf)); |
|
1061 } |
|
1062 |
|
1063 |
|
1064 /** Convert to OpenTTD's encoding from that of the local environment in |
|
1065 * UNICODE. OpenTTD encoding is UTF8, local is wide-char |
|
1066 * @param name pointer to a valid string that will be converted |
|
1067 * @param utf8_buf pointer to a valid buffer that will receive the converted string |
|
1068 * @param buflen length in characters of the receiving buffer |
|
1069 * @return pointer to utf8_buf. If conversion fails the string is of zero-length */ |
|
1070 char *convert_from_fs(const wchar_t *name, char *utf8_buf, size_t buflen) |
|
1071 { |
|
1072 int len = WideCharToMultiByte(CP_UTF8, 0, name, -1, utf8_buf, buflen, NULL, NULL); |
|
1073 if (len == 0) { |
|
1074 DEBUG(misc, 0, "[utf8] error converting wide-string. Errno %d", GetLastError()); |
|
1075 utf8_buf[0] = '\0'; |
|
1076 } |
|
1077 |
|
1078 return utf8_buf; |
|
1079 } |
|
1080 |
|
1081 /** Convert to OpenTTD's encoding from that of the local environment in |
|
1082 * UNICODE. OpenTTD encoding is UTF8, local is wide-char. |
|
1083 * The returned value's contents can only be guaranteed until the next call to |
|
1084 * this function. So if the value is needed for anything else, use convert_from_fs |
|
1085 * @param name pointer to a valid string that will be converted |
|
1086 * @return pointer to the converted string; if failed string is of zero-length */ |
|
1087 const char *FS2OTTD(const wchar_t *name) |
|
1088 { |
|
1089 static char utf8_buf[512]; |
|
1090 return convert_from_fs(name, utf8_buf, lengthof(utf8_buf)); |
|
1091 } |
|
1092 |
|
1093 /** Our very own SHGetFolderPath function for support of windows operating |
|
1094 * systems that don't have this function (eg Win9x, etc.). We try using the |
|
1095 * native function, and if that doesn't exist we will try a more crude approach |
|
1096 * of environment variables and hope for the best */ |
|
1097 HRESULT OTTDSHGetFolderPath(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPTSTR pszPath) |
|
1098 { |
|
1099 static HRESULT (WINAPI *SHGetFolderPath)(HWND, int, HANDLE, DWORD, LPTSTR) = NULL; |
|
1100 static bool first_time = true; |
|
1101 |
|
1102 /* We only try to load the library one time; if it fails, it fails */ |
|
1103 if (first_time) { |
|
1104 #if defined(UNICODE) |
|
1105 # define W(x) x "W" |
|
1106 #else |
|
1107 # define W(x) x "A" |
|
1108 #endif |
|
1109 if (!LoadLibraryList((Function*)&SHGetFolderPath, "SHFolder.dll\0" W("SHGetFolderPath") "\0\0")) { |
|
1110 DEBUG(misc, 0, "Unable to load " W("SHGetFolderPath") "from SHFolder.dll"); |
|
1111 } |
|
1112 #undef W |
|
1113 first_time = false; |
|
1114 } |
|
1115 |
|
1116 if (SHGetFolderPath != NULL) return SHGetFolderPath(hwnd, csidl, hToken, dwFlags, pszPath); |
|
1117 |
|
1118 /* SHGetFolderPath doesn't exist, try a more conservative approach, |
|
1119 * eg environment variables. This is only included for legacy modes |
|
1120 * MSDN says: that 'pszPath' is a "Pointer to a null-terminated string of |
|
1121 * length MAX_PATH which will receive the path" so let's assume that |
|
1122 * Windows 95 with Internet Explorer 5.0, Windows 98 with Internet Explorer 5.0, |
|
1123 * Windows 98 Second Edition (SE), Windows NT 4.0 with Internet Explorer 5.0, |
|
1124 * Windows NT 4.0 with Service Pack 4 (SP4) */ |
|
1125 { |
|
1126 DWORD ret; |
|
1127 switch (csidl) { |
|
1128 case CSIDL_FONTS: /* Get the system font path, eg %WINDIR%\Fonts */ |
|
1129 ret = GetEnvironmentVariable(_T("WINDIR"), pszPath, MAX_PATH); |
|
1130 if (ret == 0) break; |
|
1131 _tcsncat(pszPath, _T("\\Fonts"), MAX_PATH); |
|
1132 |
|
1133 return (HRESULT)0; |
|
1134 break; |
|
1135 /* XXX - other types to go here when needed... */ |
|
1136 } |
|
1137 } |
|
1138 |
|
1139 return E_INVALIDARG; |
|
1140 } |