1
0
Fork 0

Compare commits

...

11 Commits

Author SHA1 Message Date
Colin Caine f22e163fb3
Merge 7b68c184fb into 1d38cbafcb 2025-07-13 23:12:27 +00:00
Peter Nelson 1d38cbafcb Codechange: Use unique_ptr for ScriptInfo instances.
Replaces raw pointers, slightly.
2025-07-14 00:10:14 +01:00
Peter Nelson 992d58d799 Codechange: Pass ScriptInfo by reference to IsSameScript. 2025-07-14 00:10:14 +01:00
Peter Nelson 8f34b7a821 Codechange: Keep Squirrel engine in unique_ptr. 2025-07-14 00:10:14 +01:00
Peter Nelson bf6d0c4934
Codechange: Don't pre-fill font metrics when loading fonts. (#14436)
Each font cache implementation sets its own metrics based on the loaded font, so there is no need to pre-fill with (unscaled, invalid) default metrics.
2025-07-13 23:38:31 +01:00
Michael Lutz 3c4fb21a5e
Fix: [Win32] Link failure with newer Windows SDK version due to WinRT changes. (#14432) 2025-07-13 22:34:32 +01:00
Colin Caine 7b68c184fb WIP 2025-06-17 18:00:40 +02:00
Colin Caine 2f4c5e6737 Codefix: outlined font and use shorter names 2025-06-17 14:52:36 +02:00
Colin Caine 016970154d Codefix: undo changes to scenario editor widget ids 2025-06-17 14:52:36 +02:00
Colin Caine a92619be89 Feature: WIP: Draw hotkey hints over some widgets 2025-06-17 14:52:36 +02:00
Colin Caine 679f95d1de Codechange: make more hotkey ids match widgets 2025-06-17 14:52:36 +02:00
18 changed files with 314 additions and 139 deletions

View File

@ -90,7 +90,7 @@ template <> SQInteger PushClassName<AIInfo, ScriptType::AI>(HSQUIRRELVM vm) { sq
/* Remove the link to the real instance, else it might get deleted by RegisterAI() */ /* Remove the link to the real instance, else it might get deleted by RegisterAI() */
sq_setinstanceup(vm, 2, nullptr); sq_setinstanceup(vm, 2, nullptr);
/* Register the AI to the base system */ /* Register the AI to the base system */
info->GetScanner()->RegisterScript(info); info->GetScanner()->RegisterScript(std::unique_ptr<AIInfo>{info});
return 0; return 0;
} }
@ -136,22 +136,21 @@ bool AIInfo::CanLoadFromVersion(int version) const
/* static */ SQInteger AILibrary::Constructor(HSQUIRRELVM vm) /* static */ SQInteger AILibrary::Constructor(HSQUIRRELVM vm)
{ {
/* Create a new library */ /* Create a new library */
AILibrary *library = new AILibrary(); auto library = std::make_unique<AILibrary>();
SQInteger res = ScriptInfo::Constructor(vm, *library); SQInteger res = ScriptInfo::Constructor(vm, *library);
if (res != 0) { if (res != 0) {
delete library;
return res; return res;
} }
/* Cache the category */ /* Cache the category */
if (!library->CheckMethod("GetCategory") || !library->engine->CallStringMethod(library->SQ_instance, "GetCategory", &library->category, MAX_GET_OPS)) { if (!library->CheckMethod("GetCategory") || !library->engine->CallStringMethod(library->SQ_instance, "GetCategory", &library->category, MAX_GET_OPS)) {
delete library;
return SQ_ERROR; return SQ_ERROR;
} }
/* Register the Library to the base system */ /* Register the Library to the base system */
library->GetScanner()->RegisterScript(library); ScriptScanner *scanner = library->GetScanner();
scanner->RegisterScript(std::move(library));
return 0; return 0;
} }

View File

