Merge branch 'master' into jgrpp

# Conflicts:
#	os/macosx/notarize.sh
#	src/3rdparty/CMakeLists.txt
#	src/3rdparty/squirrel/squirrel/sqcompiler.cpp
#	src/3rdparty/squirrel/squirrel/sqdebug.cpp
#	src/3rdparty/squirrel/squirrel/sqvm.cpp
#	src/console_cmds.cpp
#	src/core/span_type.hpp
#	src/crashlog.cpp
#	src/currency.h
#	src/date_gui.cpp
#	src/driver.cpp
#	src/fios.cpp
#	src/genworld_gui.cpp
#	src/hotkeys.cpp
#	src/misc_gui.cpp
#	src/music/os2_m.cpp
#	src/network/core/os_abstraction.h
#	src/network/network_server.cpp
#	src/newgrf.cpp
#	src/newgrf_config.h
#	src/newgrf_text.cpp
#	src/openttd.cpp
#	src/os/macosx/font_osx.cpp
#	src/os/macosx/misc_osx.cpp
#	src/os/os2/CMakeLists.txt
#	src/os/os2/os2.cpp
#	src/os/unix/CMakeLists.txt
#	src/os/windows/font_win32.cpp
#	src/os/windows/win32_main.cpp
#	src/saveload/saveload.cpp
#	src/script/api/script_text.cpp
#	src/settings.cpp
#	src/settings_gui.cpp
#	src/stdafx.h
#	src/strings.cpp
#	src/timetable_gui.cpp
#	src/town_gui.cpp
#	src/train_cmd.cpp
#	src/video/dedicated_v.cpp
#	src/video/video_driver.cpp
#	src/video/win32_v.cpp
#	src/viewport.cpp
#	src/waypoint_gui.cpp
#	src/widgets/dropdown_type.h
#	src/window.cpp
#	src/window_gui.h
This commit is contained in:
Jonathan G Rennison
2023-09-12 20:06:47 +01:00
242 changed files with 4733 additions and 6402 deletions

View File

@@ -1,4 +1,3 @@
add_subdirectory(macosx)
add_subdirectory(os2)
add_subdirectory(unix)
add_subdirectory(windows)

View File

