primeiro commit

This commit is contained in:
2024-08-10 10:51:42 -03:00
commit 13a9ba0750
1569 changed files with 721067 additions and 0 deletions

View File

@@ -0,0 +1,38 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file G5_detector.cpp Detection for G5 machines (PowerPC). */
#include <mach/mach.h>
#include <mach/mach_host.h>
#include <mach/host_info.h>
#include <mach/machine.h>
#include <stdio.h>
#ifndef CPU_SUBTYPE_POWERPC_970
#define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
#endif
/* this function is a lightly modified version of some code from Apple's developer homepage to detect G5 CPUs at runtime */
int main()
{
host_basic_info_data_t hostInfo;
mach_msg_type_number_t infoCount;
boolean_t is_G5;
infoCount = HOST_BASIC_INFO_COUNT;
host_info(mach_host_self(), HOST_BASIC_INFO,
(host_info_t)&hostInfo, &infoCount);
is_G5 = ((hostInfo.cpu_type == CPU_TYPE_POWERPC) &&
(hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970));
if (is_G5)
printf("1");
}

View File

@@ -0,0 +1,256 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file crashlog_osx.cpp OS X crash log handler */
#include "../../stdafx.h"
#include "../../crashlog.h"
#include "../../string_func.h"
#include "../../gamelog.h"
#include "../../saveload/saveload.h"
#include "macos.h"
#include <errno.h>
#include <signal.h>
#include <mach-o/arch.h>
#include <dlfcn.h>
#include <cxxabi.h>
#include "../../safeguards.h"
/* Macro testing a stack address for valid alignment. */
#if defined(__i386__)
#define IS_ALIGNED(addr) (((uintptr_t)(addr) & 0xf) == 8)
#else
#define IS_ALIGNED(addr) (((uintptr_t)(addr) & 0xf) == 0)
#endif
/* printf format specification for 32/64-bit addresses. */
#ifdef __LP64__
#define PRINTF_PTR "0x%016lx"
#else
#define PRINTF_PTR "0x%08lx"
#endif
#define MAX_STACK_FRAMES 64
/**
* OSX implementation for the crash logger.
*/
class CrashLogOSX : public CrashLog {
/** Signal that has been thrown. */
int signum;
char filename_log[MAX_PATH]; ///< Path of crash.log
char filename_save[MAX_PATH]; ///< Path of crash.sav
char filename_screenshot[MAX_PATH]; ///< Path of crash.(png|bmp|pcx)
/* virtual */ char *LogOSVersion(char *buffer, const char *last) const
{
int ver_maj, ver_min, ver_bug;
GetMacOSVersion(&ver_maj, &ver_min, &ver_bug);
const NXArchInfo *arch = NXGetLocalArchInfo();
return buffer + seprintf(buffer, last,
"Operating system:\n"
" Name: Mac OS X\n"
" Release: %d.%d.%d\n"
" Machine: %s\n"
" Min Ver: %d\n",
ver_maj, ver_min, ver_bug,
arch != NULL ? arch->description : "unknown",
MAC_OS_X_VERSION_MIN_REQUIRED
);
}
/* virtual */ char *LogError(char *buffer, const char *last, const char *message) const
{
return buffer + seprintf(buffer, last,
"Crash reason:\n"
" Signal: %s (%d)\n"
" Message: %s\n\n",
strsignal(this->signum),
this->signum,
message == NULL ? "<none>" : message
);
}
/* virtual */ char *LogStacktrace(char *buffer, const char *last) const
{
/* As backtrace() is only implemented in 10.5 or later,
* we're rolling our own here. Mostly based on
* http://stackoverflow.com/questions/289820/getting-the-current-stack-trace-on-mac-os-x
* and some details looked up in the Darwin sources. */
buffer += seprintf(buffer, last, "\nStacktrace:\n");
void **frame;
#if defined(__ppc__) || defined(__ppc64__)
/* Apple says __builtin_frame_address can be broken on PPC. */
__asm__ volatile("mr %0, r1" : "=r" (frame));
#else
frame = (void **)__builtin_frame_address(0);
#endif
for (int i = 0; frame != NULL && i < MAX_STACK_FRAMES; i++) {
/* Get IP for current stack frame. */
#if defined(__ppc__) || defined(__ppc64__)
void *ip = frame[2];
#else
void *ip = frame[1];
#endif
if (ip == NULL) break;
/* Print running index. */
buffer += seprintf(buffer, last, " [%02d]", i);
Dl_info dli;
bool dl_valid = dladdr(ip, &dli) != 0;
const char *fname = "???";
if (dl_valid && dli.dli_fname) {
/* Valid image name? Extract filename from the complete path. */
const char *s = strrchr(dli.dli_fname, '/');
if (s != NULL) {
fname = s + 1;
} else {
fname = dli.dli_fname;
}
}
/* Print image name and IP. */
buffer += seprintf(buffer, last, " %-20s " PRINTF_PTR, fname, (uintptr_t)ip);
/* Print function offset if information is available. */
if (dl_valid && dli.dli_sname != NULL && dli.dli_saddr != NULL) {
/* Try to demangle a possible C++ symbol. */
int status = -1;
char *func_name = abi::__cxa_demangle(dli.dli_sname, NULL, 0, &status);
long int offset = (intptr_t)ip - (intptr_t)dli.dli_saddr;
buffer += seprintf(buffer, last, " (%s + %ld)", func_name != NULL ? func_name : dli.dli_sname, offset);
free(func_name);
}
buffer += seprintf(buffer, last, "\n");
/* Get address of next stack frame. */
void **next = (void **)frame[0];
/* Frame address not increasing or not aligned? Broken stack, exit! */
if (next <= frame || !IS_ALIGNED(next)) break;
frame = next;
}
return buffer + seprintf(buffer, last, "\n");
}
public:
/**
* A crash log is always generated by signal.
* @param signum the signal that was caused by the crash.
*/
CrashLogOSX(int signum) : signum(signum)
{
filename_log[0] = '\0';
filename_save[0] = '\0';
filename_screenshot[0] = '\0';
}
/** Generate the crash log. */
bool MakeCrashLog()
{
char buffer[65536];
bool ret = true;
printf("Crash encountered, generating crash log...\n");
this->FillCrashLog(buffer, lastof(buffer));
printf("%s\n", buffer);
printf("Crash log generated.\n\n");
printf("Writing crash log to disk...\n");
if (!this->WriteCrashLog(buffer, filename_log, lastof(filename_log))) {
filename_log[0] = '\0';
ret = false;
}
printf("Writing crash savegame...\n");
if (!this->WriteSavegame(filename_save, lastof(filename_save))) {
filename_save[0] = '\0';
ret = false;
}
printf("Writing crash savegame...\n");
if (!this->WriteScreenshot(filename_screenshot, lastof(filename_screenshot))) {
filename_screenshot[0] = '\0';
ret = false;
}
return ret;
}
/** Show a dialog with the crash information. */
void DisplayCrashDialog() const
{
static const char crash_title[] =
"A serious fault condition occurred in the game. The game will shut down.";
char message[1024];
seprintf(message, lastof(message),
"Please send the generated crash information and the last (auto)save to the developers. "
"This will greatly help debugging. The correct place to do this is http://bugs.openttd.org.\n\n"
"Generated file(s):\n%s\n%s\n%s",
this->filename_log, this->filename_save, this->filename_screenshot);
ShowMacDialog(crash_title, message, "Quit");
}
};
/** The signals we want our crash handler to handle. */
static const int _signals_to_handle[] = { SIGSEGV, SIGABRT, SIGFPE, SIGBUS, SIGILL, SIGSYS };
/**
* Entry point for the crash handler.
* @note Not static so it shows up in the backtrace.
* @param signum the signal that caused us to crash.
*/
void CDECL HandleCrash(int signum)
{
/* Disable all handling of signals by us, so we don't go into infinite loops. */
for (const int *i = _signals_to_handle; i != endof(_signals_to_handle); i++) {
signal(*i, SIG_DFL);
}
if (GamelogTestEmergency()) {
ShowMacDialog("A serious fault condition occurred in the game. The game will shut down.",
"As you loaded an emergency savegame no crash information will be generated.\n",
"Quit");
abort();
}
if (SaveloadCrashWithMissingNewGRFs()) {
ShowMacDialog("A serious fault condition occurred in the game. The game will shut down.",
"As you loaded an savegame for which you do not have the required NewGRFs no crash information will be generated.\n",
"Quit");
abort();
}
CrashLogOSX log(signum);
log.MakeCrashLog();
log.DisplayCrashDialog();
CrashLog::AfterCrashLogCleanup();
abort();
}
/* static */ void CrashLog::InitialiseCrashLog()
{
for (const int *i = _signals_to_handle; i != endof(_signals_to_handle); i++) {
signal(*i, HandleCrash);
}
}

41
src/os/macosx/macos.h Normal file
View File

@@ -0,0 +1,41 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file macos.h Functions related to MacOS support. */
#ifndef MACOS_H
#define MACOS_H
/** Helper function displaying a message the best possible way. */
void ShowMacDialog(const char *title, const char *message, const char *button_label);
void GetMacOSVersion(int *return_major, int *return_minor, int *return_bugfix);
/**
* Check if we are at least running on the specified version of Mac OS.
* @param major major version of the os. This would be 10 in the case of 10.4.11.
* @param minor minor version of the os. This would be 4 in the case of 10.4.11.
* @param bugfix bugfix version of the os. This would be 11 in the case of 10.4.11.
* @return true if the running os is at least what we asked, false otherwise.
*/
static inline bool MacOSVersionIsAtLeast(long major, long minor, long bugfix)
{
int version_major, version_minor, version_bugfix;
GetMacOSVersion(&version_major, &version_minor, &version_bugfix);
if (version_major < major) return false;
if (version_major == major && version_minor < minor) return false;
if (version_major == major && version_minor == minor && version_bugfix < bugfix) return false;
return true;
}
bool IsMonospaceFont(CFStringRef name);
#endif /* MACOS_H */

207
src/os/macosx/macos.mm Normal file
View File