@ -29,7 +29,7 @@ void AIScannerInfo::Initialize()
{ {
ScriptScanner::Initialize("AIScanner"); ScriptScanner::Initialize("AIScanner");
ScriptAllocatorScope alloc_scope(this->engine); ScriptAllocatorScope alloc_scope(this->engine.get());
/* Create the dummy AI */ /* Create the dummy AI */
this->main_script = "%_dummy"; this->main_script = "%_dummy";

View File

@ -22,9 +22,10 @@
#include "safeguards.h" #include "safeguards.h"
/** Default heights for the different sizes of fonts. */ /** Default unscaled heights for the different sizes of fonts. */
static const int _default_font_height[FS_END] = {10, 6, 18, 10}; /* static */ const int FontCache::DEFAULT_FONT_HEIGHT[FS_END] = {10, 6, 18, 10};
static const int _default_font_ascender[FS_END] = { 8, 5, 15, 8}; /** Default unscaled ascenders for the different sizes of fonts. */
/* static */ const int FontCache::DEFAULT_FONT_ASCENDER[FS_END] = {8, 5, 15, 8};
FontCacheSettings _fcsettings; FontCacheSettings _fcsettings;
@ -32,8 +33,7 @@ FontCacheSettings _fcsettings;
* Create a new font cache. * Create a new font cache.
* @param fs The size of the font. * @param fs The size of the font.
*/ */
FontCache::FontCache(FontSize fs) : parent(FontCache::Get(fs)), fs(fs), height(_default_font_height[fs]), FontCache::FontCache(FontSize fs) : parent(FontCache::Get(fs)), fs(fs)
ascender(_default_font_ascender[fs]), descender(_default_font_ascender[fs] - _default_font_height[fs])
{ {
assert(this->parent == nullptr || this->fs == this->parent->fs); assert(this->parent == nullptr || this->fs == this->parent->fs);
FontCache::caches[this->fs] = this; FontCache::caches[this->fs] = this;
@ -50,7 +50,7 @@ FontCache::~FontCache()
int FontCache::GetDefaultFontHeight(FontSize fs) int FontCache::GetDefaultFontHeight(FontSize fs)
{ {
return _default_font_height[fs]; return FontCache::DEFAULT_FONT_HEIGHT[fs];
} }
/** /**

View File

@ -23,9 +23,9 @@ protected:
static FontCache *caches[FS_END]; ///< All the font caches. static FontCache *caches[FS_END]; ///< All the font caches.
FontCache *parent; ///< The parent of this font cache. FontCache *parent; ///< The parent of this font cache.
const FontSize fs; ///< The size of the font. const FontSize fs; ///< The size of the font.
int height; ///< The height of the font. int height = 0; ///< The height of the font.
int ascender; ///< The ascender value of the font. int ascender = 0; ///< The ascender value of the font.
int descender; ///< The descender value of the font. int descender = 0; ///< The descender value of the font.
public: public:
FontCache(FontSize fs); FontCache(FontSize fs);
@ -33,6 +33,11 @@ public:
static void InitializeFontCaches(); static void InitializeFontCaches();
/** Default unscaled font heights. */
static const int DEFAULT_FONT_HEIGHT[FS_END];
/** Default unscaled font ascenders. */
static const int DEFAULT_FONT_ASCENDER[FS_END];
static int GetDefaultFontHeight(FontSize fs); static int GetDefaultFontHeight(FontSize fs);
/** /**

View File

@ -78,7 +78,7 @@ template <> SQInteger PushClassName<GameInfo, ScriptType::GS>(HSQUIRRELVM vm) {
/* Remove the link to the real instance, else it might get deleted by RegisterGame() */ /* Remove the link to the real instance, else it might get deleted by RegisterGame() */
sq_setinstanceup(vm, 2, nullptr); sq_setinstanceup(vm, 2, nullptr);
/* Register the Game to the base system */ /* Register the Game to the base system */
info->GetScanner()->RegisterScript(info); info->GetScanner()->RegisterScript(std::unique_ptr<GameInfo>{info});
return 0; return 0;
} }
@ -106,22 +106,21 @@ bool GameInfo::CanLoadFromVersion(int version) const
/* static */ SQInteger GameLibrary::Constructor(HSQUIRRELVM vm) /* static */ SQInteger GameLibrary::Constructor(HSQUIRRELVM vm)
{ {
/* Create a new library */ /* Create a new library */
GameLibrary *library = new GameLibrary(); auto library = std::make_unique<GameLibrary>();
SQInteger res = ScriptInfo::Constructor(vm, *library); SQInteger res = ScriptInfo::Constructor(vm, *library);
if (res != 0) { if (res != 0) {
delete library;
return res; return res;
} }
/* Cache the category */ /* Cache the category */
if (!library->CheckMethod("GetCategory") || !library->engine->CallStringMethod(library->SQ_instance, "GetCategory", &library->category, MAX_GET_OPS)) { if (!library->CheckMethod("GetCategory") || !library->engine->CallStringMethod(library->SQ_instance, "GetCategory", &library->category, MAX_GET_OPS)) {
delete library;
return SQ_ERROR; return SQ_ERROR;
} }
/* Register the Library to the base system */ /* Register the Library to the base system */
library->GetScanner()->RegisterScript(library); ScriptScanner *scanner = library->GetScanner();
scanner->RegisterScript(std::move(library));
return 0; return 0;
} }

View File

@ -92,8 +92,8 @@ GameLibrary *GameScannerLibrary::FindLibrary(const std::string &library, int ver
std::string library_name = fmt::format("{}.{}", library, version); std::string library_name = fmt::format("{}.{}", library, version);
/* Check if the library + version exists */ /* Check if the library + version exists */
ScriptInfoList::iterator it = this->info_list.find(library_name); auto it = this->info_list.find(library_name);
if (it == this->info_list.end()) return nullptr; if (it == this->info_list.end()) return nullptr;
return static_cast<GameLibrary *>((*it).second); return static_cast<GameLibrary *>(it->second);
} }

View File

@ -27,8 +27,16 @@ static std::vector<HotkeyList*> *_hotkey_lists = nullptr;
/** String representation of a keycode */ /** String representation of a keycode */
struct KeycodeNames { struct KeycodeNames {
const std::string_view name; ///< Name of the keycode std::string_view name; ///< Name of the keycode
WindowKeyCodes keycode; ///< The keycode WindowKeyCodes keycode; ///< The keycode
std::string_view short_name;
KeycodeNames(const std::string_view name, const WindowKeyCodes keycode, const std::string_view short_name = "")
{
this->name = name;
this->keycode = keycode;
this->short_name = short_name.empty() ? name : short_name;
}
}; };
/** Array of non-standard keycodes that can be used in the hotkeys config file. */ /** Array of non-standard keycodes that can be used in the hotkeys config file. */
@ -38,16 +46,17 @@ static const std::initializer_list<KeycodeNames> _keycode_to_name = {
{"ALT", WKC_ALT}, {"ALT", WKC_ALT},
{"META", WKC_META}, {"META", WKC_META},
{"GLOBAL", WKC_GLOBAL_HOTKEY}, {"GLOBAL", WKC_GLOBAL_HOTKEY},
{"ESC", WKC_ESC}, {"ESC", WKC_ESC, "Esc"},
{"BACKSPACE", WKC_BACKSPACE}, {"TAB", WKC_TAB, "Tab"},
{"INS", WKC_INSERT}, {"BACKSPACE", WKC_BACKSPACE, "BS"},
{"DEL", WKC_DELETE}, {"INS", WKC_INSERT, "Ins"},
{"PAGEUP", WKC_PAGEUP}, {"DEL", WKC_DELETE, "Del"},
{"PAGEDOWN", WKC_PAGEDOWN}, {"PAGEUP", WKC_PAGEUP, "Page up"},
{"END", WKC_END}, {"PAGEDOWN", WKC_PAGEDOWN, "Page down"},
{"HOME", WKC_HOME}, {"END", WKC_END, "End"},
{"RETURN", WKC_RETURN}, {"HOME", WKC_HOME, "Home"},
{"SPACE", WKC_SPACE}, {"RETURN", WKC_RETURN, "Enter"},
{"SPACE", WKC_SPACE, "Space"},
{"F1", WKC_F1}, {"F1", WKC_F1},
{"F2", WKC_F2}, {"F2", WKC_F2},
{"F3", WKC_F3}, {"F3", WKC_F3},
@ -61,31 +70,31 @@ static const std::initializer_list<KeycodeNames> _keycode_to_name = {
{"F11", WKC_F11}, {"F11", WKC_F11},
{"F12", WKC_F12}, {"F12", WKC_F12},
{"BACKQUOTE", WKC_BACKQUOTE}, {"BACKQUOTE", WKC_BACKQUOTE},
{"PAUSE", WKC_PAUSE}, {"PAUSE", WKC_PAUSE, "Pause"},
{"NUM_DIV", WKC_NUM_DIV}, {"NUM_DIV", WKC_NUM_DIV, "Num /"},
{"NUM_MUL", WKC_NUM_MUL}, {"NUM_MUL", WKC_NUM_MUL, "Num *"},
{"NUM_MINUS", WKC_NUM_MINUS}, {"NUM_MINUS", WKC_NUM_MINUS, "Num -"},
{"NUM_PLUS", WKC_NUM_PLUS}, {"NUM_PLUS", WKC_NUM_PLUS, "Num +"},
{"NUM_ENTER", WKC_NUM_ENTER}, {"NUM_ENTER", WKC_NUM_ENTER, "Num Enter"},
{"NUM_DOT", WKC_NUM_DECIMAL}, {"NUM_DOT", WKC_NUM_DECIMAL, "Num ."},
{"SLASH", WKC_SLASH}, {"SLASH", WKC_SLASH, "/"},
{"/", WKC_SLASH}, /* deprecated, use SLASH */ {"/", WKC_SLASH}, /* deprecated, use SLASH */
{"SEMICOLON", WKC_SEMICOLON}, {"SEMICOLON", WKC_SEMICOLON, ";"},
{";", WKC_SEMICOLON}, /* deprecated, use SEMICOLON */ {";", WKC_SEMICOLON}, /* deprecated, use SEMICOLON */
{"EQUALS", WKC_EQUALS}, {"EQUALS", WKC_EQUALS, "="},
{"=", WKC_EQUALS}, /* deprecated, use EQUALS */ {"=", WKC_EQUALS}, /* deprecated, use EQUALS */
{"L_BRACKET", WKC_L_BRACKET}, {"L_BRACKET", WKC_L_BRACKET, "["},
{"[", WKC_L_BRACKET}, /* deprecated, use L_BRACKET */ {"[", WKC_L_BRACKET}, /* deprecated, use L_BRACKET */
{"BACKSLASH", WKC_BACKSLASH}, {"BACKSLASH", WKC_BACKSLASH, "\\"},
{"\\", WKC_BACKSLASH}, /* deprecated, use BACKSLASH */ {"\\", WKC_BACKSLASH}, /* deprecated, use BACKSLASH */
{"R_BRACKET", WKC_R_BRACKET}, {"R_BRACKET", WKC_R_BRACKET, "]"},
{"]", WKC_R_BRACKET}, /* deprecated, use R_BRACKET */ {"]", WKC_R_BRACKET}, /* deprecated, use R_BRACKET */
{"SINGLEQUOTE", WKC_SINGLEQUOTE}, {"SINGLEQUOTE", WKC_SINGLEQUOTE, "'"},
{"'", WKC_SINGLEQUOTE}, /* deprecated, use SINGLEQUOTE */ {"'", WKC_SINGLEQUOTE}, /* deprecated, use SINGLEQUOTE */
{"COMMA", WKC_COMMA}, {"COMMA", WKC_COMMA, ","},
{"PERIOD", WKC_PERIOD}, {"PERIOD", WKC_PERIOD, "."},
{".", WKC_PERIOD}, /* deprecated, use PERIOD */ {".", WKC_PERIOD}, /* deprecated, use PERIOD */
{"MINUS", WKC_MINUS}, {"MINUS", WKC_MINUS, "-"},
{"-", WKC_MINUS}, /* deprecated, use MINUS */ {"-", WKC_MINUS}, /* deprecated, use MINUS */
}; };
@ -196,6 +205,40 @@ static std::string KeycodeToString(uint16_t keycode)
return str; return str;
} }
/**
* A short representation of the keycode, for printing as a hotkey hint.
* @param keycode The keycode to convert to a string.
* @return A string representation of this keycode.
*/
std::string KeycodeToShortString(uint16_t keycode)
{
std::string str;
if (keycode & WKC_SHIFT) {
// TODO
str += "»";
}
if (keycode & WKC_CTRL) {
str += "^";
}
if (keycode & WKC_ALT) {
str += "A+";
}
if (keycode & WKC_META) {
str += "M+";
}
keycode = keycode & ~WKC_SPECIAL_KEYS;
for (const auto &kn : _keycode_to_name) {
if (kn.keycode == keycode) {
str += kn.short_name;
return str;
}
}
assert(keycode < 128);
str.push_back(keycode);
return str;
}
/** /**
* Convert all keycodes attached to a hotkey to a single string. If multiple * Convert all keycodes attached to a hotkey to a single string. If multiple
* keycodes are attached to the hotkey they are split by a comma. * keycodes are attached to the hotkey they are split by a comma.
@ -350,3 +393,12 @@ void HandleGlobalHotkeys([[maybe_unused]] char32_t key, uint16_t keycode)
} }
} }
const Hotkey* HotkeyList::GetHotkeyByNum(int num) const
{
for (const Hotkey &hotkey : this->items) {
if (hotkey.num == num) {
return &hotkey;
}
}
return (const Hotkey*) nullptr;
}

View File

@ -44,6 +44,7 @@ struct HotkeyList {
void Save(IniFile &ini) const; void Save(IniFile &ini) const;
int CheckMatch(uint16_t keycode, bool global_only = false) const; int CheckMatch(uint16_t keycode, bool global_only = false) const;
const Hotkey* GetHotkeyByNum(int num) const;
GlobalHotkeyHandlerFunc global_hotkey_handler; GlobalHotkeyHandlerFunc global_hotkey_handler;
private: private:
@ -64,5 +65,6 @@ void SaveHotkeysToConfig();
void HandleGlobalHotkeys(char32_t key, uint16_t keycode); void HandleGlobalHotkeys(char32_t key, uint16_t keycode);
std::string KeycodeToShortString(uint16_t keycode);
#endif /* HOTKEYS_H */ #endif /* HOTKEYS_H */