@@ -24,72 +24,26 @@
#include "safeguards.h"
#ifdef WITH_FREETYPE
#include <ft2build.h>
#include FT_FREETYPE_H
extern FT_Library _library;
FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
{
FT_Error err = FT_Err_Cannot_Open_Resource;
/* Get font reference from name. */
UInt8 file_path[PATH_MAX];
OSStatus os_err = -1;
CFAutoRelease<CFStringRef> name(CFStringCreateWithCString(kCFAllocatorDefault, font_name, kCFStringEncodingUTF8));
/* Simply creating the font using CTFontCreateWithNameAndSize will *always* return
* something, no matter the name. As such, we can't use it to check for existence.
* We instead query the list of all font descriptors that match the given name which
* does not do this stupid name fallback. */
CFAutoRelease<CTFontDescriptorRef> name_desc(CTFontDescriptorCreateWithNameAndSize(name.get(), 0.0));
CFAutoRelease<CFSetRef> mandatory_attribs(CFSetCreate(kCFAllocatorDefault, const_cast<const void **>(reinterpret_cast<const void *const *>(&kCTFontNameAttribute)), 1, &kCFTypeSetCallBacks));
CFAutoRelease<CFArrayRef> descs(CTFontDescriptorCreateMatchingFontDescriptors(name_desc.get(), mandatory_attribs.get()));
/* Loop over all matches until we can get a path for one of them. */
for (CFIndex i = 0; descs.get() != nullptr && i < CFArrayGetCount(descs.get()) && os_err != noErr; i++) {
CFAutoRelease<CTFontRef> font(CTFontCreateWithFontDescriptor((CTFontDescriptorRef)CFArrayGetValueAtIndex(descs.get(), i), 0.0, nullptr));
CFAutoRelease<CFURLRef> fontURL((CFURLRef)CTFontCopyAttribute(font.get(), kCTFontURLAttribute));
if (CFURLGetFileSystemRepresentation(fontURL.get(), true, file_path, lengthof(file_path))) os_err = noErr;
}
if (os_err == noErr) {
DEBUG(fontcache, 3, "Font path for %s: %s", font_name, file_path);
err = FT_New_Face(_library, (const char *)file_path, 0, face);
}
return err;
}
#endif /* WITH_FREETYPE */
bool SetFallbackFont(FontCacheSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback)
bool SetFallbackFont(FontCacheSettings *settings, const std::string &language_isocode, int winlangid, MissingGlyphSearcher *callback)
{
/* Determine fallback font using CoreText. This uses the language isocode
* to find a suitable font. CoreText is available from 10.5 onwards. */
char lang[16];
if (strcmp(language_isocode, "zh_TW") == 0) {
std::string lang;
if (language_isocode == "zh_TW") {
/* Traditional Chinese */
strecpy(lang, "zh-Hant", lastof(lang));
} else if (strcmp(language_isocode, "zh_CN") == 0) {
lang = "zh-Hant";
} else if (language_isocode == "zh_CN") {
/* Simplified Chinese */
strecpy(lang, "zh-Hans", lastof(lang));
lang = "zh-Hans";
} else {
/* Just copy the first part of the isocode. */
strecpy(lang, language_isocode, lastof(lang));
char *sep = strchr(lang, '_');
if (sep != nullptr) *sep = '\0';
lang = language_isocode.substr(0, language_isocode.find('_'));
}
/* Create a font descriptor matching the wanted language and latin (english) glyphs.
* Can't use CFAutoRelease here for everything due to the way the dictionary has to be created. */
CFStringRef lang_codes[2];
lang_codes[0] = CFStringCreateWithCString(kCFAllocatorDefault, lang, kCFStringEncodingUTF8);
lang_codes[0] = CFStringCreateWithCString(kCFAllocatorDefault, lang.c_str(), kCFStringEncodingUTF8);
lang_codes[1] = CFSTR("en");
CFArrayRef lang_arr = CFArrayCreate(kCFAllocatorDefault, (const void **)lang_codes, lengthof(lang_codes), &kCFTypeArrayCallBacks);
CFAutoRelease<CFDictionaryRef> lang_attribs(CFDictionaryCreate(kCFAllocatorDefault, const_cast<const void **>(reinterpret_cast<const void *const *>(&kCTFontLanguagesAttribute)), (const void **)&lang_arr, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));

View File

@@ -1,4 +0,0 @@
add_files(
os2.cpp
CONDITION OPTION_OS2
)

View File

@@ -1,219 +0,0 @@
/*
* 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 "../../thread.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(FileList &file_list)
{
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 = file_list.Append();
fios->type = FIOS_TYPE_DRIVE;
fios->mtime = 0;
#ifndef __INNOTEK_LIBC__
fios->name += 'A' + disk - 1;
#else
fios->name += (char)disk;
#endif
fios->name += ':';
fios->title = fios->name;
}
}
/* Restore the original drive */
#ifndef __INNOTEK_LIBC__
_dos_setdrive(save, &total);
#else
chdir(wd);
#endif
}
std::optional<uint64_t> FiosGetDiskFreeSpace(const std::string &path)
{
#ifndef __INNOTEK_LIBC__
struct diskfree_t free;
char drive = path[0] - 'A' + 1;
if (_getdiskfree(drive, &free) == 0) {
return free.avail_clusters * free.sectors_per_cluster * free.bytes_per_sector;
}
#elif defined(HAS_STATVFS)
struct statvfs s;
if (statvfs(path.c_str(), &s) == 0) return static_cast<uint64_t>(s.f_frsize) * s.f_bavail;
#endif
return std::nullopt;
}
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);
}
void DoOSAbort()
{
abort();
}
int CDECL main(int argc, char *argv[])
{
SetRandomSeed(time(nullptr));
/* Make sure our arguments contain only valid UTF-8 characters. */
for (int i = 0; i < argc; i++) StrMakeValidInPlace(argv[i]);
return openttd_main(argc, argv);
}
std::optional<std::string> GetClipboardContents()
{
/* 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 != nullptr) {
std::string result = text;
WinCloseClipbrd(hab);
return result;
}
WinCloseClipbrd(hab);
}
#endif
return std::nullopt;
}
void OSOpenBrowser(const char *url)
{
// stub only
DEBUG(misc, 0, "Failed to open url: %s", url);
}
void SetCurrentThreadName(const char *)
{
}
int GetCurrentThreadName(char *str, const char *last) { return 0; }
void SetSelfAsMainThread() { }
void SetSelfAsGameThread() { }
void PerThreadSetup() { }
void PerThreadSetupInit() { }
bool IsMainThread() { return false; }
bool IsNonMainThread() { return false; }
bool IsGameThread() { return false; }
bool IsNonGameThread() { return false; }

View File

@@ -1,12 +1,12 @@
add_files(
crashlog_unix.cpp
survey_unix.cpp
CONDITION UNIX AND NOT APPLE AND NOT OPTION_OS2
CONDITION UNIX AND NOT APPLE
)
add_files(
unix.cpp
CONDITION UNIX AND NOT OPTION_OS2
CONDITION UNIX
)
add_files(

View File

@@ -17,13 +17,25 @@
#include "safeguards.h"
#ifdef WITH_FREETYPE
#include <ft2build.h>
#include FT_FREETYPE_H
extern FT_Library _library;
/**
* Split the font name into the font family and style. These fields are separated by a comma,
* but the style does not necessarily need to exist.
* @param font_name The font name.
* @return The font family and style.
*/
static std::tuple<std::string, std::string> SplitFontFamilyAndStyle(std::string_view font_name)
{
auto separator = font_name.find(',');
if (separator == std::string_view::npos) return { std::string(font_name), std::string() };
auto begin = font_name.find_first_not_of("\t ", separator + 1);
return { std::string(font_name.substr(0, separator)), std::string(font_name.substr(begin)) };
}
FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
{
@@ -37,39 +49,26 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
auto fc_instance = FcConfigReference(nullptr);
assert(fc_instance != nullptr);
FcPattern *match;
FcPattern *pat;
FcFontSet *fs;
FcResult result;
char *font_style;
char *font_family;
/* Split & strip the font's style */
font_family = stredup(font_name);
font_style = strchr(font_family, ',');
if (font_style != nullptr) {
font_style[0] = '\0';
font_style++;
while (*font_style == ' ' || *font_style == '\t') font_style++;
}
auto [font_family, font_style] = SplitFontFamilyAndStyle(font_name);
/* Resolve the name and populate the information structure */
pat = FcNameParse((FcChar8 *)font_family);
if (font_style != nullptr) FcPatternAddString(pat, FC_STYLE, (FcChar8 *)font_style);
FcPattern *pat = FcNameParse((FcChar8 *)font_family.data());
if (!font_style.empty()) FcPatternAddString(pat, FC_STYLE, (FcChar8 *)font_style.data());
FcConfigSubstitute(nullptr, pat, FcMatchPattern);
FcDefaultSubstitute(pat);
fs = FcFontSetCreate();
match = FcFontMatch(nullptr, pat, &result);
FcFontSet *fs = FcFontSetCreate();
FcResult result;
FcPattern *match = FcFontMatch(nullptr, pat, &result);
if (fs != nullptr && match != nullptr) {
int i;
FcChar8 *family;
FcChar8 *style;
FcChar8 *file;
int32_t index;
FcFontSetAdd(fs, match);
for (i = 0; err != FT_Err_Ok && i < fs->nfont; i++) {
for (int i = 0; err != FT_Err_Ok && i < fs->nfont; i++) {
/* Try the new filename */
if (FcPatternGetString(fs->fonts[i], FC_FILE, 0, &file) == FcResultMatch &&
FcPatternGetString(fs->fonts[i], FC_FAMILY, 0, &family) == FcResultMatch &&
@@ -77,7 +76,7 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
FcPatternGetInteger(fs->fonts[i], FC_INDEX, 0, &index) == FcResultMatch) {
/* The correct style? */
if (font_style != nullptr && !StrEqualsIgnoreCase(font_style, (char *)style)) continue;
if (!font_style.empty() && !StrEqualsIgnoreCase(font_style, (char *)style)) continue;
/* Font config takes the best shot, which, if the family name is spelled
* wrongly a 'random' font, so check whether the family name is the
@@ -89,7 +88,6 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
}
}
free(font_family);
FcPatternDestroy(pat);
FcFontSetDestroy(fs);
FcConfigDestroy(fc_instance);
@@ -97,10 +95,7 @@ FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
return err;
}
#endif /* WITH_FREETYPE */
bool SetFallbackFont(FontCacheSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback)
bool SetFallbackFont(FontCacheSettings *settings, const std::string &language_isocode, int winlangid, MissingGlyphSearcher *callback)
{
bool ret = false;
@@ -112,13 +107,10 @@ bool SetFallbackFont(FontCacheSettings *settings, const char *language_isocode,
/* Fontconfig doesn't handle full language isocodes, only the part
* before the _ of e.g. en_GB is used, so "remove" everything after
* the _. */
char lang[16];
seprintf(lang, lastof(lang), ":lang=%s", language_isocode);
char *split = strchr(lang, '_');
if (split != nullptr) *split = '\0';
std::string lang = ":lang=" + language_isocode.substr(0, language_isocode.find('_'));
/* First create a pattern to match the wanted language. */
FcPattern *pat = FcNameParse((FcChar8 *)lang);
FcPattern *pat = FcNameParse((const FcChar8 *)lang.c_str());
/* We only want to know the filename. */
FcObjectSet *os = FcObjectSetBuild(FC_FILE, FC_SPACING, FC_SLANT, FC_WEIGHT, nullptr);
/* Get the list of filenames matching the wanted language. */

View File

@@ -31,209 +31,6 @@
#include "safeguards.h"
#ifdef WITH_FREETYPE
#include <ft2build.h>
#include FT_FREETYPE_H
extern FT_Library _library;
/**
* Get the short DOS 8.3 format for paths.
* FreeType doesn't support Unicode filenames and Windows' fopen (as used
* by FreeType) doesn't support UTF-8 filenames. So we have to convert the
* filename into something that isn't UTF-8 but represents the Unicode file
* name. This is the short DOS 8.3 format. This does not contain any
* characters that fopen doesn't support.
* @param long_path the path in system encoding.
* @return the short path in ANSI (ASCII).
*/
static const char *GetShortPath(const wchar_t *long_path)
{
static char short_path[MAX_PATH];
wchar_t short_path_w[MAX_PATH];
GetShortPathName(long_path, short_path_w, lengthof(short_path_w));
WideCharToMultiByte(CP_ACP, 0, short_path_w, -1, short_path, lengthof(short_path), nullptr, nullptr);
return short_path;
}
/* Get the font file to be loaded into Freetype by looping the registry
* location where windows lists all installed fonts. Not very nice, will
* surely break if the registry path changes, but it works. Much better
* solution would be to use CreateFont, and extract the font data from it
* by GetFontData. The problem with this is that the font file needs to be
* kept in memory then until the font is no longer needed. This could mean
* an additional memory usage of 30MB (just for fonts!) when using an eastern
* font for all font sizes */
static const wchar_t *FONT_DIR_NT = L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts";
FT_Error GetFontByFaceName(const char *font_name, FT_Face *face)
{
FT_Error err = FT_Err_Cannot_Open_Resource;
HKEY hKey;
LONG ret;
wchar_t vbuffer[MAX_PATH], dbuffer[256];
wchar_t *pathbuf;
const char *font_path;
uint index;
size_t path_len;
ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, FONT_DIR_NT, 0, KEY_READ, &hKey);
if (ret != ERROR_SUCCESS) {
DEBUG(fontcache, 0, "Cannot open registry key HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts");
return err;
}
/* Convert font name to file system encoding. */
wchar_t *font_namep = wcsdup(OTTD2FS(font_name).c_str());
for (index = 0;; index++) {
wchar_t *s;
DWORD vbuflen = lengthof(vbuffer);
DWORD dbuflen = lengthof(dbuffer);
ret = RegEnumValue(hKey, index, vbuffer, &vbuflen, nullptr, nullptr, (byte *)dbuffer, &dbuflen);
if (ret != ERROR_SUCCESS) goto registry_no_font_found;
/* The font names in the registry are of the following 3 forms:
* - ADMUI3.fon
* - Book Antiqua Bold (TrueType)
* - Batang & BatangChe & Gungsuh & GungsuhChe (TrueType)
* We will strip the font-type '()' if any and work with the font name
* itself, which must match exactly; if...
* TTC files, font files which contain more than one font are separated
* by '&'. Our best bet will be to do substr match for the fontname
* and then let FreeType figure out which index to load */
s = wcschr(vbuffer, L'(');
if (s != nullptr) s[-1] = '\0';
if (wcschr(vbuffer, L'&') == nullptr) {
if (wcsicmp(vbuffer, font_namep) == 0) break;
} else {
if (wcsstr(vbuffer, font_namep) != nullptr) break;
}
}
if (!SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_FONTS, nullptr, SHGFP_TYPE_CURRENT, vbuffer))) {
DEBUG(fontcache, 0, "SHGetFolderPath cannot return fonts directory");
goto folder_error;
}
/* Some fonts are contained in .ttc files, TrueType Collection fonts. These
* contain multiple fonts inside this single file. GetFontData however
* returns the whole file, so we need to check each font inside to get the
* proper font. */
path_len = wcslen(vbuffer) + wcslen(dbuffer) + 2; // '\' and terminating nul.
pathbuf = AllocaM(wchar_t, path_len);
_snwprintf(pathbuf, path_len, L"%s\\%s", vbuffer, dbuffer);
/* Convert the path into something that FreeType understands. */
font_path = GetShortPath(pathbuf);
index = 0;
do {
err = FT_New_Face(_library, font_path, index, face);
if (err != FT_Err_Ok) break;
if (StrStartsWithIgnoreCase(font_name, (*face)->family_name)) break;
/* Try english name if font name failed */
if (StrStartsWithIgnoreCase(font_name + strlen(font_name) + 1, (*face)->family_name)) break;
err = FT_Err_Cannot_Open_Resource;
} while ((FT_Long)++index != (*face)->num_faces);
folder_error:
registry_no_font_found:
free(font_namep);
RegCloseKey(hKey);
return err;
}
/**
* Fonts can have localised names and when the system locale is the same as
* one of those localised names Windows will always return that localised name
* instead of allowing to get the non-localised (English US) name of the font.
* This will later on give problems as freetype uses the non-localised name of
* the font and we need to compare based on that name.
* Windows furthermore DOES NOT have an API to get the non-localised name nor
* can we override the system locale. This means that we have to actually read
* the font itself to gather the font name we want.
* Based on: http://blogs.msdn.com/michkap/archive/2006/02/13/530814.aspx
* @param logfont the font information to get the english name of.
* @return the English name (if it could be found).
*/
static std::string GetEnglishFontName(const ENUMLOGFONTEX *logfont)
{
static char font_name[MAX_PATH];
const char *ret_font_name = nullptr;
uint pos = 0;
HDC dc;
HGDIOBJ oldfont;
byte *buf;
DWORD dw;
uint16 format, count, stringOffset, platformId, encodingId, languageId, nameId, length, offset;
HFONT font = CreateFontIndirect(&logfont->elfLogFont);
if (font == nullptr) goto err1;
dc = GetDC(nullptr);
oldfont = SelectObject(dc, font);
dw = GetFontData(dc, 'eman', 0, nullptr, 0);
if (dw == GDI_ERROR) goto err2;
buf = MallocT<byte>(dw);
dw = GetFontData(dc, 'eman', 0, buf, dw);
if (dw == GDI_ERROR) goto err3;
format = buf[pos++] << 8;
format += buf[pos++];
assert(format == 0);
count = buf[pos++] << 8;
count += buf[pos++];
stringOffset = buf[pos++] << 8;
stringOffset += buf[pos++];
for (uint i = 0; i < count; i++) {
platformId = buf[pos++] << 8;
platformId += buf[pos++];
encodingId = buf[pos++] << 8;
encodingId += buf[pos++];
languageId = buf[pos++] << 8;
languageId += buf[pos++];
nameId = buf[pos++] << 8;
nameId += buf[pos++];
if (nameId != 1) {
pos += 4; // skip length and offset
continue;
}
length = buf[pos++] << 8;
length += buf[pos++];
offset = buf[pos++] << 8;
offset += buf[pos++];
/* Don't buffer overflow */
length = std::min<uint16>(length, MAX_PATH - 1);
for (uint j = 0; j < length; j++) font_name[j] = buf[stringOffset + offset + j];
font_name[length] = '\0';
if ((platformId == 1 && languageId == 0) || // Macintosh English
(platformId == 3 && languageId == 0x0409)) { // Microsoft English (US)
ret_font_name = font_name;
break;
}
}
err3:
free(buf);
err2:
SelectObject(dc, oldfont);
ReleaseDC(nullptr, dc);
DeleteObject(font);
err1:
return ret_font_name == nullptr ? FS2OTTD((const wchar_t *)logfont->elfFullName) : std::string(ret_font_name);
}
#endif /* WITH_FREETYPE */
struct EFCParam {
FontCacheSettings *settings;
LOCALESIGNATURE locale;
@@ -284,38 +81,13 @@ static int CALLBACK EnumFontCallback(const ENUMLOGFONTEX *logfont, const NEWTEXT
char font_name[MAX_PATH];
convert_from_fs((const wchar_t *)logfont->elfFullName, font_name, lengthof(font_name));
#ifdef WITH_FREETYPE
/* Add english name after font name */
std::string english_name = GetEnglishFontName(logfont);
strecpy(font_name + strlen(font_name) + 1, english_name.c_str(), lastof(font_name));
/* Check whether we can actually load the font. */
bool ft_init = _library != nullptr;
bool found = false;
FT_Face face;
/* Init FreeType if needed. */
if ((ft_init || FT_Init_FreeType(&_library) == FT_Err_Ok) && GetFontByFaceName(font_name, &face) == FT_Err_Ok) {
FT_Done_Face(face);
found = true;
}
if (!ft_init) {
/* Uninit FreeType if we did the init. */
FT_Done_FreeType(_library);
_library = nullptr;
}
if (!found) return 1;
#else
const char *english_name = font_name;
#endif /* WITH_FREETYPE */
info->callback->SetFontNames(info->settings, font_name, &logfont->elfLogFont);
if (info->callback->FindMissingGlyphs()) return 1;
DEBUG(fontcache, 1, "Fallback font: %s (%s)", font_name, english_name);
DEBUG(fontcache, 1, "Fallback font: %s", font_name);
return 0; // stop enumerating
}
bool SetFallbackFont(FontCacheSettings *settings, const char *language_isocode, int winlangid, MissingGlyphSearcher *callback)
bool SetFallbackFont(FontCacheSettings *settings, const std::string &language_isocode, int winlangid, MissingGlyphSearcher *callback)
{
DEBUG(fontcache, 1, "Trying fallback fonts");
EFCParam langInfo;

View File

@@ -429,10 +429,8 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLi
PerThreadSetupInit();
CrashLog::InitialiseCrashLog();
/* 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()).c_str());
/* Convert the command line to UTF-8. */
std::string cmdline = FS2OTTD(GetCommandLine());
/* Set the console codepage to UTF-8. */
SetConsoleOutputCP(CP_UTF8);
@@ -446,7 +444,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLi
/* setup random seed to something quite random */
SetRandomSeed(GetTickCount());
argc = ParseCommandLine(cmdline, argv, lengthof(argv));
argc = ParseCommandLine(cmdline.data(), argv, lengthof(argv));
/* Make sure our arguments contain only valid UTF-8 characters. */
for (int i = 0; i < argc; i++) StrMakeValidInPlace(argv[i]);
@@ -456,7 +454,6 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLi
/* Restore system timer resolution. */
timeEndPeriod(1);
free(cmdline);
return 0;
}
@@ -659,23 +656,21 @@ const char *GetCurrentLocale(const char *)
static WCHAR _cur_iso_locale[16] = L"";
void Win32SetCurrentLocaleName(const char *iso_code)
void Win32SetCurrentLocaleName(std::string iso_code)
{
/* Convert the iso code into the format that windows expects. */
char iso[16];
if (strcmp(iso_code, "zh_TW") == 0) {
strecpy(iso, "zh-Hant", lastof(iso));
} else if (strcmp(iso_code, "zh_CN") == 0) {
strecpy(iso, "zh-Hans", lastof(iso));
if (iso_code == "zh_TW") {
iso_code = "zh-Hant";
} else if (iso_code == "zh_CN") {
iso_code = "zh-Hans";
} else {
/* Windows expects a '-' between language and country code, but we use a '_'. */
strecpy(iso, iso_code, lastof(iso));
for (char *c = iso; *c != '\0'; c++) {
if (*c == '_') *c = '-';
for (char &c : iso_code) {
if (c == '_') c = '-';
}
}
MultiByteToWideChar(CP_UTF8, 0, iso, -1, _cur_iso_locale, lengthof(_cur_iso_locale));
MultiByteToWideChar(CP_UTF8, 0, iso_code.c_str(), -1, _cur_iso_locale, lengthof(_cur_iso_locale));
}
int OTTDStringCompare(std::string_view s1, std::string_view s2)