@@ -0,0 +1,207 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file macos.mm Code related to MacOSX. */
#include "../../stdafx.h"
#include "../../core/bitmath_func.hpp"
#include "../../rev.h"
#include "macos.h"
#include "../../string_func.h"
#define Rect OTTDRect
#define Point OTTDPoint
#include <AppKit/AppKit.h>
#undef Rect
#undef Point
/*
* This file contains objective C
* Apple uses objective C instead of plain C to interact with OS specific/native functions
*/
/**
* Get the version of the MacOS we are running under. Code adopted
* from http://www.cocoadev.com/index.pl?DeterminingOSVersion
* @param return_major major version of the os. This would be 10 in the case of 10.4.11
* @param return_minor minor version of the os. This would be 4 in the case of 10.4.11
* @param return_bugfix bugfix version of the os. This would be 11 in the case of 10.4.11
* A return value of -1 indicates that something went wrong and we don't know.
*/
void GetMacOSVersion(int *return_major, int *return_minor, int *return_bugfix)
{
*return_major = -1;
*return_minor = -1;
*return_bugfix = -1;
SInt32 systemVersion, version_major, version_minor, version_bugfix;
if (Gestalt(gestaltSystemVersion, &systemVersion) == noErr) {
if (systemVersion >= 0x1040) {
if (Gestalt(gestaltSystemVersionMajor, &version_major) == noErr) *return_major = (int)version_major;
if (Gestalt(gestaltSystemVersionMinor, &version_minor) == noErr) *return_minor = (int)version_minor;
if (Gestalt(gestaltSystemVersionBugFix, &version_bugfix) == noErr) *return_bugfix = (int)version_bugfix;
} else {
*return_major = (int)(GB(systemVersion, 12, 4) * 10 + GB(systemVersion, 8, 4));
*return_minor = (int)GB(systemVersion, 4, 4);
*return_bugfix = (int)GB(systemVersion, 0, 4);
}
}
}
#ifdef WITH_SDL
/**
* Show the system dialogue message (SDL on MacOSX).
*
* @param title Window title.
* @param message Message text.
* @param buttonLabel Button text.
*/
void ShowMacDialog(const char *title, const char *message, const char *buttonLabel)
{
NSRunAlertPanel([ NSString stringWithUTF8String:title ], [ NSString stringWithUTF8String:message ], [ NSString stringWithUTF8String:buttonLabel ], nil, nil);
}
#elif defined WITH_COCOA
extern void CocoaDialog(const char *title, const char *message, const char *buttonLabel);
/**
* Show the system dialogue message (Cocoa on MacOSX).
*
* @param title Window title.
* @param message Message text.
* @param buttonLabel Button text.
*/
void ShowMacDialog(const char *title, const char *message, const char *buttonLabel)
{
CocoaDialog(title, message, buttonLabel);
}
#else
/**
* Show the system dialogue message (console on MacOSX).
*
* @param title Window title.
* @param message Message text.
* @param buttonLabel Button text.
*/
void ShowMacDialog(const char *title, const char *message, const char *buttonLabel)
{
fprintf(stderr, "%s: %s\n", title, message);
}
#endif
/**
* Show an error message.
*
* @param buf error message text.
* @param system message text originates from OS.
*/
void ShowOSErrorBox(const char *buf, bool system)
{
/* Display the error in the best way possible. */
if (system) {
ShowMacDialog("OpenTTD has encountered an error", buf, "Quit");
} else {
ShowMacDialog(buf, "See the readme for more info.", "Quit");
}
}
void OSOpenBrowser(const char *url)
{
[ [ NSWorkspace sharedWorkspace ] openURL:[ NSURL URLWithString:[ NSString stringWithUTF8String:url ] ] ];
}
/**
* Determine and return the current user's locale.
*/
const char *GetCurrentLocale(const char *)
{
static char retbuf[32] = { '\0' };
NSUserDefaults *defs = [ NSUserDefaults standardUserDefaults ];
NSArray *languages = [ defs objectForKey:@"AppleLanguages" ];
NSString *preferredLang = [ languages objectAtIndex:0 ];
/* preferredLang is either 2 or 5 characters long ("xx" or "xx_YY"). */
/* Since Apple introduced encoding to CString in OSX 10.4 we have to make a few conditions
* to get the right code for the used version of OSX. */
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4)
if (MacOSVersionIsAtLeast(10, 4, 0)) {
[ preferredLang getCString:retbuf maxLength:32 encoding:NSASCIIStringEncoding ];
} else
#endif
{
#if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_4)
/* maxLength does not include the \0 char in contrast to the call above. */
[ preferredLang getCString:retbuf maxLength:31 ];
#endif
}
return retbuf;
}
#ifdef WITH_COCOA
/**
* Return the contents of the clipboard (COCOA).
*
* @param buffer Clipboard content.
* @param last The pointer to the last element of the destination buffer
* @return Whether clipboard is empty or not.
*/
bool GetClipboardContents(char *buffer, const char *last)
{
NSPasteboard *pb = [ NSPasteboard generalPasteboard ];
NSArray *types = [ NSArray arrayWithObject:NSStringPboardType ];
NSString *bestType = [ pb availableTypeFromArray:types ];
/* Clipboard has no text data available. */
if (bestType == nil) return false;
NSString *string = [ pb stringForType:NSStringPboardType ];
if (string == nil || [ string length ] == 0) return false;
strecpy(buffer, [ string UTF8String ], last);
return true;
}
#endif
uint GetCPUCoreCount()
{
uint count = 1;
#if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
if (MacOSVersionIsAtLeast(10, 5, 0)) {
count = [ [ NSProcessInfo processInfo ] activeProcessorCount ];
} else
#endif
{
#if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
count = MPProcessorsScheduled();
#endif
}
return count;
}
/**
* Check if a font is a monospace font.
* @param name Name of the font.
* @return True if the font is a monospace font.
*/
bool IsMonospaceFont(CFStringRef name)
{
NSFont *font = [ NSFont fontWithName:(NSString *)name size:0.0f ];
return font != NULL ? [ font isFixedPitch ] : false;
}

114
src/os/macosx/osx_stdafx.h Normal file
View File

@@ -0,0 +1,114 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file osx_stdafx.h OSX is different on some places. */
#ifndef MACOS_STDAFX_H
#define MACOS_STDAFX_H
/* It would seem that to ensure backward compability we have to ensure that we have defined MAC_OS_X_VERSION_10_x everywhere */
#ifndef MAC_OS_X_VERSION_10_3
#define MAC_OS_X_VERSION_10_3 1030
#endif
#ifndef MAC_OS_X_VERSION_10_4
#define MAC_OS_X_VERSION_10_4 1040
#endif
#ifndef MAC_OS_X_VERSION_10_5
#define MAC_OS_X_VERSION_10_5 1050
#endif
#ifndef MAC_OS_X_VERSION_10_6
#define MAC_OS_X_VERSION_10_6 1060
#endif
#ifndef MAC_OS_X_VERSION_10_7
#define MAC_OS_X_VERSION_10_7 1070
#endif
#ifndef MAC_OS_X_VERSION_10_8
#define MAC_OS_X_VERSION_10_8 1080
#endif
#ifndef MAC_OS_X_VERSION_10_9
#define MAC_OS_X_VERSION_10_9 1090
#endif
#define __STDC_LIMIT_MACROS
#include <stdint.h>
/* Some gcc versions include assert.h via this header. As this would interfere
* with our own assert redefinition, include this header first. */
#if !defined(__clang__) && defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3))
# include <debug/debug.h>
#endif
/* Check for mismatching 'architectures' */
#if !defined(STRGEN) && !defined(SETTINGSGEN) && ((defined(__LP64__) && !defined(_SQ64)) || (!defined(__LP64__) && defined(_SQ64)))
# error "Compiling 64 bits without _SQ64 set! (or vice versa)"
#endif
#include <AvailabilityMacros.h>
/* Name conflict */
#define Rect OTTDRect
#define Point OTTDPoint
#define WindowClass OTTDWindowClass
#define ScriptOrder OTTDScriptOrder
#define Palette OTTDPalette
#define GlyphID OTTDGlyphID
#include <CoreServices/CoreServices.h>
#include <ApplicationServices/ApplicationServices.h>
#undef Rect
#undef Point
#undef WindowClass
#undef ScriptOrder
#undef Palette
#undef GlyphID
/* remove the variables that CoreServices defines, but we define ourselves too */
#undef bool
#undef false
#undef true
/* Name conflict */
#define GetTime OTTD_GetTime
#define SL_ERROR OSX_SL_ERROR
/* NSInteger and NSUInteger are part of 10.5 and higher. */
#ifndef NSInteger
#ifdef __LP64__
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif /* __LP64__ */
#endif /* NSInteger */
#ifndef CGFLOAT_DEFINED
#ifdef __LP64__
typedef double CGFloat;
#else
typedef float CGFloat;
#endif /* __LP64__ */
#endif /* CGFLOAT_DEFINED */
/* OS X SDK versions >= 10.5 have a non-const iconv. */
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
# define HAVE_NON_CONST_ICONV
#endif
#endif /* MACOS_STDAFX_H */

187
src/os/macosx/splash.cpp Normal file
View File

@@ -0,0 +1,187 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file splash.cpp Splash screen support for OSX. */
#include "../../stdafx.h"
#include "../../openttd.h"
#include "../../debug.h"
#include "../../gfx_func.h"
#include "../../fileio_func.h"
#include "../../blitter/factory.hpp"
#include "../../core/mem_func.hpp"
#include "splash.h"
#ifdef WITH_PNG
#include <png.h>
#include "../../safeguards.h"
/**
* Handle pnglib error.
*
* @param png_ptr Pointer to png struct.
* @param message Error message text.
*/
static void PNGAPI png_my_error(png_structp png_ptr, png_const_charp message)
{
DEBUG(misc, 0, "[libpng] error: %s - %s", message, (char *)png_get_error_ptr(png_ptr));
longjmp(png_jmpbuf(png_ptr), 1);
}
/**
* Handle warning in pnglib.
*
* @param png_ptr Pointer to png struct.
* @param message Warning message text.
*/
static void PNGAPI png_my_warning(png_structp png_ptr, png_const_charp message)
{
DEBUG(misc, 1, "[libpng] warning: %s - %s", message, (char *)png_get_error_ptr(png_ptr));
}
/**
* Display a splash image shown on startup (WITH_PNG).
*/
void DisplaySplashImage()
{
FILE *f = FioFOpenFile(SPLASH_IMAGE_FILE, "r", BASESET_DIR);
if (f == NULL) return;
png_byte header[8];
fread(header, sizeof(png_byte), 8, f);
if (png_sig_cmp(header, 0, 8) != 0) {
fclose(f);
return;
}
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp) NULL, png_my_error, png_my_warning);
if (png_ptr == NULL) {
fclose(f);
return;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
fclose(f);
return;
}
png_infop end_info = png_create_info_struct(png_ptr);
if (end_info == NULL) {
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
fclose(f);
return;
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(f);
return;
}
png_init_io(png_ptr, f);
png_set_sig_bytes(png_ptr, 8);
png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
uint width = png_get_image_width(png_ptr, info_ptr);
uint height = png_get_image_height(png_ptr, info_ptr);
uint bit_depth = png_get_bit_depth(png_ptr, info_ptr);
uint color_type = png_get_color_type(png_ptr, info_ptr);
if (color_type != PNG_COLOR_TYPE_PALETTE || bit_depth != 8) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(f);
return;
}
if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_PLTE)) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(f);
return;
}
png_colorp palette;
int num_palette;
png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
png_bytep *row_pointers = png_get_rows(png_ptr, info_ptr);
if (width > (uint) _screen.width) width = _screen.width;
if (height > (uint) _screen.height) height = _screen.height;
uint xoff = (_screen.width - width) / 2;
uint yoff = (_screen.height - height) / 2;
switch (BlitterFactory::GetCurrentBlitter()->GetScreenDepth()) {
case 8: {
uint8 *dst_ptr = (uint8 *)_screen.dst_ptr;
/* Initialize buffer */
MemSetT(dst_ptr, 0xff, _screen.pitch * _screen.height);
for (uint y = 0; y < height; y++) {
uint8 *src = row_pointers[y];
uint8 *dst = dst_ptr + (yoff + y) * _screen.pitch + xoff;
memcpy(dst, src, width);
}
for (int i = 0; i < num_palette; i++) {
_cur_palette.palette[i].a = i == 0 ? 0 : 0xff;
_cur_palette.palette[i].r = palette[i].red;
_cur_palette.palette[i].g = palette[i].green;
_cur_palette.palette[i].b = palette[i].blue;
}
_cur_palette.palette[0xff].a = 0xff;
_cur_palette.palette[0xff].r = 0;
_cur_palette.palette[0xff].g = 0;
_cur_palette.palette[0xff].b = 0;
_cur_palette.first_dirty = 0;
_cur_palette.count_dirty = 256;
break;
}
case 32: {
uint32 *dst_ptr = (uint32 *)_screen.dst_ptr;
/* Initialize buffer */
MemSetT(dst_ptr, 0, _screen.pitch * _screen.height);
for (uint y = 0; y < height; y++) {
uint8 *src = row_pointers[y];
uint32 *dst = dst_ptr + (yoff + y) * _screen.pitch + xoff;
for (uint x = 0; x < width; x++) {
dst[x] = palette[src[x]].blue | (palette[src[x]].green << 8) | (palette[src[x]].red << 16) | 0xff000000;
}
}
break;
}
}
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(f);
return;
}
#else /* WITH_PNG */
/**
* Empty 'Display a splash image' routine (WITHOUT_PNG).
*/
void DisplaySplashImage() {}
#endif /* WITH_PNG */

19
src/os/macosx/splash.h Normal file
View File

@@ -0,0 +1,19 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file splash.h Functions to support splash screens for OSX. */
#ifndef SPLASH_H
#define SPLASH_H
#define SPLASH_IMAGE_FILE "splash.png"
void DisplaySplashImage();
#endif /* SPLASH_H */

225
src/os/os2/os2.cpp Normal file
View File