View File

@ -469,14 +469,14 @@ static Order GetOrderCmdFromTile(const Vehicle *v, TileIndex tile)
/** Hotkeys for order window. */ /** Hotkeys for order window. */
enum OrderHotKeys : int32_t { enum OrderHotKeys : int32_t {
OHK_SKIP, OHK_SKIP = WID_O_SKIP,
OHK_DELETE, OHK_DELETE = WID_O_DELETE,
OHK_GOTO, OHK_GOTO = WID_O_GOTO,
OHK_NONSTOP, OHK_NONSTOP = WID_O_NON_STOP,
OHK_FULLLOAD, OHK_FULLLOAD = WID_O_FULL_LOAD,
OHK_UNLOAD, OHK_UNLOAD = WID_O_UNLOAD,
OHK_NEAREST_DEPOT, OHK_ALWAYS_SERVICE = WID_O_DEPOT_ACTION,
OHK_ALWAYS_SERVICE, OHK_NEAREST_DEPOT = WID_O_END,
OHK_TRANSFER, OHK_TRANSFER,
OHK_NO_UNLOAD, OHK_NO_UNLOAD,
OHK_NO_LOAD, OHK_NO_LOAD,

View File

@ -44,10 +44,7 @@ bool ScriptScanner::AddFile(const std::string &filename, size_t, const std::stri
return true; return true;
} }
ScriptScanner::ScriptScanner() : ScriptScanner::ScriptScanner() = default;
engine(nullptr)
{
}
void ScriptScanner::ResetEngine() void ScriptScanner::ResetEngine()
{ {
@ -58,7 +55,7 @@ void ScriptScanner::ResetEngine()
void ScriptScanner::Initialize(std::string_view name) void ScriptScanner::Initialize(std::string_view name)
{ {
this->engine = new Squirrel(name); this->engine = std::make_unique<Squirrel>(name);
this->RescanDir(); this->RescanDir();
@ -68,8 +65,6 @@ void ScriptScanner::Initialize(std::string_view name)
ScriptScanner::~ScriptScanner() ScriptScanner::~ScriptScanner()
{ {
this->Reset(); this->Reset();
delete this->engine;
} }
void ScriptScanner::RescanDir() void ScriptScanner::RescanDir()
@ -83,15 +78,12 @@ void ScriptScanner::RescanDir()
void ScriptScanner::Reset() void ScriptScanner::Reset()
{ {
for (const auto &item : this->info_list) {
delete item.second;
}
this->info_list.clear(); this->info_list.clear();
this->info_single_list.clear(); this->info_single_list.clear();
this->info_vector.clear();
} }
void ScriptScanner::RegisterScript(ScriptInfo *info) void ScriptScanner::RegisterScript(std::unique_ptr<ScriptInfo> &&info)
{ {
std::string script_original_name = this->GetScriptName(*info); std::string script_original_name = this->GetScriptName(*info);
std::string script_name = fmt::format("{}.{}", script_original_name, info->GetVersion()); std::string script_name = fmt::format("{}.{}", script_original_name, info->GetVersion());
@ -99,7 +91,6 @@ void ScriptScanner::RegisterScript(ScriptInfo *info)
/* Check if GetShortName follows the rules */ /* Check if GetShortName follows the rules */
if (info->GetShortName().size() != 4) { if (info->GetShortName().size() != 4) {
Debug(script, 0, "The script '{}' returned a string from GetShortName() which is not four characters. Unable to load the script.", info->GetName()); Debug(script, 0, "The script '{}' returned a string from GetShortName() which is not four characters. Unable to load the script.", info->GetName());
delete info;
return; return;
} }
@ -111,7 +102,6 @@ void ScriptScanner::RegisterScript(ScriptInfo *info)
#else #else
if (it->second->GetMainScript() == info->GetMainScript()) { if (it->second->GetMainScript() == info->GetMainScript()) {
#endif #endif
delete info;
return; return;
} }
@ -120,20 +110,20 @@ void ScriptScanner::RegisterScript(ScriptInfo *info)
Debug(script, 1, " 2: {}", info->GetMainScript()); Debug(script, 1, " 2: {}", info->GetMainScript());
Debug(script, 1, "The first is taking precedence."); Debug(script, 1, "The first is taking precedence.");
delete info;
return; return;
} }
this->info_list[script_name] = info; ScriptInfo *script_info = this->info_vector.emplace_back(std::move(info)).get();
this->info_list[script_name] = script_info;
if (!info->IsDeveloperOnly() || _settings_client.gui.ai_developer_tools) { if (!script_info->IsDeveloperOnly() || _settings_client.gui.ai_developer_tools) {
/* Add the script to the 'unique' script list, where only the highest version /* Add the script to the 'unique' script list, where only the highest version
* of the script is registered. */ * of the script is registered. */
auto it = this->info_single_list.find(script_original_name); auto it = this->info_single_list.find(script_original_name);
if (it == this->info_single_list.end()) { if (it == this->info_single_list.end()) {
this->info_single_list[script_original_name] = info; this->info_single_list[script_original_name] = script_info;
} else if (it->second->GetVersion() < info->GetVersion()) { } else if (it->second->GetVersion() < script_info->GetVersion()) {
it->second = info; it->second = script_info;
} }
} }
} }
@ -195,17 +185,17 @@ struct ScriptFileChecksumCreator : FileScanner {
* @param info The script to get the shortname and md5 sum from. * @param info The script to get the shortname and md5 sum from.
* @return True iff they're the same. * @return True iff they're the same.
*/ */
static bool IsSameScript(const ContentInfo &ci, bool md5sum, ScriptInfo *info, Subdirectory dir) static bool IsSameScript(const ContentInfo &ci, bool md5sum, const ScriptInfo &info, Subdirectory dir)
{ {
uint32_t id = 0; uint32_t id = 0;
auto str = std::string_view{info->GetShortName()}.substr(0, 4); auto str = std::string_view{info.GetShortName()}.substr(0, 4);
for (size_t j = 0; j < str.size(); j++) id |= static_cast<uint8_t>(str[j]) << (8 * j); for (size_t j = 0; j < str.size(); j++) id |= static_cast<uint8_t>(str[j]) << (8 * j);
if (id != ci.unique_id) return false; if (id != ci.unique_id) return false;
if (!md5sum) return true; if (!md5sum) return true;
ScriptFileChecksumCreator checksum(dir); ScriptFileChecksumCreator checksum(dir);
const auto &tar_filename = info->GetTarFile(); const auto &tar_filename = info.GetTarFile();
TarList::iterator iter; TarList::iterator iter;
if (!tar_filename.empty() && (iter = _tar_list[dir].find(tar_filename)) != _tar_list[dir].end()) { if (!tar_filename.empty() && (iter = _tar_list[dir].find(tar_filename)) != _tar_list[dir].end()) {
/* The main script is in a tar file, so find all files that /* The main script is in a tar file, so find all files that
@ -224,7 +214,7 @@ static bool IsSameScript(const ContentInfo &ci, bool md5sum, ScriptInfo *info, S
/* There'll always be at least 1 path separator character in a script /* There'll always be at least 1 path separator character in a script
* main script name as the search algorithm requires the main script to * main script name as the search algorithm requires the main script to
* be in a subdirectory of the script directory; so <dir>/<path>/main.nut. */ * be in a subdirectory of the script directory; so <dir>/<path>/main.nut. */
const std::string &main_script = info->GetMainScript(); const std::string &main_script = info.GetMainScript();
std::string path = main_script.substr(0, main_script.find_last_of(PATHSEPCHAR)); std::string path = main_script.substr(0, main_script.find_last_of(PATHSEPCHAR));
checksum.Scan(".nut", path); checksum.Scan(".nut", path);
} }
@ -235,7 +225,7 @@ static bool IsSameScript(const ContentInfo &ci, bool md5sum, ScriptInfo *info, S
bool ScriptScanner::HasScript(const ContentInfo &ci, bool md5sum) bool ScriptScanner::HasScript(const ContentInfo &ci, bool md5sum)
{ {
for (const auto &item : this->info_list) { for (const auto &item : this->info_list) {
if (IsSameScript(ci, md5sum, item.second, this->GetDirectory())) return true; if (IsSameScript(ci, md5sum, *item.second, this->GetDirectory())) return true;
} }
return false; return false;
} }
@ -243,7 +233,7 @@ bool ScriptScanner::HasScript(const ContentInfo &ci, bool md5sum)
std::optional<std::string_view> ScriptScanner::FindMainScript(const ContentInfo &ci, bool md5sum) std::optional<std::string_view> ScriptScanner::FindMainScript(const ContentInfo &ci, bool md5sum)
{ {
for (const auto &item : this->info_list) { for (const auto &item : this->info_list) {
if (IsSameScript(ci, md5sum, item.second, this->GetDirectory())) return item.second->GetMainScript(); if (IsSameScript(ci, md5sum, *item.second, this->GetDirectory())) return item.second->GetMainScript();
} }
return std::nullopt; return std::nullopt;
} }

View File

@ -13,7 +13,7 @@
#include "../fileio_func.h" #include "../fileio_func.h"
#include "../string_func.h" #include "../string_func.h"
typedef std::map<std::string, class ScriptInfo *, CaseInsensitiveComparator> ScriptInfoList; ///< Type for the list of scripts. using ScriptInfoList = std::map<std::string, class ScriptInfo *, CaseInsensitiveComparator>; ///< Type for the list of scripts.
/** Scanner to help finding scripts. */ /** Scanner to help finding scripts. */
class ScriptScanner : public FileScanner { class ScriptScanner : public FileScanner {
@ -26,7 +26,7 @@ public:
/** /**
* Get the engine of the main squirrel handler (it indexes all available scripts). * Get the engine of the main squirrel handler (it indexes all available scripts).
*/ */
class Squirrel *GetEngine() { return this->engine; } class Squirrel *GetEngine() { return this->engine.get(); }
/** /**
* Get the current main script the ScanDir is currently tracking. * Get the current main script the ScanDir is currently tracking.
@ -51,7 +51,7 @@ public:
/** /**
* Register a ScriptInfo to the scanner. * Register a ScriptInfo to the scanner.
*/ */
void RegisterScript(class ScriptInfo *info); void RegisterScript(std::unique_ptr<class ScriptInfo> &&info);
/** /**
* Get the list of registered scripts to print on the console. * Get the list of registered scripts to print on the console.
@ -84,11 +84,13 @@ public:
void RescanDir(); void RescanDir();
protected: protected:
class Squirrel *engine; ///< The engine we're scanning with. std::unique_ptr<class Squirrel> engine; ///< The engine we're scanning with.
std::string main_script; ///< The full path of the script. std::string main_script; ///< The full path of the script.
std::string tar_file; ///< If, which tar file the script was in. std::string tar_file; ///< If, which tar file the script was in.
ScriptInfoList info_list; ///< The list of all script. std::vector<std::unique_ptr<ScriptInfo>> info_vector;
ScriptInfoList info_list; ///< The list of all script.
ScriptInfoList info_single_list; ///< The list of all unique script. The best script (highest version) is shown. ScriptInfoList info_single_list; ///< The list of all unique script. The best script (highest version) is shown.
/** /**

View File

@ -2305,29 +2305,29 @@ static ToolbarButtonProc * const _scen_toolbar_button_procs[] = {
}; };
enum MainToolbarEditorHotkeys : int32_t { enum MainToolbarEditorHotkeys : int32_t {
MTEHK_PAUSE, MTEHK_PAUSE = WID_TE_PAUSE,
MTEHK_FASTFORWARD, MTEHK_FASTFORWARD = WID_TE_FAST_FORWARD,
MTEHK_SETTINGS, MTEHK_SETTINGS = WID_TE_SETTINGS,
MTEHK_SAVEGAME, MTEHK_SAVEGAME = WID_TE_SAVE,
MTEHK_GENLAND, MTEHK_GENLAND = WID_TE_LAND_GENERATE,
MTEHK_GENTOWN, MTEHK_GENTOWN = WID_TE_TOWN_GENERATE,
MTEHK_GENINDUSTRY, MTEHK_GENINDUSTRY = WID_TE_INDUSTRY,
MTEHK_BUILD_ROAD, MTEHK_BUILD_ROAD = WID_TE_ROADS,
MTEHK_BUILD_TRAM, MTEHK_BUILD_TRAM = WID_TE_TRAMS,
MTEHK_BUILD_DOCKS, MTEHK_BUILD_DOCKS = WID_TE_WATER,
MTEHK_BUILD_TREES, MTEHK_BUILD_TREES = WID_TE_TREES,
MTEHK_SIGN, MTEHK_SIGN = WID_TE_SIGNS,
MTEHK_MUSIC, MTEHK_MUSIC = WID_TE_MUSIC_SOUND,
MTEHK_LANDINFO, MTEHK_LANDINFO = WID_TE_HELP,
MTEHK_ZOOM_IN = WID_TE_ZOOM_IN,
MTEHK_ZOOM_OUT = WID_TE_ZOOM_OUT,
MTEHK_SMALLMAP = WID_TE_SMALL_MAP,
MTEHK_TERRAFORM = WID_TE_END,
MTEHK_EXTRA_VIEWPORT,
MTEHK_SMALL_SCREENSHOT, MTEHK_SMALL_SCREENSHOT,
MTEHK_ZOOMEDIN_SCREENSHOT, MTEHK_ZOOMEDIN_SCREENSHOT,
MTEHK_DEFAULTZOOM_SCREENSHOT, MTEHK_DEFAULTZOOM_SCREENSHOT,
MTEHK_GIANT_SCREENSHOT, MTEHK_GIANT_SCREENSHOT,
MTEHK_ZOOM_IN,
MTEHK_ZOOM_OUT,
MTEHK_TERRAFORM,
MTEHK_SMALLMAP,
MTEHK_EXTRA_VIEWPORT,
}; };
struct ScenarioEditorToolbarWindow : Window { struct ScenarioEditorToolbarWindow : Window {

View File

@ -10,47 +10,52 @@
#ifndef TOOLBAR_GUI_H #ifndef TOOLBAR_GUI_H
#define TOOLBAR_GUI_H #define TOOLBAR_GUI_H
#include "widgets/toolbar_widget.h"
// TODO: Replace all instances of "MTHK_blah" with "WID_blah" where we can,
// then redefine this as AdditionalMainToolbarHotkeys, or something like that.
enum MainToolbarHotkeys : int32_t { enum MainToolbarHotkeys : int32_t {
MTHK_PAUSE, MTHK_PAUSE = WID_TN_PAUSE,
MTHK_FASTFORWARD, MTHK_FASTFORWARD = WID_TN_FAST_FORWARD,
MTHK_SETTINGS, MTHK_SETTINGS = WID_TN_SETTINGS,
MTHK_SAVEGAME, MTHK_SAVEGAME = WID_TN_SAVE,
MTHK_LOADGAME, MTHK_SMALLMAP = WID_TN_SMALL_MAP,
MTHK_SMALLMAP, MTHK_TOWNDIRECTORY = WID_TN_TOWNS,
MTHK_TOWNDIRECTORY, MTHK_SUBSIDIES = WID_TN_SUBSIDIES,
MTHK_SUBSIDIES, MTHK_STATIONS = WID_TN_STATIONS,
MTHK_STATIONS, MTHK_FINANCES = WID_TN_FINANCES,
MTHK_FINANCES, MTHK_COMPANIES = WID_TN_COMPANIES,
MTHK_COMPANIES, MTHK_STORY = WID_TN_STORY,
MTHK_STORY, MTHK_GOAL = WID_TN_GOAL,
MTHK_GOAL, MTHK_GRAPHS = WID_TN_GRAPHS,
MTHK_GRAPHS, MTHK_LEAGUE = WID_TN_LEAGUE,
MTHK_LEAGUE, MTHK_INDUSTRIES = WID_TN_INDUSTRIES,
MTHK_INDUSTRIES, MTHK_TRAIN_LIST = WID_TN_TRAINS,
MTHK_TRAIN_LIST, MTHK_ROADVEH_LIST = WID_TN_ROADVEHS,
MTHK_ROADVEH_LIST, MTHK_SHIP_LIST = WID_TN_SHIPS,
MTHK_SHIP_LIST, MTHK_AIRCRAFT_LIST = WID_TN_AIRCRAFT,
MTHK_AIRCRAFT_LIST, MTHK_ZOOM_IN = WID_TN_ZOOM_IN,
MTHK_ZOOM_IN, MTHK_ZOOM_OUT = WID_TN_ZOOM_OUT,
MTHK_ZOOM_OUT, MTHK_BUILD_RAIL = WID_TN_RAILS,
MTHK_BUILD_RAIL, MTHK_BUILD_ROAD = WID_TN_ROADS,
MTHK_BUILD_ROAD, MTHK_BUILD_TRAM = WID_TN_TRAMS,
MTHK_BUILD_TRAM, MTHK_BUILD_DOCKS = WID_TN_WATER,
MTHK_BUILD_DOCKS, MTHK_BUILD_AIRPORT = WID_TN_AIR,
MTHK_BUILD_AIRPORT, MTHK_TERRAFORM = WID_TN_LANDSCAPE,
MTHK_MUSIC = WID_TN_MUSIC_SOUND,
MTHK_LANDINFO = WID_TN_HELP,
// Hotkeys without associated widgets.
MTHK_LOADGAME = WID_TN_END,
MTHK_BUILD_TREES, MTHK_BUILD_TREES,
MTHK_MUSIC,
MTHK_LANDINFO,
MTHK_SCRIPT_DEBUG, MTHK_SCRIPT_DEBUG,
MTHK_SMALL_SCREENSHOT, MTHK_SMALL_SCREENSHOT,
MTHK_ZOOMEDIN_SCREENSHOT, MTHK_ZOOMEDIN_SCREENSHOT,
MTHK_DEFAULTZOOM_SCREENSHOT, MTHK_DEFAULTZOOM_SCREENSHOT,
MTHK_GIANT_SCREENSHOT, MTHK_GIANT_SCREENSHOT,
MTHK_CHEATS, MTHK_CHEATS,
MTHK_TERRAFORM,
MTHK_EXTRA_VIEWPORT, MTHK_EXTRA_VIEWPORT,
MTHK_CLIENT_LIST, MTHK_CLIENT_LIST,
MTHK_SIGN_LIST MTHK_SIGN_LIST,
}; };
void AllocateToolbar(); void AllocateToolbar();

View File

@ -401,6 +401,40 @@ static void CancelIMEComposition(HWND hwnd)
HandleTextInput({}, true); HandleTextInput({}, true);
} }
#if defined(_MSC_VER) && defined(NTDDI_WIN10_RS4)
/* We only use WinRT functions on Windows 10 or later. Unfortunately, newer Windows SDKs are now
* linking the two functions below directly instead of using dynamic linking as previously.
* To avoid any runtime linking errors on Windows 7 or older, we stub in our own dynamic
* linking trampoline. */
static LibraryLoader _combase("combase.dll");
extern "C" int32_t __stdcall WINRT_IMPL_RoOriginateLanguageException(int32_t error, void *message, void *languageException) noexcept
{
typedef BOOL(WINAPI *PFNRoOriginateLanguageException)(int32_t, void *, void *);
static PFNRoOriginateLanguageException RoOriginateLanguageException = _combase.GetFunction("RoOriginateLanguageException");
if (RoOriginateLanguageException != nullptr) {
return RoOriginateLanguageException(error, message, languageException);
} else {
return TRUE;
}
}
extern "C" int32_t __stdcall WINRT_IMPL_RoGetActivationFactory(void *classId, winrt::guid const &iid, void **factory) noexcept
{
typedef BOOL(WINAPI *PFNRoGetActivationFactory)(void *, winrt::guid const &, void **);
static PFNRoGetActivationFactory RoGetActivationFactory = _combase.GetFunction("RoGetActivationFactory");
if (RoGetActivationFactory != nullptr) {
return RoGetActivationFactory(classId, iid, factory);
} else {
*factory = nullptr;
return winrt::impl::error_class_not_available;
}
}
#endif
static bool IsDarkModeEnabled() static bool IsDarkModeEnabled()
{ {
/* Only build if SDK is Windows 10 1803 or later. */ /* Only build if SDK is Windows 10 1803 or later. */

View File

@ -27,6 +27,9 @@
#include "safeguards.h" #include "safeguards.h"
#include "widgets/toolbar_widget.h"
#include "hotkeys.h"
WidgetDimensions WidgetDimensions::scaled = {}; WidgetDimensions WidgetDimensions::scaled = {};
static std::string GetStringForWidget(const Window *w, const NWidgetCore *nwid, bool secondary = false) static std::string GetStringForWidget(const Window *w, const NWidgetCore *nwid, bool secondary = false)
@ -3108,6 +3111,87 @@ void NWidgetLeaf::Draw(const Window *w)
} }
DrawOutline(w, this); DrawOutline(w, this);
// TODO: Draw hints only if Alt is being held.
// Don't draw hotkey hints on disabled widgets or editboxes with focus.
if (!(this->IsDisabled() || (this->type == WWT_EDITBOX && w->nested_focus == this))) {
this->DrawHotkeyHint(w);
}
}
void NWidgetLeaf::DrawHotkeyHint(const Window* w) {
// TODO: Use global hotkey for autoroads for rail, road, tram, etc. if
// they have been set.
const uint o = ScaleGUITrad(1);
Rect r = this->GetCurrentRect().Shrink(o);
std::string hint;
uint16_t keycode = 0;
if (w->window_desc.cls == WC_MAIN_TOOLBAR && this->index == WID_TN_FAST_FORWARD) {
// Special-case hint text for Fast-forwards because it's not really a hotkey
hint = "Tab";
} else if (w->window_desc.hotkeys != nullptr) {
// Widget IDs can coincidentally overlap with hotkey IDs if
// they aren't assigned properly. Avoid this.
auto hk = w->window_desc.hotkeys->GetHotkeyByNum(this->index);
if (hk != nullptr && hk->keycodes.size()) {
// Find the "best" of the available keycodes
// TODO: maybe don't repeat this work so much
keycode = *(hk->keycodes.begin());
hint = KeycodeToShortString(keycode);
for (auto k : hk->keycodes) {
if (!(keycode & WKC_GLOBAL_HOTKEY) && (k & WKC_GLOBAL_HOTKEY)) {
keycode = k;
} else {
auto h = KeycodeToShortString(k);
if (hint.length() > h.length()) {
keycode = k;
hint = h;
}
}
}
// Convert to a string
// TODO: Glyphs for Shift, Alt, etc. Colour for global.
// - On screen keyboard has a sprite for shift.
hint = KeycodeToShortString(keycode);
}
}
if (hint.empty()) {
return;
}
// Choose the font-size
auto fontsize = FS_SMALL;
// It's better to have a single consistent size.
/*auto availableSize = Dimension(r.right - r.left, r.bottom - r.top);*/
/*auto desiredSize = GetStringBoundingBox(hint, FS_NORMAL);*/
/*if (availableSize < desiredSize) {*/
/* fontsize = FS_SMALL;*/
/*}*/
// Choose hint colour
auto colour = TC_WHITE;
if (keycode & WKC_GLOBAL_HOTKEY) {
colour = TC_LIGHT_BLUE;
}
auto alignment = SA_LEFT | SA_BOTTOM;
// Draw a slightly shoddy outline
DrawStringMultiLine(r.Translate( o, o), hint, TC_BLACK | TC_NO_SHADE, alignment, false, fontsize);
DrawStringMultiLine(r.Translate( o, -o), hint, TC_BLACK | TC_NO_SHADE, alignment, false, fontsize);
DrawStringMultiLine(r.Translate(-o, o), hint, TC_BLACK | TC_NO_SHADE, alignment, false, fontsize);
DrawStringMultiLine(r.Translate(-o, -o), hint, TC_BLACK | TC_NO_SHADE, alignment, false, fontsize);
DrawStringMultiLine(r.Translate( o, 0), hint, TC_BLACK | TC_NO_SHADE, alignment, false, fontsize);
DrawStringMultiLine(r.Translate(-o, 0), hint, TC_BLACK | TC_NO_SHADE, alignment, false, fontsize);
DrawStringMultiLine(r.Translate( 0, o), hint, TC_BLACK | TC_NO_SHADE, alignment, false, fontsize);
DrawStringMultiLine(r.Translate( 0, -o), hint, TC_BLACK | TC_NO_SHADE, alignment, false, fontsize);
// Draw the hint text
DrawStringMultiLine(r, hint, colour | TC_NO_SHADE, alignment, false, fontsize);
} }
/** /**

View File

@ -922,6 +922,7 @@ public:
void SetupSmallestSize(Window *w) override; void SetupSmallestSize(Window *w) override;
void Draw(const Window *w) override; void Draw(const Window *w) override;
void DrawHotkeyHint(const Window* window);
bool ButtonHit(const Point &pt); bool ButtonHit(const Point &pt);

View File

@ -37,6 +37,7 @@ enum OrderWidgets : WidgetID {
WID_O_SEL_TOP_ROW, ///< #NWID_SELECTION widget for the top row of the 'your non-trains' order window. WID_O_SEL_TOP_ROW, ///< #NWID_SELECTION widget for the top row of the 'your non-trains' order window.
WID_O_SEL_BOTTOM_MIDDLE, ///< #NWID_SELECTION widget for the middle part of the bottom row of the 'your train' order window. WID_O_SEL_BOTTOM_MIDDLE, ///< #NWID_SELECTION widget for the middle part of the bottom row of the 'your train' order window.
WID_O_SHARED_ORDER_LIST, ///< Open list of shared vehicles. WID_O_SHARED_ORDER_LIST, ///< Open list of shared vehicles.
WID_O_END, ///< End of the list of widgets.
}; };
#endif /* WIDGETS_ORDER_WIDGET_H */ #endif /* WIDGETS_ORDER_WIDGET_H */

View File

@ -73,6 +73,7 @@ enum ToolbarEditorWidgets : WidgetID {
WID_TE_MUSIC_SOUND, ///< Music/sound configuration menu. WID_TE_MUSIC_SOUND, ///< Music/sound configuration menu.
WID_TE_HELP, ///< Help menu. WID_TE_HELP, ///< Help menu.
WID_TE_SWITCH_BAR, ///< Only available when toolbar has been split to switch between different subsets. WID_TE_SWITCH_BAR, ///< Only available when toolbar has been split to switch between different subsets.
WID_TE_END,
}; };
#endif /* WIDGETS_TOOLBAR_WIDGET_H */ #endif /* WIDGETS_TOOLBAR_WIDGET_H */