@@ -0,0 +1,225 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file os2.cpp OS2 related OS support. */
#include "../../stdafx.h"
#include "../../openttd.h"
#include "../../gui.h"
#include "../../fileio_func.h"
#include "../../fios.h"
#include "../../openttd.h"
#include "../../core/random_func.hpp"
#include "../../string_func.h"
#include "../../textbuf_gui.h"
#include "table/strings.h"
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <time.h>
#ifndef __INNOTEK_LIBC__
#include <dos.h>
#endif
#include "../../safeguards.h"
#define INCL_WIN
#define INCL_WINCLIPBOARD
#include <os2.h>
#ifndef __INNOTEK_LIBC__
#include <i86.h>
#endif
bool FiosIsRoot(const char *file)
{
return file[3] == '\0';
}
void FiosGetDrives()
{
uint disk, disk2, save, total;
#ifndef __INNOTEK_LIBC__
_dos_getdrive(&save); // save original drive
#else
save = _getdrive(); // save original drive
char wd[MAX_PATH];
getcwd(wd, MAX_PATH);
total = 'z';
#endif
/* get an available drive letter */
#ifndef __INNOTEK_LIBC__
for (disk = 1;; disk++) {
_dos_setdrive(disk, &total);
#else
for (disk = 'A';; disk++) {
_chdrive(disk);
#endif
if (disk >= total) break;
#ifndef __INNOTEK_LIBC__
_dos_getdrive(&disk2);
#else
disk2 = _getdrive();
#endif
if (disk == disk2) {
FiosItem *fios = _fios_items.Append();
fios->type = FIOS_TYPE_DRIVE;
fios->mtime = 0;
#ifndef __INNOTEK_LIBC__
snprintf(fios->name, lengthof(fios->name), "%c:", 'A' + disk - 1);
#else
snprintf(fios->name, lengthof(fios->name), "%c:", disk);
#endif
strecpy(fios->title, fios->name, lastof(fios->title));
}
}
/* Restore the original drive */
#ifndef __INNOTEK_LIBC__
_dos_setdrive(save, &total);
#else
chdir(wd);
#endif
}
bool FiosGetDiskFreeSpace(const char *path, uint64 *tot)
{
#ifndef __INNOTEK_LIBC__
struct diskfree_t free;
char drive = path[0] - 'A' + 1;
if (tot != NULL && _getdiskfree(drive, &free) == 0) {
*tot = free.avail_clusters * free.sectors_per_cluster * free.bytes_per_sector;
return true;
}
return false;
#else
uint64 free = 0;
#ifdef HAS_STATVFS
{
struct statvfs s;
if (statvfs(path, &s) != 0) return false;
free = (uint64)s.f_frsize * s.f_bavail;
}
#endif
if (tot != NULL) *tot = free;
return true;
#endif
}
bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb)
{
char filename[MAX_PATH];
snprintf(filename, lengthof(filename), "%s" PATHSEP "%s", path, ent->d_name);
return stat(filename, sb) == 0;
}
bool FiosIsHiddenFile(const struct dirent *ent)
{
return ent->d_name[0] == '.';
}
void ShowInfo(const char *str)
{
HAB hab;
HMQ hmq;
ULONG rc;
/* init PM env. */
hmq = WinCreateMsgQueue((hab = WinInitialize(0)), 0);
/* display the box */
rc = WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, (const unsigned char *)str, (const unsigned char *)"OpenTTD", 0, MB_OK | MB_MOVEABLE | MB_INFORMATION);
/* terminate PM env. */
WinDestroyMsgQueue(hmq);
WinTerminate(hab);
}
void ShowOSErrorBox(const char *buf, bool system)
{
HAB hab;
HMQ hmq;
ULONG rc;
/* init PM env. */
hmq = WinCreateMsgQueue((hab = WinInitialize(0)), 0);
/* display the box */
rc = WinMessageBox(HWND_DESKTOP, HWND_DESKTOP, (const unsigned char *)buf, (const unsigned char *)"OpenTTD", 0, MB_OK | MB_MOVEABLE | MB_ERROR);
/* terminate PM env. */
WinDestroyMsgQueue(hmq);
WinTerminate(hab);
}
int CDECL main(int argc, char *argv[])
{
SetRandomSeed(time(NULL));
return openttd_main(argc, argv);
}
bool GetClipboardContents(char *buffer, const char *last)
{
/* XXX -- Currently no clipboard support implemented with GCC */
#ifndef __INNOTEK_LIBC__
HAB hab = 0;
if (WinOpenClipbrd(hab))
{
const char *text = (const char*)WinQueryClipbrdData(hab, CF_TEXT);
if (text != NULL)
{
strecpy(buffer, text, last);
WinCloseClipbrd(hab);
return true;
}
WinCloseClipbrd(hab);
}
#endif
return false;
}
void CSleep(int milliseconds)
{
#ifndef __INNOTEK_LIBC__
delay(milliseconds);
#else
usleep(milliseconds * 1000);
#endif
}
const char *FS2OTTD(const char *name) {return name;}
const char *OTTD2FS(const char *name) {return name;}
uint GetCPUCoreCount()
{
return 1;
}
void OSOpenBrowser(const char *url)
{
// stub only
DEBUG(misc, 0, "Failed to open url: %s", url);
}

View File

@@ -0,0 +1,185 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file crashlog_unix.cpp Unix crash log handler */
#include "../../stdafx.h"
#include "../../crashlog.h"
#include "../../string_func.h"
#include "../../gamelog.h"
#include "../../saveload/saveload.h"
#include <errno.h>
#include <signal.h>
#include <sys/utsname.h>
#if defined(__GLIBC__)
/* Execinfo (and thus making stacktraces) is a GNU extension */
# include <execinfo.h>
#elif defined(SUNOS)
# include <ucontext.h>
# include <dlfcn.h>
#endif
#if defined(__NetBSD__)
#include <unistd.h>
#endif
#include "../../safeguards.h"
/**
* Unix implementation for the crash logger.
*/
class CrashLogUnix : public CrashLog {
/** Signal that has been thrown. */
int signum;
/* virtual */ char *LogOSVersion(char *buffer, const char *last) const
{
struct utsname name;
if (uname(&name) < 0) {
return buffer + seprintf(buffer, last, "Could not get OS version: %s\n", strerror(errno));
}
return buffer + seprintf(buffer, last,
"Operating system:\n"
" Name: %s\n"
" Release: %s\n"
" Version: %s\n"
" Machine: %s\n",
name.sysname,
name.release,
name.version,
name.machine
);
}
/* virtual */ char *LogError(char *buffer, const char *last, const char *message) const
{
return buffer + seprintf(buffer, last,
"Crash reason:\n"
" Signal: %s (%d)\n"
" Message: %s\n\n",
strsignal(this->signum),
this->signum,
message == NULL ? "<none>" : message
);
}
#if defined(SUNOS)
/** Data needed while walking up the stack */
struct StackWalkerParams {
char **bufptr; ///< Buffer
const char *last; ///< End of buffer
int counter; ///< We are at counter-th stack level
};
/**
* Callback used while walking up the stack.
* @param pc program counter
* @param sig 'active' signal (unused)
* @param params parameters
* @return always 0, continue walking up the stack
*/
static int SunOSStackWalker(uintptr_t pc, int sig, void *params)
{
StackWalkerParams *wp = (StackWalkerParams *)params;
/* Resolve program counter to file and nearest symbol (if possible) */
Dl_info dli;
if (dladdr((void *)pc, &dli) != 0) {
*wp->bufptr += seprintf(*wp->bufptr, wp->last, " [%02i] %s(%s+0x%x) [0x%x]\n",
wp->counter, dli.dli_fname, dli.dli_sname, (int)((byte *)pc - (byte *)dli.dli_saddr), (uint)pc);
} else {
*wp->bufptr += seprintf(*wp->bufptr, wp->last, " [%02i] [0x%x]\n", wp->counter, (uint)pc);
}
wp->counter++;
return 0;
}
#endif
/* virtual */ char *LogStacktrace(char *buffer, const char *last) const
{
buffer += seprintf(buffer, last, "Stacktrace:\n");
#if defined(__GLIBC__)
void *trace[64];
int trace_size = backtrace(trace, lengthof(trace));
char **messages = backtrace_symbols(trace, trace_size);
for (int i = 0; i < trace_size; i++) {
buffer += seprintf(buffer, last, " [%02i] %s\n", i, messages[i]);
}
free(messages);
#elif defined(SUNOS)
ucontext_t uc;
if (getcontext(&uc) != 0) {
buffer += seprintf(buffer, last, " getcontext() failed\n\n");
return buffer;
}
StackWalkerParams wp = { &buffer, last, 0 };
walkcontext(&uc, &CrashLogUnix::SunOSStackWalker, &wp);
#else
buffer += seprintf(buffer, last, " Not supported.\n");
#endif
return buffer + seprintf(buffer, last, "\n");
}
public:
/**
* A crash log is always generated by signal.
* @param signum the signal that was caused by the crash.
*/
CrashLogUnix(int signum) :
signum(signum)
{
}
};
/** The signals we want our crash handler to handle. */
static const int _signals_to_handle[] = { SIGSEGV, SIGABRT, SIGFPE, SIGBUS, SIGILL };
/**
* Entry point for the crash handler.
* @note Not static so it shows up in the backtrace.
* @param signum the signal that caused us to crash.
*/
static void CDECL HandleCrash(int signum)
{
/* Disable all handling of signals by us, so we don't go into infinite loops. */
for (const int *i = _signals_to_handle; i != endof(_signals_to_handle); i++) {
signal(*i, SIG_DFL);
}
if (GamelogTestEmergency()) {
printf("A serious fault condition occurred in the game. The game will shut down.\n");
printf("As you loaded an emergency savegame no crash information will be generated.\n");
abort();
}
if (SaveloadCrashWithMissingNewGRFs()) {
printf("A serious fault condition occurred in the game. The game will shut down.\n");
printf("As you loaded an savegame for which you do not have the required NewGRFs\n");
printf("no crash information will be generated.\n");
abort();
}
CrashLogUnix log(signum);
log.MakeCrashLog();
CrashLog::AfterCrashLogCleanup();
abort();
}
/* static */ void CrashLog::InitialiseCrashLog()
{
for (const int *i = _signals_to_handle; i != endof(_signals_to_handle); i++) {
signal(*i, HandleCrash);
}
}

378
src/os/unix/unix.cpp Normal file
View File

@@ -0,0 +1,378 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file unix.cpp Implementation of Unix specific file handling. */
#include "../../stdafx.h"
#include "../../textbuf_gui.h"
#include "../../openttd.h"
#include "../../crashlog.h"
#include "../../core/random_func.hpp"
#include "../../debug.h"
#include "../../string_func.h"
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <time.h>
#include <signal.h>
#ifdef __APPLE__
#include <sys/mount.h>
#elif (defined(_POSIX_VERSION) && _POSIX_VERSION >= 200112L) || defined(__GLIBC__)
#define HAS_STATVFS
#endif
#if defined(OPENBSD) || defined(__NetBSD__) || defined(__FreeBSD__)
#define HAS_SYSCTL
#endif
#ifdef HAS_STATVFS
#include <sys/statvfs.h>
#endif
#ifdef HAS_SYSCTL
#include <sys/sysctl.h>
#endif
#ifdef __MORPHOS__
#include <exec/types.h>
ULONG __stack = (1024*1024)*2; // maybe not that much is needed actually ;)
/* The system supplied definition of SIG_IGN does not match */
#undef SIG_IGN
#define SIG_IGN (void (*)(int))1
#endif /* __MORPHOS__ */
#ifdef __AMIGA__
#warning add stack symbol to avoid that user needs to set stack manually (tokai)
// ULONG __stack =
#endif
#if defined(__APPLE__)
#if defined(WITH_SDL)
/* the mac implementation needs this file included in the same file as main() */
#include <SDL.h>
#endif
#endif
#include "../../safeguards.h"
bool FiosIsRoot(const char *path)
{
#if !defined(__MORPHOS__) && !defined(__AMIGAOS__)
return path[1] == '\0';
#else
/* On MorphOS or AmigaOS paths look like: "Volume:directory/subdirectory" */
const char *s = strchr(path, ':');
return s != NULL && s[1] == '\0';
#endif
}
void FiosGetDrives()
{
return;
}
bool FiosGetDiskFreeSpace(const char *path, uint64 *tot)
{
uint64 free = 0;
#ifdef __APPLE__
struct statfs s;
if (statfs(path, &s) != 0) return false;
free = (uint64)s.f_bsize * s.f_bavail;
#elif defined(HAS_STATVFS)
struct statvfs s;
if (statvfs(path, &s) != 0) return false;
free = (uint64)s.f_frsize * s.f_bavail;
#endif
if (tot != NULL) *tot = free;
return true;
}
bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb)
{
char filename[MAX_PATH];
int res;
#if defined(__MORPHOS__) || defined(__AMIGAOS__)
/* On MorphOS or AmigaOS paths look like: "Volume:directory/subdirectory" */
if (FiosIsRoot(path)) {
res = seprintf(filename, lastof(filename), "%s:%s", path, ent->d_name);
} else // XXX - only next line!
#else
assert(path[strlen(path) - 1] == PATHSEPCHAR);
if (strlen(path) > 2) assert(path[strlen(path) - 2] != PATHSEPCHAR);
#endif
res = seprintf(filename, lastof(filename), "%s%s", path, ent->d_name);
/* Could we fully concatenate the path and filename? */
if (res >= (int)lengthof(filename) || res < 0) return false;
return stat(filename, sb) == 0;
}
bool FiosIsHiddenFile(const struct dirent *ent)
{
return ent->d_name[0] == '.';
}
#ifdef WITH_ICONV
#include <iconv.h>
#include <errno.h>
#include "../../debug.h"
#include "../../string_func.h"
const char *GetCurrentLocale(const char *param);
#define INTERNALCODE "UTF-8"
/**
* Try and try to decipher the current locale from environmental
* variables. MacOSX is hardcoded, other OS's are dynamic. If no suitable
* locale can be found, don't do any conversion ""
*/
static const char *GetLocalCode()
{
#if defined(__APPLE__)
return "UTF-8-MAC";
#else
/* Strip locale (eg en_US.UTF-8) to only have UTF-8 */
const char *locale = GetCurrentLocale("LC_CTYPE");
if (locale != NULL) locale = strchr(locale, '.');
return (locale == NULL) ? "" : locale + 1;
#endif
}
/**
* Convert between locales, which from and which to is set in the calling
* functions OTTD2FS() and FS2OTTD().
*/
static const char *convert_tofrom_fs(iconv_t convd, const char *name)
{
static char buf[1024];
/* There are different implementations of iconv. The older ones,
* e.g. SUSv2, pass a const pointer, whereas the newer ones, e.g.
* IEEE 1003.1 (2004), pass a non-const pointer. */
#ifdef HAVE_NON_CONST_ICONV
char *inbuf = const_cast<char*>(name);
#else
const char *inbuf = name;
#endif
char *outbuf = buf;
size_t outlen = sizeof(buf) - 1;
size_t inlen = strlen(name);
strecpy(outbuf, name, outbuf + outlen);
iconv(convd, NULL, NULL, NULL, NULL);
if (iconv(convd, &inbuf, &inlen, &outbuf, &outlen) == (size_t)(-1)) {
DEBUG(misc, 0, "[iconv] error converting '%s'. Errno %d", name, errno);
}
*outbuf = '\0';
/* FIX: invalid characters will abort conversion, but they shouldn't occur? */
return buf;
}
/**
* Convert from OpenTTD's encoding to that of the local environment
* @param name pointer to a valid string that will be converted
* @return pointer to a new stringbuffer that contains the converted string
*/
const char *OTTD2FS(const char *name)
{
static iconv_t convd = (iconv_t)(-1);
if (convd == (iconv_t)(-1)) {
const char *env = GetLocalCode();
convd = iconv_open(env, INTERNALCODE);
if (convd == (iconv_t)(-1)) {
DEBUG(misc, 0, "[iconv] conversion from codeset '%s' to '%s' unsupported", INTERNALCODE, env);
return name;
}
}
return convert_tofrom_fs(convd, name);
}
/**
* Convert to OpenTTD's encoding from that of the local environment
* @param name pointer to a valid string that will be converted
* @return pointer to a new stringbuffer that contains the converted string
*/
const char *FS2OTTD(const char *name)
{
static iconv_t convd = (iconv_t)(-1);
if (convd == (iconv_t)(-1)) {
const char *env = GetLocalCode();
convd = iconv_open(INTERNALCODE, env);
if (convd == (iconv_t)(-1)) {
DEBUG(misc, 0, "[iconv] conversion from codeset '%s' to '%s' unsupported", env, INTERNALCODE);
return name;
}
}
return convert_tofrom_fs(convd, name);
}
#else
const char *FS2OTTD(const char *name) {return name;}
const char *OTTD2FS(const char *name) {return name;}
#endif /* WITH_ICONV */
void ShowInfo(const char *str)
{
fprintf(stderr, "%s\n", str);
}
#if !defined(__APPLE__)
void ShowOSErrorBox(const char *buf, bool system)
{
/* All unix systems, except OSX. Only use escape codes on a TTY. */
if (isatty(fileno(stderr))) {
fprintf(stderr, "\033[1;31mError: %s\033[0;39m\n", buf);
} else {
fprintf(stderr, "Error: %s\n", buf);
}
}
#endif
#ifdef WITH_COCOA
void cocoaSetupAutoreleasePool();
void cocoaReleaseAutoreleasePool();
#endif
int CDECL main(int argc, char *argv[])
{
int ret;
#ifdef WITH_COCOA
cocoaSetupAutoreleasePool();
/* This is passed if we are launched by double-clicking */
if (argc >= 2 && strncmp(argv[1], "-psn", 4) == 0) {
argv[1] = NULL;
argc = 1;
}
#endif
CrashLog::InitialiseCrashLog();
SetRandomSeed(time(NULL));
signal(SIGPIPE, SIG_IGN);
ret = openttd_main(argc, argv);
#ifdef WITH_COCOA
cocoaReleaseAutoreleasePool();
#endif
return ret;
}
#ifndef WITH_COCOA
bool GetClipboardContents(char *buffer, const char *last)
{
return false;
}
#endif
/* multi os compatible sleep function */
#ifdef __AMIGA__
/* usleep() implementation */
# include <devices/timer.h>
# include <dos/dos.h>
extern struct Device *TimerBase = NULL;
extern struct MsgPort *TimerPort = NULL;
extern struct timerequest *TimerRequest = NULL;
#endif /* __AMIGA__ */
void CSleep(int milliseconds)
{
#if defined(PSP)
sceKernelDelayThread(milliseconds * 1000);
#elif defined(__BEOS__)
snooze(milliseconds * 1000);
#elif defined(__AMIGA__)
{
ULONG signals;
ULONG TimerSigBit = 1 << TimerPort->mp_SigBit;
/* send IORequest */
TimerRequest->tr_node.io_Command = TR_ADDREQUEST;
TimerRequest->tr_time.tv_secs = (milliseconds * 1000) / 1000000;
TimerRequest->tr_time.tv_micro = (milliseconds * 1000) % 1000000;
SendIO((struct IORequest *)TimerRequest);
if (!((signals = Wait(TimerSigBit | SIGBREAKF_CTRL_C)) & TimerSigBit) ) {
AbortIO((struct IORequest *)TimerRequest);
}
WaitIO((struct IORequest *)TimerRequest);
}
#else
usleep(milliseconds * 1000);
#endif
}
#ifndef __APPLE__
uint GetCPUCoreCount()
{
uint count = 1;
#ifdef HAS_SYSCTL
int ncpu = 0;
size_t len = sizeof(ncpu);
#ifdef OPENBSD
int name[2];
name[0] = CTL_HW;
name[1] = HW_NCPU;
if (sysctl(name, 2, &ncpu, &len, NULL, 0) < 0) {
ncpu = 0;
}
#else
if (sysctlbyname("hw.availcpu", &ncpu, &len, NULL, 0) < 0) {
sysctlbyname("hw.ncpu", &ncpu, &len, NULL, 0);
}
#endif /* #ifdef OPENBSD */
if (ncpu > 0) count = ncpu;
#elif defined(_SC_NPROCESSORS_ONLN)
long res = sysconf(_SC_NPROCESSORS_ONLN);
if (res > 0) count = res;
#endif
return count;
}
void OSOpenBrowser(const char *url)
{
pid_t child_pid = fork();
if (child_pid != 0) return;
const char *args[3];
args[0] = "xdg-open";
args[1] = url;
args[2] = NULL;
execvp(args[0], const_cast<char * const *>(args));
DEBUG(misc, 0, "Failed to open url: %s", url);
exit(0);
}
#endif

View File

@@ -0,0 +1,695 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file crashlog_win.cpp Implementation of a crashlogger for Windows */
#include "../../stdafx.h"
#include "../../crashlog.h"
#include "win32.h"
#include "../../core/alloc_func.hpp"
#include "../../core/math_func.hpp"
#include "../../string_func.h"
#include "../../fileio_func.h"
#include "../../strings_func.h"
#include "../../gamelog.h"
#include "../../saveload/saveload.h"
#include "../../video/video_driver.hpp"
#include <windows.h>
#include <signal.h>
#include "../../safeguards.h"
static const uint MAX_SYMBOL_LEN = 512;
static const uint MAX_FRAMES = 64;
/* printf format specification for 32/64-bit addresses. */
#ifdef _M_AMD64
#define PRINTF_PTR "0x%016IX"
#else
#define PRINTF_PTR "0x%08X"
#endif
/**
* Windows implementation for the crash logger.
*/
class CrashLogWindows : public CrashLog {
/** Information about the encountered exception */
EXCEPTION_POINTERS *ep;
/* virtual */ char *LogOSVersion(char *buffer, const char *last) const;
/* virtual */ char *LogError(char *buffer, const char *last, const char *message) const;
/* virtual */ char *LogStacktrace(char *buffer, const char *last) const;
/* virtual */ char *LogRegisters(char *buffer, const char *last) const;
/* virtual */ char *LogModules(char *buffer, const char *last) const;
public:
#if defined(_MSC_VER)
/* virtual */ int WriteCrashDump(char *filename, const char *filename_last) const;
char *AppendDecodedStacktrace(char *buffer, const char *last) const;
#else
char *AppendDecodedStacktrace(char *buffer, const char *last) const { return buffer; }
#endif /* _MSC_VER */
/** Buffer for the generated crash log */
char crashlog[65536];
/** Buffer for the filename of the crash log */
char crashlog_filename[MAX_PATH];
/** Buffer for the filename of the crash dump */
char crashdump_filename[MAX_PATH];
/** Buffer for the filename of the crash screenshot */
char screenshot_filename[MAX_PATH];
/**
* A crash log is always generated when it's generated.
* @param ep the data related to the exception.
*/
CrashLogWindows(EXCEPTION_POINTERS *ep = NULL) :
ep(ep)
{
this->crashlog[0] = '\0';
this->crashlog_filename[0] = '\0';
this->crashdump_filename[0] = '\0';
this->screenshot_filename[0] = '\0';
}
/**
* Points to the current crash log.
*/
static CrashLogWindows *current;
};
/* static */ CrashLogWindows *CrashLogWindows::current = NULL;
/* virtual */ char *CrashLogWindows::LogOSVersion(char *buffer, const char *last) const
{
_OSVERSIONINFOA os;
os.dwOSVersionInfoSize = sizeof(os);
GetVersionExA(&os);
return buffer + seprintf(buffer, last,
"Operating system:\n"
" Name: Windows\n"
" Release: %d.%d.%d (%s)\n",
(int)os.dwMajorVersion,
(int)os.dwMinorVersion,
(int)os.dwBuildNumber,
os.szCSDVersion
);
}
/* virtual */ char *CrashLogWindows::LogError(char *buffer, const char *last, const char *message) const
{
return buffer + seprintf(buffer, last,
"Crash reason:\n"
" Exception: %.8X\n"
#ifdef _M_AMD64
" Location: %.16IX\n"
#else
" Location: %.8X\n"
#endif
" Message: %s\n\n",
(int)ep->ExceptionRecord->ExceptionCode,
(size_t)ep->ExceptionRecord->ExceptionAddress,
message == NULL ? "<none>" : message
);
}
struct DebugFileInfo {
uint32 size;
uint32 crc32;
SYSTEMTIME file_time;
};
static uint32 *_crc_table;
static void MakeCRCTable(uint32 *table)
{
uint32 crc, poly = 0xEDB88320L;
int i;
int j;
_crc_table = table;
for (i = 0; i != 256; i++) {
crc = i;
for (j = 8; j != 0; j--) {
crc = (crc & 1 ? (crc >> 1) ^ poly : crc >> 1);
}
table[i] = crc;
}
}
static uint32 CalcCRC(byte *data, uint size, uint32 crc)
{
for (; size > 0; size--) {
crc = ((crc >> 8) & 0x00FFFFFF) ^ _crc_table[(crc ^ *data++) & 0xFF];
}
return crc;
}
static void GetFileInfo(DebugFileInfo *dfi, const TCHAR *filename)
{
HANDLE file;
memset(dfi, 0, sizeof(*dfi));
file = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
if (file != INVALID_HANDLE_VALUE) {
byte buffer[1024];
DWORD numread;
uint32 filesize = 0;
FILETIME write_time;
uint32 crc = (uint32)-1;
for (;;) {
if (ReadFile(file, buffer, sizeof(buffer), &numread, NULL) == 0 || numread == 0) {
break;
}
filesize += numread;
crc = CalcCRC(buffer, numread, crc);
}
dfi->size = filesize;
dfi->crc32 = crc ^ (uint32)-1;
if (GetFileTime(file, NULL, NULL, &write_time)) {
FileTimeToSystemTime(&write_time, &dfi->file_time);
}
CloseHandle(file);
}
}
static char *PrintModuleInfo(char *output, const char *last, HMODULE mod)
{
TCHAR buffer[MAX_PATH];
DebugFileInfo dfi;
GetModuleFileName(mod, buffer, MAX_PATH);
GetFileInfo(&dfi, buffer);
output += seprintf(output, last, " %-20s handle: %p size: %d crc: %.8X date: %d-%.2d-%.2d %.2d:%.2d:%.2d\n",
FS2OTTD(buffer),
mod,
dfi.size,
dfi.crc32,
dfi.file_time.wYear,
dfi.file_time.wMonth,
dfi.file_time.wDay,
dfi.file_time.wHour,
dfi.file_time.wMinute,
dfi.file_time.wSecond
);
return output;
}
/* virtual */ char *CrashLogWindows::LogModules(char *output, const char *last) const
{
MakeCRCTable(AllocaM(uint32, 256));
BOOL (WINAPI *EnumProcessModules)(HANDLE, HMODULE*, DWORD, LPDWORD);
output += seprintf(output, last, "Module information:\n");
if (LoadLibraryList((Function*)&EnumProcessModules, "psapi.dll\0EnumProcessModules\0\0")) {
HMODULE modules[100];
DWORD needed;
BOOL res;
HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
if (proc != NULL) {
res = EnumProcessModules(proc, modules, sizeof(modules), &needed);
CloseHandle(proc);
if (res) {
size_t count = min(needed / sizeof(HMODULE), lengthof(modules));
for (size_t i = 0; i != count; i++) output = PrintModuleInfo(output, last, modules[i]);
return output + seprintf(output, last, "\n");
}
}
}
output = PrintModuleInfo(output, last, NULL);
return output + seprintf(output, last, "\n");
}
/* virtual */ char *CrashLogWindows::LogRegisters(char *buffer, const char *last) const
{
buffer += seprintf(buffer, last, "Registers:\n");
#ifdef _M_AMD64
buffer += seprintf(buffer, last,
" RAX: %.16I64X RBX: %.16I64X RCX: %.16I64X RDX: %.16I64X\n"
" RSI: %.16I64X RDI: %.16I64X RBP: %.16I64X RSP: %.16I64X\n"
" R8: %.16I64X R9: %.16I64X R10: %.16I64X R11: %.16I64X\n"
" R12: %.16I64X R13: %.16I64X R14: %.16I64X R15: %.16I64X\n"
" RIP: %.16I64X EFLAGS: %.8lX\n",
ep->ContextRecord->Rax,
ep->ContextRecord->Rbx,
ep->ContextRecord->Rcx,
ep->ContextRecord->Rdx,
ep->ContextRecord->Rsi,
ep->ContextRecord->Rdi,
ep->ContextRecord->Rbp,
ep->ContextRecord->Rsp,
ep->ContextRecord->R8,
ep->ContextRecord->R9,
ep->ContextRecord->R10,
ep->ContextRecord->R11,
ep->ContextRecord->R12,
ep->ContextRecord->R13,
ep->ContextRecord->R14,
ep->ContextRecord->R15,
ep->ContextRecord->Rip,
ep->ContextRecord->EFlags
);
#else
buffer += seprintf(buffer, last,
" EAX: %.8X EBX: %.8X ECX: %.8X EDX: %.8X\n"
" ESI: %.8X EDI: %.8X EBP: %.8X ESP: %.8X\n"
" EIP: %.8X EFLAGS: %.8X\n",
(int)ep->ContextRecord->Eax,
(int)ep->ContextRecord->Ebx,
(int)ep->ContextRecord->Ecx,
(int)ep->ContextRecord->Edx,
(int)ep->ContextRecord->Esi,
(int)ep->ContextRecord->Edi,
(int)ep->ContextRecord->Ebp,
(int)ep->ContextRecord->Esp,
(int)ep->ContextRecord->Eip,
(int)ep->ContextRecord->EFlags
);
#endif
buffer += seprintf(buffer, last, "\n Bytes at instruction pointer:\n");
#ifdef _M_AMD64
byte *b = (byte*)ep->ContextRecord->Rip;
#else
byte *b = (byte*)ep->ContextRecord->Eip;
#endif
for (int i = 0; i != 24; i++) {
if (IsBadReadPtr(b, 1)) {
buffer += seprintf(buffer, last, " ??"); // OCR: WAS: , 0);
} else {
buffer += seprintf(buffer, last, " %.2X", *b);
}
b++;
}
return buffer + seprintf(buffer, last, "\n\n");
}
/* virtual */ char *CrashLogWindows::LogStacktrace(char *buffer, const char *last) const
{
buffer += seprintf(buffer, last, "Stack trace:\n");
#ifdef _M_AMD64
uint32 *b = (uint32*)ep->ContextRecord->Rsp;
#else
uint32 *b = (uint32*)ep->ContextRecord->Esp;
#endif
for (int j = 0; j != 24; j++) {
for (int i = 0; i != 8; i++) {
if (IsBadReadPtr(b, sizeof(uint32))) {
buffer += seprintf(buffer, last, " ????????"); // OCR: WAS - , 0);
} else {
buffer += seprintf(buffer, last, " %.8X", *b);
}
b++;
}
buffer += seprintf(buffer, last, "\n");
}
return buffer + seprintf(buffer, last, "\n");
}
#if defined(_MSC_VER)
#include <dbghelp.h>
char *CrashLogWindows::AppendDecodedStacktrace(char *buffer, const char *last) const
{
#define M(x) x "\0"
static const char dbg_import[] =
M("dbghelp.dll")
M("SymInitialize")
M("SymSetOptions")
M("SymCleanup")
M("StackWalk64")
M("SymFunctionTableAccess64")
M("SymGetModuleBase64")
M("SymGetModuleInfo64")
M("SymGetSymFromAddr64")
M("SymGetLineFromAddr64")
M("")
;
#undef M
struct ProcPtrs {
BOOL (WINAPI * pSymInitialize)(HANDLE, PCSTR, BOOL);
BOOL (WINAPI * pSymSetOptions)(DWORD);
BOOL (WINAPI * pSymCleanup)(HANDLE);
BOOL (WINAPI * pStackWalk64)(DWORD, HANDLE, HANDLE, LPSTACKFRAME64, PVOID, PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64, PTRANSLATE_ADDRESS_ROUTINE64);
PVOID (WINAPI * pSymFunctionTableAccess64)(HANDLE, DWORD64);
DWORD64 (WINAPI * pSymGetModuleBase64)(HANDLE, DWORD64);
BOOL (WINAPI * pSymGetModuleInfo64)(HANDLE, DWORD64, PIMAGEHLP_MODULE64);
BOOL (WINAPI * pSymGetSymFromAddr64)(HANDLE, DWORD64, PDWORD64, PIMAGEHLP_SYMBOL64);
BOOL (WINAPI * pSymGetLineFromAddr64)(HANDLE, DWORD64, PDWORD, PIMAGEHLP_LINE64);
} proc;
buffer += seprintf(buffer, last, "\nDecoded stack trace:\n");
/* Try to load the functions from the DLL, if that fails because of a too old dbghelp.dll, just skip it. */
if (LoadLibraryList((Function*)&proc, dbg_import)) {
/* Initialize symbol handler. */
HANDLE hCur = GetCurrentProcess();
proc.pSymInitialize(hCur, NULL, TRUE);
/* Load symbols only when needed, fail silently on errors, demangle symbol names. */
proc.pSymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_UNDNAME);
/* Initialize starting stack frame from context record. */
STACKFRAME64 frame;
memset(&frame, 0, sizeof(frame));
#ifdef _M_AMD64
frame.AddrPC.Offset = ep->ContextRecord->Rip;
frame.AddrFrame.Offset = ep->ContextRecord->Rbp;
frame.AddrStack.Offset = ep->ContextRecord->Rsp;
#else
frame.AddrPC.Offset = ep->ContextRecord->Eip;
frame.AddrFrame.Offset = ep->ContextRecord->Ebp;
frame.AddrStack.Offset = ep->ContextRecord->Esp;
#endif
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrFrame.Mode = AddrModeFlat;
frame.AddrStack.Mode = AddrModeFlat;
/* Copy context record as StackWalk64 may modify it. */
CONTEXT ctx;
memcpy(&ctx, ep->ContextRecord, sizeof(ctx));
/* Allocate space for symbol info. */
IMAGEHLP_SYMBOL64 *sym_info = (IMAGEHLP_SYMBOL64*)alloca(sizeof(IMAGEHLP_SYMBOL64) + MAX_SYMBOL_LEN - 1);
sym_info->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
sym_info->MaxNameLength = MAX_SYMBOL_LEN;
/* Walk stack at most MAX_FRAMES deep in case the stack is corrupt. */
for (uint num = 0; num < MAX_FRAMES; num++) {
if (!proc.pStackWalk64(
#ifdef _M_AMD64
IMAGE_FILE_MACHINE_AMD64,
#else
IMAGE_FILE_MACHINE_I386,
#endif
hCur, GetCurrentThread(), &frame, &ctx, NULL, proc.pSymFunctionTableAccess64, proc.pSymGetModuleBase64, NULL)) break;
if (frame.AddrPC.Offset == frame.AddrReturn.Offset) {
buffer += seprintf(buffer, last, " <infinite loop>\n");
break;
}
/* Get module name. */
const char *mod_name = "???";
IMAGEHLP_MODULE64 module;
module.SizeOfStruct = sizeof(module);
if (proc.pSymGetModuleInfo64(hCur, frame.AddrPC.Offset, &module)) {
mod_name = module.ModuleName;
}
/* Print module and instruction pointer. */
buffer += seprintf(buffer, last, "[%02d] %-20s " PRINTF_PTR, num, mod_name, frame.AddrPC.Offset);
/* Get symbol name and line info if possible. */
DWORD64 offset;
if (proc.pSymGetSymFromAddr64(hCur, frame.AddrPC.Offset, &offset, sym_info)) {
buffer += seprintf(buffer, last, " %s + %I64u", sym_info->Name, offset);
DWORD line_offs;
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
if (proc.pSymGetLineFromAddr64(hCur, frame.AddrPC.Offset, &line_offs, &line)) {
buffer += seprintf(buffer, last, " (%s:%d)", line.FileName, line.LineNumber);
}
}
buffer += seprintf(buffer, last, "\n");
}
proc.pSymCleanup(hCur);
}
return buffer + seprintf(buffer, last, "\n*** End of additional info ***\n");
}
/* virtual */ int CrashLogWindows::WriteCrashDump(char *filename, const char *filename_last) const
{
int ret = 0;
HMODULE dbghelp = LoadLibrary(_T("dbghelp.dll"));
if (dbghelp != NULL) {
typedef BOOL (WINAPI *MiniDumpWriteDump_t)(HANDLE, DWORD, HANDLE,
MINIDUMP_TYPE,
CONST PMINIDUMP_EXCEPTION_INFORMATION,
CONST PMINIDUMP_USER_STREAM_INFORMATION,
CONST PMINIDUMP_CALLBACK_INFORMATION);
MiniDumpWriteDump_t funcMiniDumpWriteDump = (MiniDumpWriteDump_t)GetProcAddress(dbghelp, "MiniDumpWriteDump");
if (funcMiniDumpWriteDump != NULL) {
seprintf(filename, filename_last, "%scrash.dmp", _personal_dir);
HANDLE file = CreateFile(OTTD2FS(filename), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
HANDLE proc = GetCurrentProcess();
DWORD procid = GetCurrentProcessId();
MINIDUMP_EXCEPTION_INFORMATION mdei;
MINIDUMP_USER_STREAM userstream;
MINIDUMP_USER_STREAM_INFORMATION musi;
userstream.Type = LastReservedStream + 1;
userstream.Buffer = (void*)this->crashlog;
userstream.BufferSize = (ULONG)strlen(this->crashlog) + 1;
musi.UserStreamCount = 1;
musi.UserStreamArray = &userstream;
mdei.ThreadId = GetCurrentThreadId();
mdei.ExceptionPointers = ep;
mdei.ClientPointers = false;
funcMiniDumpWriteDump(proc, procid, file, MiniDumpWithDataSegs, &mdei, &musi, NULL);
ret = 1;
} else {
ret = -1;
}
FreeLibrary(dbghelp);
}
return ret;
}
#endif /* _MSC_VER */
extern bool CloseConsoleLogIfActive();
static void ShowCrashlogWindow();
/**
* Stack pointer for use when 'starting' the crash handler.
* Not static as gcc's inline assembly needs it that way.
*/
void *_safe_esp = NULL;
static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep)
{
if (CrashLogWindows::current != NULL) {
CrashLog::AfterCrashLogCleanup();
ExitProcess(2);
}
if (GamelogTestEmergency()) {
static const TCHAR _emergency_crash[] =
_T("A serious fault condition occurred in the game. The game will shut down.\n")
_T("As you loaded an emergency savegame no crash information will be generated.\n");
MessageBox(NULL, _emergency_crash, _T("Fatal Application Failure"), MB_ICONERROR);
ExitProcess(3);
}
if (SaveloadCrashWithMissingNewGRFs()) {
static const TCHAR _saveload_crash[] =
_T("A serious fault condition occurred in the game. The game will shut down.\n")
_T("As you loaded an savegame for which you do not have the required NewGRFs\n")
_T("no crash information will be generated.\n");
MessageBox(NULL, _saveload_crash, _T("Fatal Application Failure"), MB_ICONERROR);
ExitProcess(3);
}
CrashLogWindows *log = new CrashLogWindows(ep);
CrashLogWindows::current = log;
char *buf = log->FillCrashLog(log->crashlog, lastof(log->crashlog));
log->WriteCrashDump(log->crashdump_filename, lastof(log->crashdump_filename));
log->AppendDecodedStacktrace(buf, lastof(log->crashlog));
log->WriteCrashLog(log->crashlog, log->crashlog_filename, lastof(log->crashlog_filename));
log->WriteScreenshot(log->screenshot_filename, lastof(log->screenshot_filename));
/* Close any possible log files */
CloseConsoleLogIfActive();
if ((VideoDriver::GetInstance() == NULL || VideoDriver::GetInstance()->HasGUI()) && _safe_esp != NULL) {
#ifdef _M_AMD64
ep->ContextRecord->Rip = (DWORD64)ShowCrashlogWindow;
ep->ContextRecord->Rsp = (DWORD64)_safe_esp;
#else
ep->ContextRecord->Eip = (DWORD)ShowCrashlogWindow;
ep->ContextRecord->Esp = (DWORD)_safe_esp;
#endif
return EXCEPTION_CONTINUE_EXECUTION;
}
CrashLog::AfterCrashLogCleanup();
return EXCEPTION_EXECUTE_HANDLER;
}
static void CDECL CustomAbort(int signal)
{
RaiseException(0xE1212012, 0, 0, NULL);
}
/* static */ void CrashLog::InitialiseCrashLog()
{
#ifdef _M_AMD64
CONTEXT ctx;
RtlCaptureContext(&ctx);
/* The stack pointer for AMD64 must always be 16-byte aligned inside a
* function. As we are simulating a function call with the safe ESP value,
* we need to subtract 8 for the imaginary return address otherwise stack
* alignment would be wrong in the called function. */
_safe_esp = (void *)(ctx.Rsp - 8);
#else
#if defined(_MSC_VER)
_asm {
mov _safe_esp, esp
}
#else
asm("movl %esp, __safe_esp");
#endif
#endif
/* SIGABRT is not an unhandled exception, so we need to intercept it. */
signal(SIGABRT, CustomAbort);
#if defined(_MSC_VER)
/* Don't show abort message as we will get the crashlog window anyway. */
_set_abort_behavior(0, _WRITE_ABORT_MSG);
#endif
SetUnhandledExceptionFilter(ExceptionHandler);
}
/* The crash log GUI */
static bool _expanded;
static const TCHAR _crash_desc[] =
_T("A serious fault condition occurred in the game. The game will shut down.\n")
_T("Please send the crash information and the crash.dmp file (if any) to the developers.\n")
_T("This will greatly help debugging. The correct place to do this is http://bugs.openttd.org. ")
_T("The information contained in the report is displayed below.\n")
_T("Press \"Emergency save\" to attempt saving the game. Generated file(s):\n")
_T("%s");
static const TCHAR _save_succeeded[] =
_T("Emergency save succeeded.\nIts location is '%s'.\n")
_T("Be aware that critical parts of the internal game state may have become ")
_T("corrupted. The saved game is not guaranteed to work.");
static const TCHAR * const _expand_texts[] = {_T("S&how report >>"), _T("&Hide report <<") };
static void SetWndSize(HWND wnd, int mode)
{
RECT r, r2;
GetWindowRect(wnd, &r);
SetDlgItemText(wnd, 15, _expand_texts[mode == 1]);
if (mode >= 0) {
GetWindowRect(GetDlgItem(wnd, 11), &r2);
int offs = r2.bottom - r2.top + 10;
if (mode == 0) offs = -offs;
SetWindowPos(wnd, HWND_TOPMOST, 0, 0,
r.right - r.left, r.bottom - r.top + offs, SWP_NOMOVE | SWP_NOZORDER);
} else {
SetWindowPos(wnd, HWND_TOPMOST,
(GetSystemMetrics(SM_CXSCREEN) - (r.right - r.left)) / 2,
(GetSystemMetrics(SM_CYSCREEN) - (r.bottom - r.top)) / 2,
0, 0, SWP_NOSIZE);
}
}
/* When TCHAR is char, then _sntprintf becomes snprintf. When TCHAR is wchar it doesn't. Likewise for strcat. */
#undef snprintf
#undef strcat
static INT_PTR CALLBACK CrashDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_INITDIALOG: {
/* We need to put the crash-log in a separate buffer because the default
* buffer in MB_TO_WIDE is not large enough (512 chars) */
TCHAR crash_msgW[lengthof(CrashLogWindows::current->crashlog)];
/* Convert unix -> dos newlines because the edit box only supports that properly :( */
const char *unix_nl = CrashLogWindows::current->crashlog;
char dos_nl[lengthof(CrashLogWindows::current->crashlog)];
char *p = dos_nl;
WChar c;
while ((c = Utf8Consume(&unix_nl)) && p < lastof(dos_nl) - 4) { // 4 is max number of bytes per character
if (c == '\n') p += Utf8Encode(p, '\r');
p += Utf8Encode(p, c);
}
*p = '\0';
/* Add path to crash.log and crash.dmp (if any) to the crash window text */
size_t len = _tcslen(_crash_desc) + 2;
len += _tcslen(OTTD2FS(CrashLogWindows::current->crashlog_filename)) + 2;
len += _tcslen(OTTD2FS(CrashLogWindows::current->crashdump_filename)) + 2;
len += _tcslen(OTTD2FS(CrashLogWindows::current->screenshot_filename)) + 1;
TCHAR *text = AllocaM(TCHAR, len);
_sntprintf(text, len, _crash_desc, OTTD2FS(CrashLogWindows::current->crashlog_filename));
if (OTTD2FS(CrashLogWindows::current->crashdump_filename)[0] != _T('\0')) {
_tcscat(text, _T("\n"));
_tcscat(text, OTTD2FS(CrashLogWindows::current->crashdump_filename));
}
if (OTTD2FS(CrashLogWindows::current->screenshot_filename)[0] != _T('\0')) {
_tcscat(text, _T("\n"));
_tcscat(text, OTTD2FS(CrashLogWindows::current->screenshot_filename));
}
SetDlgItemText(wnd, 10, text);
SetDlgItemText(wnd, 11, convert_to_fs(dos_nl, crash_msgW, lengthof(crash_msgW)));
SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE);
SetWndSize(wnd, -1);
} return TRUE;
case WM_COMMAND:
switch (wParam) {
case 12: // Close
CrashLog::AfterCrashLogCleanup();
ExitProcess(2);
case 13: // Emergency save
char filename[MAX_PATH];
if (CrashLogWindows::current->WriteSavegame(filename, lastof(filename))) {
size_t len = _tcslen(_save_succeeded) + _tcslen(OTTD2FS(filename)) + 1;
TCHAR *text = AllocaM(TCHAR, len);
_sntprintf(text, len, _save_succeeded, OTTD2FS(filename));
MessageBox(wnd, text, _T("Save successful"), MB_ICONINFORMATION);
} else {
MessageBox(wnd, _T("Save failed"), _T("Save failed"), MB_ICONINFORMATION);
}
break;
case 15: // Expand window to show crash-message
_expanded ^= 1;
SetWndSize(wnd, _expanded);
break;
}
return TRUE;
case WM_CLOSE:
CrashLog::AfterCrashLogCleanup();
ExitProcess(2);
}
return FALSE;
}
static void ShowCrashlogWindow()
{
ShowCursor(TRUE);
ShowWindow(GetActiveWindow(), FALSE);
DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(100), NULL, CrashDialogFunc);
}

View File

@@ -0,0 +1,121 @@
//Microsoft Developer Studio generated resource script.
// $Id$
//
// This file is part of OpenTTD.
// 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.
// 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.
// 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/>.
//
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#define APSTUDIO_READONLY_SYMBOLS
#define APSTUDIO_HIDDEN_SYMBOLS
#include "windows.h"
#undef APSTUDIO_HIDDEN_SYMBOLS
#ifdef MSVC
#include "winres.h"
#else
#define IDC_STATIC (-1) // all static controls
#endif
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// Neutral (Default) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEUD)
#ifdef _WIN32
LANGUAGE LANG_NEUTRAL, SUBLANG_DEFAULT
#pragma code_page(1252)
#endif //_WIN32
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
100 ICON DISCARDABLE "../../../media/openttd.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Dialog
//
100 DIALOG DISCARDABLE 0, 0, 305, 99
STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Fatal Application Failure"
FONT 8, "MS Sans Serif"
BEGIN
PUSHBUTTON "&Close",12,7,80,50,14
PUSHBUTTON "&Emergency save",13,155,80,68,14
PUSHBUTTON "",15,243,80,55,14
EDITTEXT 11,7,101,291,118,ES_MULTILINE | ES_READONLY | WS_VSCROLL |
WS_HSCROLL | NOT WS_TABSTOP
LTEXT "",10,36,7,262,65
ICON 100,IDC_STATIC,9,9,20,20
END
101 DIALOG DISCARDABLE 0, 0, 600, 400
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "OpenTTD command line help"
FONT 8, "MS Sans Serif"
BEGIN
DEFPUSHBUTTON "&OK",12,274,378,50,14,BS_CENTER
EDITTEXT 11,7,6,583,365,ES_MULTILINE | ES_READONLY | WS_VSCROLL | WS_HSCROLL
END
#ifndef _MAC
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,5,3,!!REVISION!!
PRODUCTVERSION 1,5,3,!!REVISION!!
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
FILEFLAGS 0x1L
#else
FILEFLAGS 0x0L
#endif
FILEOS 0x4L
FILETYPE 0x1L
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "000004b0"
BEGIN
VALUE "Comments", "This program is licensed under the GNU General Public License version 2.\0"
VALUE "CompanyName", "OpenTTD Development Team\0"
VALUE "FileDescription", "OpenTTD\0"
VALUE "FileVersion", "!!VERSION!!\0"
VALUE "InternalName", "openttd\0"
VALUE "LegalCopyright", "Copyright \xA9 OpenTTD Developers 2002-2015. All Rights Reserved.\0"
VALUE "LegalTrademarks", "\0"
VALUE "OriginalFilename", "openttd.exe\0"
VALUE "PrivateBuild", "\0"
VALUE "ProductName", "OpenTTD\0"
VALUE "ProductVersion", "!!VERSION!!\0"
VALUE "SpecialBuild", "-\0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x0, 1200
END
END
#endif // !_MAC
#endif // Neutral (Default) resources
/////////////////////////////////////////////////////////////////////////////

777
src/os/windows/win32.cpp Normal file
View File

@@ -0,0 +1,777 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file win32.cpp Implementation of MS Windows system calls */
#include "../../stdafx.h"
#include "../../debug.h"
#include "../../gfx_func.h"
#include "../../textbuf_gui.h"
#include "../../fileio_func.h"
#include "../../fios.h"
#include <windows.h>
#include <fcntl.h>
#include <regstr.h>
#include <shlobj.h> /* SHGetFolderPath */
#include <shellapi.h>
#include "win32.h"
#include "../../core/alloc_func.hpp"
#include "../../openttd.h"
#include "../../core/random_func.hpp"
#include "../../string_func.h"
#include "../../crashlog.h"
#include <errno.h>
#include <sys/stat.h>
/* Due to TCHAR, strncat and strncpy have to remain (for a while). */
#include "../../safeguards.h"
#undef strncat
#undef strncpy
static bool _has_console;
static bool _cursor_disable = true;
static bool _cursor_visible = true;
bool MyShowCursor(bool show, bool toggle)
{
if (toggle) _cursor_disable = !_cursor_disable;
if (_cursor_disable) return show;
if (_cursor_visible == show) return show;
_cursor_visible = show;
ShowCursor(show);
return !show;
}
/**
* Helper function needed by dynamically loading libraries
* XXX: Hurray for MS only having an ANSI GetProcAddress function
* on normal windows and no Wide version except for in Windows Mobile/CE
*/
bool LoadLibraryList(Function proc[], const char *dll)
{
while (*dll != '\0') {
HMODULE lib;
lib = LoadLibrary(MB_TO_WIDE(dll));
if (lib == NULL) return false;
for (;;) {
FARPROC p;
while (*dll++ != '\0') { /* Nothing */ }
if (*dll == '\0') break;
#if defined(WINCE)
p = GetProcAddress(lib, MB_TO_WIDE(dll));
#else
p = GetProcAddress(lib, dll);
#endif
if (p == NULL) return false;
*proc++ = (Function)p;
}
dll++;
}
return true;
}
void ShowOSErrorBox(const char *buf, bool system)
{
MyShowCursor(true);
MessageBox(GetActiveWindow(), OTTD2FS(buf), _T("Error!"), MB_ICONSTOP);
}
void OSOpenBrowser(const char *url)
{
ShellExecute(GetActiveWindow(), _T("open"), OTTD2FS(url), NULL, NULL, SW_SHOWNORMAL);
}
/* Code below for windows version of opendir/readdir/closedir copied and
* modified from Jan Wassenberg's GPL implementation posted over at
* http://www.gamedev.net/community/forums/topic.asp?topic_id=364584&whichpage=1&#2398903 */
struct DIR {
HANDLE hFind;
/* the dirent returned by readdir.
* note: having only one global instance is not possible because
* multiple independent opendir/readdir sequences must be supported. */
dirent ent;
WIN32_FIND_DATA fd;
/* since opendir calls FindFirstFile, we need a means of telling the
* first call to readdir that we already have a file.
* that's the case iff this is true */
bool at_first_entry;
};
/* suballocator - satisfies most requests with a reusable static instance.
* this avoids hundreds of alloc/free which would fragment the heap.
* To guarantee concurrency, we fall back to malloc if the instance is
* already in use (it's important to avoid surprises since this is such a
* low-level routine). */
static DIR _global_dir;
static LONG _global_dir_is_in_use = false;
static inline DIR *dir_calloc()
{
DIR *d;
if (InterlockedExchange(&_global_dir_is_in_use, true) == (LONG)true) {
d = CallocT<DIR>(1);
} else {
d = &_global_dir;
memset(d, 0, sizeof(*d));
}
return d;
}
static inline void dir_free(DIR *d)
{
if (d == &_global_dir) {
_global_dir_is_in_use = (LONG)false;
} else {
free(d);
}
}
DIR *opendir(const TCHAR *path)
{
DIR *d;
UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // disable 'no-disk' message box
DWORD fa = GetFileAttributes(path);
if ((fa != INVALID_FILE_ATTRIBUTES) && (fa & FILE_ATTRIBUTE_DIRECTORY)) {
d = dir_calloc();
if (d != NULL) {
TCHAR search_path[MAX_PATH];
bool slash = path[_tcslen(path) - 1] == '\\';
/* build search path for FindFirstFile, try not to append additional slashes
* as it throws Win9x off its groove for root directories */
_sntprintf(search_path, lengthof(search_path), _T("%s%s*"), path, slash ? _T("") : _T("\\"));
*lastof(search_path) = '\0';
d->hFind = FindFirstFile(search_path, &d->fd);
if (d->hFind != INVALID_HANDLE_VALUE ||
GetLastError() == ERROR_NO_MORE_FILES) { // the directory is empty
d->ent.dir = d;
d->at_first_entry = true;
} else {
dir_free(d);
d = NULL;
}
} else {
errno = ENOMEM;
}
} else {
/* path not found or not a directory */
d = NULL;
errno = ENOENT;
}
SetErrorMode(sem); // restore previous setting
return d;
}
struct dirent *readdir(DIR *d)
{
DWORD prev_err = GetLastError(); // avoid polluting last error
if (d->at_first_entry) {
/* the directory was empty when opened */
if (d->hFind == INVALID_HANDLE_VALUE) return NULL;
d->at_first_entry = false;
} else if (!FindNextFile(d->hFind, &d->fd)) { // determine cause and bail
if (GetLastError() == ERROR_NO_MORE_FILES) SetLastError(prev_err);
return NULL;
}
/* This entry has passed all checks; return information about it.
* (note: d_name is a pointer; see struct dirent definition) */
d->ent.d_name = d->fd.cFileName;
return &d->ent;
}
int closedir(DIR *d)
{
FindClose(d->hFind);
dir_free(d);
return 0;
}
bool FiosIsRoot(const char *file)
{
return file[3] == '\0'; // C:\...
}
void FiosGetDrives()
{
#if defined(WINCE)
/* WinCE only knows one drive: / */
FiosItem *fios = _fios_items.Append();
fios->type = FIOS_TYPE_DRIVE;
fios->mtime = 0;
seprintf(fios->name, lastof(fios->name), PATHSEP "");
strecpy(fios->title, fios->name, lastof(fios->title));
#else
TCHAR drives[256];
const TCHAR *s;
GetLogicalDriveStrings(lengthof(drives), drives);
for (s = drives; *s != '\0';) {
FiosItem *fios = _fios_items.Append();
fios->type = FIOS_TYPE_DRIVE;
fios->mtime = 0;
seprintf(fios->name, lastof(fios->name), "%c:", s[0] & 0xFF);
strecpy(fios->title, fios->name, lastof(fios->title));
while (*s++ != '\0') { /* Nothing */ }
}
#endif
}
bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb)
{
/* hectonanoseconds between Windows and POSIX epoch */
static const int64 posix_epoch_hns = 0x019DB1DED53E8000LL;
const WIN32_FIND_DATA *fd = &ent->dir->fd;
sb->st_size = ((uint64) fd->nFileSizeHigh << 32) + fd->nFileSizeLow;
/* UTC FILETIME to seconds-since-1970 UTC
* we just have to subtract POSIX epoch and scale down to units of seconds.
* http://www.gamedev.net/community/forums/topic.asp?topic_id=294070&whichpage=1&#1860504
* XXX - not entirely correct, since filetimes on FAT aren't UTC but local,
* this won't entirely be correct, but we use the time only for comparison. */
sb->st_mtime = (time_t)((*(const uint64*)&fd->ftLastWriteTime - posix_epoch_hns) / 1E7);
sb->st_mode = (fd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)? S_IFDIR : S_IFREG;
return true;
}
bool FiosIsHiddenFile(const struct dirent *ent)
{
return (ent->dir->fd.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) != 0;
}
bool FiosGetDiskFreeSpace(const char *path, uint64 *tot)
{
UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // disable 'no-disk' message box
bool retval = false;
TCHAR root[4];
DWORD spc, bps, nfc, tnc;
_sntprintf(root, lengthof(root), _T("%c:") _T(PATHSEP), path[0]);
if (tot != NULL && GetDiskFreeSpace(root, &spc, &bps, &nfc, &tnc)) {
*tot = ((spc * bps) * (uint64)nfc);
retval = true;
}
SetErrorMode(sem); // reset previous setting
return retval;
}
static int ParseCommandLine(char *line, char **argv, int max_argc)
{
int n = 0;
do {
/* skip whitespace */
while (*line == ' ' || *line == '\t') line++;
/* end? */
if (*line == '\0') break;
/* special handling when quoted */
if (*line == '"') {
argv[n++] = ++line;
while (*line != '"') {
if (*line == '\0') return n;
line++;
}
} else {
argv[n++] = line;
while (*line != ' ' && *line != '\t') {
if (*line == '\0') return n;
line++;
}
}
*line++ = '\0';
} while (n != max_argc);
return n;
}
void CreateConsole()
{
#if defined(WINCE)
/* WinCE doesn't support console stuff */
#else
HANDLE hand;
CONSOLE_SCREEN_BUFFER_INFO coninfo;
if (_has_console) return;
_has_console = true;
AllocConsole();
hand = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hand, &coninfo);
coninfo.dwSize.Y = 500;
SetConsoleScreenBufferSize(hand, coninfo.dwSize);
/* redirect unbuffered STDIN, STDOUT, STDERR to the console */
#if !defined(__CYGWIN__)
/* Check if we can open a handle to STDOUT. */
int fd = _open_osfhandle((intptr_t)hand, _O_TEXT);
if (fd == -1) {
/* Free everything related to the console. */
FreeConsole();
_has_console = false;
_close(fd);
CloseHandle(hand);
ShowInfo("Unable to open an output handle to the console. Check known-bugs.txt for details.");
return;
}
*stdout = *_fdopen(fd, "w");
*stdin = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT), "r" );
*stderr = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT), "w" );
#else
/* open_osfhandle is not in cygwin */
*stdout = *fdopen(1, "w" );
*stdin = *fdopen(0, "r" );
*stderr = *fdopen(2, "w" );
#endif
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
#endif
}
/** Temporary pointer to get the help message to the window */
static const char *_help_msg;
/** Callback function to handle the window */
static INT_PTR CALLBACK HelpDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_INITDIALOG: {
char help_msg[8192];
const char *p = _help_msg;
char *q = help_msg;
while (q != lastof(help_msg) && *p != '\0') {
if (*p == '\n') {
*q++ = '\r';
if (q == lastof(help_msg)) {
q[-1] = '\0';
break;
}
}
*q++ = *p++;
}
*q = '\0';
/* We need to put the text in a separate buffer because the default
* buffer in OTTD2FS might not be large enough (512 chars). */
TCHAR help_msg_buf[8192];
SetDlgItemText(wnd, 11, convert_to_fs(help_msg, help_msg_buf, lengthof(help_msg_buf)));
SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE);
} return TRUE;
case WM_COMMAND:
if (wParam == 12) ExitProcess(0);
return TRUE;
case WM_CLOSE:
ExitProcess(0);
}
return FALSE;
}
void ShowInfo(const char *str)
{
if (_has_console) {
fprintf(stderr, "%s\n", str);
} else {
bool old;
ReleaseCapture();
_left_button_clicked = _left_button_down = false;
old = MyShowCursor(true);
if (strlen(str) > 2048) {
/* The minimum length of the help message is 2048. Other messages sent via
* ShowInfo are much shorter, or so long they need this way of displaying
* them anyway. */
_help_msg = str;
DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(101), NULL, HelpDialogFunc);
} else {
/* We need to put the text in a separate buffer because the default
* buffer in OTTD2FS might not be large enough (512 chars). */
TCHAR help_msg_buf[8192];
MessageBox(GetActiveWindow(), convert_to_fs(str, help_msg_buf, lengthof(help_msg_buf)), _T("OpenTTD"), MB_ICONINFORMATION | MB_OK);
}
MyShowCursor(old);
}
}
#if defined(WINCE)
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
#else
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
#endif
{
int argc;
char *argv[64]; // max 64 command line arguments
CrashLog::InitialiseCrashLog();
#if defined(UNICODE) && !defined(WINCE)
/* Check if a win9x user started the win32 version */
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.");
#endif
/* Convert the command line to UTF-8. We need a dedicated buffer
* for this because argv[] points into this buffer and this needs to
* be available between subsequent calls to FS2OTTD(). */
char *cmdline = stredup(FS2OTTD(GetCommandLine()));
#if defined(_DEBUG)
CreateConsole();
#endif
#if !defined(WINCE)
_set_error_mode(_OUT_TO_MSGBOX); // force assertion output to messagebox
#endif
/* setup random seed to something quite random */
SetRandomSeed(GetTickCount());
argc = ParseCommandLine(cmdline, argv, lengthof(argv));
openttd_main(argc, argv);
free(cmdline);
return 0;
}
#if defined(WINCE)
void GetCurrentDirectoryW(int length, wchar_t *path)
{
/* Get the name of this module */
GetModuleFileName(NULL, path, length);
/* Remove the executable name, this we call CurrentDir */
wchar_t *pDest = wcsrchr(path, '\\');
if (pDest != NULL) {
int result = pDest - path + 1;
path[result] = '\0';
}
}
#endif
char *getcwd(char *buf, size_t size)
{
#if defined(WINCE)
TCHAR path[MAX_PATH];
GetModuleFileName(NULL, path, MAX_PATH);
convert_from_fs(path, buf, size);
/* GetModuleFileName returns dir with file, so remove everything behind latest '\\' */
char *p = strrchr(buf, '\\');
if (p != NULL) *p = '\0';
#else
TCHAR path[MAX_PATH];
GetCurrentDirectory(MAX_PATH - 1, path);
convert_from_fs(path, buf, size);
#endif
return buf;
}
void DetermineBasePaths(const char *exe)
{
char tmp[MAX_PATH];
TCHAR path[MAX_PATH];
#ifdef WITH_PERSONAL_DIR
if (SUCCEEDED(OTTDSHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, path))) {
strecpy(tmp, FS2OTTD(path), lastof(tmp));
AppendPathSeparator(tmp, lastof(tmp));
strecat(tmp, PERSONAL_DIR, lastof(tmp));
AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_PERSONAL_DIR] = stredup(tmp);
} else {
_searchpaths[SP_PERSONAL_DIR] = NULL;
}
if (SUCCEEDED(OTTDSHGetFolderPath(NULL, CSIDL_COMMON_DOCUMENTS, NULL, SHGFP_TYPE_CURRENT, path))) {
strecpy(tmp, FS2OTTD(path), lastof(tmp));
AppendPathSeparator(tmp, lastof(tmp));
strecat(tmp, PERSONAL_DIR, lastof(tmp));
AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_SHARED_DIR] = stredup(tmp);
} else {
_searchpaths[SP_SHARED_DIR] = NULL;
}
#else
_searchpaths[SP_PERSONAL_DIR] = NULL;
_searchpaths[SP_SHARED_DIR] = NULL;
#endif
/* Get the path to working directory of OpenTTD */
getcwd(tmp, lengthof(tmp));
AppendPathSeparator(tmp, lastof(tmp));
_searchpaths[SP_WORKING_DIR] = stredup(tmp);
if (!GetModuleFileName(NULL, path, lengthof(path))) {
DEBUG(misc, 0, "GetModuleFileName failed (%lu)\n", GetLastError());
_searchpaths[SP_BINARY_DIR] = NULL;
} else {
TCHAR exec_dir[MAX_PATH];
_tcsncpy(path, convert_to_fs(exe, path, lengthof(path)), lengthof(path));
if (!GetFullPathName(path, lengthof(exec_dir), exec_dir, NULL)) {
DEBUG(misc, 0, "GetFullPathName failed (%lu)\n", GetLastError());
_searchpaths[SP_BINARY_DIR] = NULL;
} else {
strecpy(tmp, convert_from_fs(exec_dir, tmp, lengthof(tmp)), lastof(tmp));
char *s = strrchr(tmp, PATHSEPCHAR);
*(s + 1) = '\0';
_searchpaths[SP_BINARY_DIR] = stredup(tmp);
}
}
_searchpaths[SP_INSTALLATION_DIR] = NULL;
_searchpaths[SP_APPLICATION_BUNDLE_DIR] = NULL;
}
bool GetClipboardContents(char *buffer, const char *last)
{
HGLOBAL cbuf;
const char *ptr;
if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
OpenClipboard(NULL);
cbuf = GetClipboardData(CF_UNICODETEXT);
ptr = (const char*)GlobalLock(cbuf);
int out_len = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)ptr, -1, buffer, (last - buffer) + 1, NULL, NULL);
GlobalUnlock(cbuf);
CloseClipboard();
if (out_len == 0) return false;
#if !defined(UNICODE)
} else if (IsClipboardFormatAvailable(CF_TEXT)) {
OpenClipboard(NULL);
cbuf = GetClipboardData(CF_TEXT);
ptr = (const char*)GlobalLock(cbuf);
strecpy(buffer, FS2OTTD(ptr), last);
GlobalUnlock(cbuf);
CloseClipboard();
#endif /* UNICODE */
} else {
return false;
}
return true;
}
void CSleep(int milliseconds)
{
Sleep(milliseconds);
}
/**
* Convert to OpenTTD's encoding from that of the local environment.
* When the project is built in UNICODE, the system codepage is irrelevant and
* the input string is wide. In ANSI mode, the string is in the
* local codepage which we'll convert to wide-char, and then to UTF-8.
* OpenTTD internal encoding is UTF8.
* The returned value's contents can only be guaranteed until the next call to
* this function. So if the value is needed for anything else, use convert_from_fs
* @param name pointer to a valid string that will be converted (local, or wide)
* @return pointer to the converted string; if failed string is of zero-length
* @see the current code-page comes from video\win32_v.cpp, event-notification
* WM_INPUTLANGCHANGE
*/
const char *FS2OTTD(const TCHAR *name)
{
static char utf8_buf[512];
return convert_from_fs(name, utf8_buf, lengthof(utf8_buf));
}
/**
* Convert from OpenTTD's encoding to that of the local environment.
* When the project is built in UNICODE the system codepage is irrelevant and
* the converted string is wide. In ANSI mode, the UTF8 string is converted
* to multi-byte.
* OpenTTD internal encoding is UTF8.
* The returned value's contents can only be guaranteed until the next call to
* this function. So if the value is needed for anything else, use convert_from_fs
* @param name pointer to a valid string that will be converted (UTF8)
* @param console_cp convert to the console encoding instead of the normal system encoding.
* @return pointer to the converted string; if failed string is of zero-length
*/
const TCHAR *OTTD2FS(const char *name, bool console_cp)
{
static TCHAR system_buf[512];
return convert_to_fs(name, system_buf, lengthof(system_buf), console_cp);
}
/**
* Convert to OpenTTD's encoding from that of the environment in
* UNICODE. OpenTTD encoding is UTF8, local is wide
* @param name pointer to a valid string that will be converted
* @param utf8_buf pointer to a valid buffer that will receive the converted string
* @param buflen length in characters of the receiving buffer
* @return pointer to utf8_buf. If conversion fails the string is of zero-length
*/
char *convert_from_fs(const TCHAR *name, char *utf8_buf, size_t buflen)
{
#if defined(UNICODE)
const WCHAR *wide_buf = name;
#else
/* Convert string from the local codepage to UTF-16. */
int wide_len = MultiByteToWideChar(CP_ACP, 0, name, -1, NULL, 0);
if (wide_len == 0) {
utf8_buf[0] = '\0';
return utf8_buf;
}
WCHAR *wide_buf = AllocaM(WCHAR, wide_len);
MultiByteToWideChar(CP_ACP, 0, name, -1, wide_buf, wide_len);
#endif
/* Convert UTF-16 string to UTF-8. */
int len = WideCharToMultiByte(CP_UTF8, 0, wide_buf, -1, utf8_buf, (int)buflen, NULL, NULL);
if (len == 0) utf8_buf[0] = '\0';
return utf8_buf;
}
/**
* Convert from OpenTTD's encoding to that of the environment in
* UNICODE. OpenTTD encoding is UTF8, local is wide
* @param name pointer to a valid string that will be converted
* @param utf16_buf pointer to a valid wide-char buffer that will receive the
* converted string
* @param buflen length in wide characters of the receiving buffer
* @param console_cp convert to the console encoding instead of the normal system encoding.
* @return pointer to utf16_buf. If conversion fails the string is of zero-length
*/
TCHAR *convert_to_fs(const char *name, TCHAR *system_buf, size_t buflen, bool console_cp)
{
#if defined(UNICODE)
int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, system_buf, (int)buflen);
if (len == 0) system_buf[0] = '\0';
#else
int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, NULL, 0);
if (len == 0) {
system_buf[0] = '\0';
return system_buf;
}
WCHAR *wide_buf = AllocaM(WCHAR, len);
MultiByteToWideChar(CP_UTF8, 0, name, -1, wide_buf, len);
len = WideCharToMultiByte(console_cp ? CP_OEMCP : CP_ACP, 0, wide_buf, len, system_buf, (int)buflen, NULL, NULL);
if (len == 0) system_buf[0] = '\0';
#endif
return system_buf;
}
/**
* Our very own SHGetFolderPath function for support of windows operating
* systems that don't have this function (eg Win9x, etc.). We try using the
* native function, and if that doesn't exist we will try a more crude approach
* of environment variables and hope for the best
*/
HRESULT OTTDSHGetFolderPath(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPTSTR pszPath)
{
static HRESULT (WINAPI *SHGetFolderPath)(HWND, int, HANDLE, DWORD, LPTSTR) = NULL;
static bool first_time = true;
/* We only try to load the library one time; if it fails, it fails */
if (first_time) {
#if defined(UNICODE)
# define W(x) x "W"
#else
# define W(x) x "A"
#endif
/* The function lives in shell32.dll for all current Windows versions, but it first started to appear in SHFolder.dll. */
if (!LoadLibraryList((Function*)&SHGetFolderPath, "shell32.dll\0" W("SHGetFolderPath") "\0\0")) {
if (!LoadLibraryList((Function*)&SHGetFolderPath, "SHFolder.dll\0" W("SHGetFolderPath") "\0\0")) {
DEBUG(misc, 0, "Unable to load " W("SHGetFolderPath") "from either shell32.dll or SHFolder.dll");
}
}
#undef W
first_time = false;
}
if (SHGetFolderPath != NULL) return SHGetFolderPath(hwnd, csidl, hToken, dwFlags, pszPath);
/* SHGetFolderPath doesn't exist, try a more conservative approach,
* eg environment variables. This is only included for legacy modes
* MSDN says: that 'pszPath' is a "Pointer to a null-terminated string of
* length MAX_PATH which will receive the path" so let's assume that
* Windows 95 with Internet Explorer 5.0, Windows 98 with Internet Explorer 5.0,
* Windows 98 Second Edition (SE), Windows NT 4.0 with Internet Explorer 5.0,
* Windows NT 4.0 with Service Pack 4 (SP4) */
{
DWORD ret;
switch (csidl) {
case CSIDL_FONTS: // Get the system font path, eg %WINDIR%\Fonts
ret = GetEnvironmentVariable(_T("WINDIR"), pszPath, MAX_PATH);
if (ret == 0) break;
_tcsncat(pszPath, _T("\\Fonts"), MAX_PATH);
return (HRESULT)0;
case CSIDL_PERSONAL:
case CSIDL_COMMON_DOCUMENTS: {
HKEY key;
if (RegOpenKeyEx(csidl == CSIDL_PERSONAL ? HKEY_CURRENT_USER : HKEY_LOCAL_MACHINE, REGSTR_PATH_SPECIAL_FOLDERS, 0, KEY_READ, &key) != ERROR_SUCCESS) break;
DWORD len = MAX_PATH;
ret = RegQueryValueEx(key, csidl == CSIDL_PERSONAL ? _T("Personal") : _T("Common Documents"), NULL, NULL, (LPBYTE)pszPath, &len);
RegCloseKey(key);
if (ret == ERROR_SUCCESS) return (HRESULT)0;
break;
}
/* XXX - other types to go here when needed... */
}
}
return E_INVALIDARG;
}
/** Determine the current user's locale. */
const char *GetCurrentLocale(const char *)
{
char lang[9], country[9];
if (GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, lang, lengthof(lang)) == 0 ||
GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, country, lengthof(country)) == 0) {
/* Unable to retrieve the locale. */
return NULL;
}
/* Format it as 'en_us'. */
static char retbuf[6] = {lang[0], lang[1], '_', country[0], country[1], 0};
return retbuf;
}
uint GetCPUCoreCount()
{
SYSTEM_INFO info;
GetSystemInfo(&info);
return info.dwNumberOfProcessors;
}

42
src/os/windows/win32.h Normal file
View File

@@ -0,0 +1,42 @@
/* $Id$ */
/*
* This file is part of OpenTTD.
* 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.
* 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.
* 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/>.
*/
/** @file win32.h declarations of functions for MS windows systems */
#ifndef WIN32_H
#define WIN32_H
#include <windows.h>
bool MyShowCursor(bool show, bool toggle = false);
typedef void (*Function)(int);
bool LoadLibraryList(Function proc[], const char *dll);
char *convert_from_fs(const TCHAR *name, char *utf8_buf, size_t buflen);
TCHAR *convert_to_fs(const char *name, TCHAR *utf16_buf, size_t buflen, bool console_cp = false);
/* Function shortcuts for UTF-8 <> UNICODE conversion. When unicode is not
* defined these macros return the string passed to them, with UNICODE
* they return a pointer to the converted string. These functions use an
* internal buffer of max 512 characters. */
#if defined(UNICODE)
# define MB_TO_WIDE(str) OTTD2FS(str)
# define WIDE_TO_MB(str) FS2OTTD(str)
#else
# define MB_TO_WIDE(str) (str)
# define WIDE_TO_MB(str) (str)
#endif
HRESULT OTTDSHGetFolderPath(HWND, int, HANDLE, DWORD, LPTSTR);
#if defined(__MINGW32__) && !defined(__MINGW64__)
#define SHGFP_TYPE_CURRENT 0
#endif /* __MINGW32__ */
#endif /* WIN32_H */