diff --git a/Game.Client/GarrysMod/HtmlPanel.cs b/Game.Client/GarrysMod/HtmlPanel.cs
index 5d8006143..c7f6c61c3 100644
--- a/Game.Client/GarrysMod/HtmlPanel.cs
+++ b/Game.Client/GarrysMod/HtmlPanel.cs
@@ -110,7 +110,9 @@ public override void OnKeyCodeTyped(ButtonCode code) {
return;
if (code >= ButtonCode.KeyF1 && code <= ButtonCode.KeyF12) {
- // todo: run key binding
+ ReadOnlySpan binding = gameuifuncs.GetBindingForButtonCode(code);
+ if (!binding.IsEmpty && binding[0] != '\0')
+ engine.ClientCmd_Unrestricted(binding);
return;
}
diff --git a/Game.Client/SourceDllMain.cs b/Game.Client/SourceDllMain.cs
index b725ed699..d53c6437d 100644
--- a/Game.Client/SourceDllMain.cs
+++ b/Game.Client/SourceDllMain.cs
@@ -56,6 +56,7 @@ public static void Link(IServiceCollection services) {
[Dependency] public static IViewRender view { get; private set; } = null!;
[Dependency] public static IRenderView render { get; private set; } = null!;
[Dependency] public static IEngineClient engine { get; private set; } = null!;
+ [Dependency] public static IGameUIFuncs gameuifuncs { get; private set; } = null!;
[Dependency] public static IMatSystemSurface surface { get; private set; } = null!;
[Dependency] public static IEngineVGui enginevgui { get; private set; } = null!;
[Dependency] public static ISpatialPartition partition { get; private set; } = null!;
diff --git a/Game.Lua/LuaConVarsImpl.cs b/Game.Lua/LuaConVarsImpl.cs
index 7c6609e4b..af3a564bf 100644
--- a/Game.Lua/LuaConVarsImpl.cs
+++ b/Game.Lua/LuaConVarsImpl.cs
@@ -62,7 +62,7 @@ public ConVar CreateConVar(ReadOnlySpan name, ReadOnlySpan defaultVa
}
public void DestroyManaged() {
- SaveManaged();
+ SaveManagedConVars();
foreach (ManagedCommand managed in Managed)
cvar.UnregisterConCommand(managed.Command);
@@ -70,7 +70,7 @@ public void DestroyManaged() {
Managed.Clear();
}
- void SaveManaged() {
+ public void SaveManagedConVars() {
foreach (ManagedCommand managed in Managed) {
if (!managed.IsConVar || !managed.Archive)
continue;
diff --git a/Game.UI/OptionsSubKeyboard.cs b/Game.UI/OptionsSubKeyboard.cs
index 44109ee50..f074ca015 100644
--- a/Game.UI/OptionsSubKeyboard.cs
+++ b/Game.UI/OptionsSubKeyboard.cs
@@ -100,11 +100,11 @@ public void ParseActionDescriptions() {
Span binding = stackalloc char[256];
Span description = stackalloc char[256];
- long size = g_pFileSystem.Size("scripts/kb_act.lst");
+ long size = g_pFileSystem.Size("scripts/kb_act.lst", "MOD");
if (size <= 0) return;
Span fileData = stackalloc byte[(int)size];
- if (!g_pFileSystem.ReadFile("scripts/kb_act.lst", null, fileData.AsBytes(), 0))
+ if (!g_pFileSystem.ReadFile("scripts/kb_act.lst", "MOD", fileData.AsBytes(), 0))
return;
ReadOnlySpan data = fileData;
@@ -126,7 +126,7 @@ public void ParseActionDescriptions() {
strcpy(description, token);
if (description[0] != '=') {
- if (streq(binding, "blank")) {
+ if (strieq(binding, "blank")) {
KeyBindList.AddSection(++sectionIndex, description);
KeyBindList.AddColumnToSection(sectionIndex, "Action", description, SectionedListPanel.ColumnBright, 286);
KeyBindList.AddColumnToSection(sectionIndex, "Key", "#GameUI_KeyButton", SectionedListPanel.ColumnBright, 128);
@@ -151,7 +151,7 @@ public void ParseActionDescriptions() {
KeyValues bindingItem = item.FindKey("Binding")!;
ReadOnlySpan bindString = bindingItem.GetString();
- if (strcmp(bindString, binding) == 0)
+ if (stricmp(bindString, binding) == 0)
return item;
}
@@ -159,10 +159,10 @@ public void ParseActionDescriptions() {
}
public void AddBinding(KeyValues item, ReadOnlySpan keyName) {
- if (stricmp(item.GetString("key", ""), keyName) == 0)
+ if (stricmp(item.GetString("Key", ""), keyName) == 0)
return;
- // RemoveKeyFromBindItems(item, keyName);
+ RemoveKeyFromBindItems(item, keyName);
ReadOnlySpan binding = item.GetString("Binding", "");
@@ -175,7 +175,7 @@ public void AddBinding(KeyValues item, ReadOnlySpan keyName) {
if (stricmp(curBinding, binding) == 0) {
curItem.SetString("Key", keyName);
- KeyBindList.InvalidateLayout();
+ KeyBindList.InvalidateItem(i);
}
}
}
@@ -186,7 +186,7 @@ public void ClearBindItems() {
if (item == null)
continue;
- item.SetString("key", "");
+ item.SetString("Key", "");
KeyBindList.InvalidateItem(i);
}
@@ -194,8 +194,35 @@ public void ClearBindItems() {
KeyBindList.InvalidateLayout();
}
- public void RemoveKeyFromBindItems() {
+ public void RemoveKeyFromBindItems(KeyValues? orgItem, ReadOnlySpan key) {
+ if (key.IsEmpty)
+ return;
+
+ string keyName = new(key);
+
+ for (int i = 0; i < KeyBindList.GetItemCount(); i++) {
+ KeyValues? item = KeyBindList.GetItemData(KeyBindList.GetItemIDFromRow(i));
+ if (item == null)
+ continue;
+
+ if (stricmp(keyName, item.GetString("Key", "")) == 0) {
+ bool clearEntry = true;
+ if (orgItem != null) {
+ ReadOnlySpan orgBinding = orgItem.GetString("Binding", "");
+ ReadOnlySpan binding = item.GetString("Binding", "");
+ if (stricmp(orgBinding, binding) == 0)
+ clearEntry = false;
+ }
+
+ if (clearEntry) {
+ item.SetString("Key", "");
+ KeyBindList.InvalidateItem(i);
+ }
+ }
+ }
+
+ KeyBindList.InvalidateLayout();
}
public void FillInCurrentBindings() {
@@ -203,15 +230,10 @@ public void FillInCurrentBindings() {
ClearBindItems();
- // bool Joystick = false;
- // ConVarRef joy = new("joystick");
- // if (joy.IsValid())
- // Joystick = joy.GetBool();
-
- // bool Falcon = false;
- // ConVarRef falcon = new("hap_HasDevice");
- // if (falcon.IsValid())
- // Falcon = falcon.GetBool();
+ bool joystick = false;
+ ConVarRef joystickVar = new("joystick");
+ if (joystickVar.IsValid())
+ joystick = joystickVar.GetBool();
for (int i = 0; i < KeyBindings.Length; i++) {
ReadOnlySpan binding = gameuifuncs.GetBindingForButtonCode((ButtonCode)i);
@@ -221,20 +243,27 @@ public void FillInCurrentBindings() {
KeyValues? item = GetItemForBinding(binding);
if (item != null) {
ReadOnlySpan keyName = inputSystem.ButtonCodeToString((ButtonCode)i);
- ReadOnlySpan currentKey = item.GetString("key", "");
+ ReadOnlySpan currentKey = item.GetString("Key", "");
if (!currentKey.IsEmpty) {
- // ButtonCode currentBC = gameuifuncs.GetButtonCodeForBind(currentKey);
- KeysToUnbind.Remove(currentKey.ToString());
+ ButtonCode currentBC = gameuifuncs.GetButtonCodeForBind(currentKey);
+
+ bool shouldOverride = joystick && IsJoystickOrNovintCode((ButtonCode)i) && !IsJoystickOrNovintCode(currentBC);
+ if (!shouldOverride)
+ continue;
+
+ KeysToUnbind.Remove(new(currentKey));
}
AddBinding(item, keyName);
- KeysToUnbind.Add(keyName.ToString());
+ KeysToUnbind.Add(new(keyName));
}
}
}
+ static bool IsJoystickOrNovintCode(ButtonCode code) => code.IsJoystickCode() || code.IsNovintCode();
+
public void DeleteSavedBindings() {
for (int i = 0; i < KeyBindings.Length; i++) {
if (KeyBindings[i].Binding != null)
@@ -247,23 +276,43 @@ public void SaveCurrentBindings() {
for (int i = 0; i < (int)ButtonCode.Last; i++) {
ReadOnlySpan binding = gameuifuncs.GetBindingForButtonCode((ButtonCode)i);
- if (!binding.IsEmpty)
+ if (binding.IsEmpty)
continue;
KeyBindings[i].Binding = new(binding);
}
}
- public void BindKey() {
+ public void BindKey(ReadOnlySpan key, ReadOnlySpan binding) => engine.ClientCmd_Unrestricted($"bind \"{key}\" \"{binding}\"\n");
- }
+ public void UnbindKey(ReadOnlySpan key) => engine.ClientCmd_Unrestricted($"unbind \"{key}\"\n");
- public void UnbindKey() {
+ public void ApplyAllBindings() {
+ for (int i = 0; i < KeysToUnbind.Count; i++)
+ UnbindKey(KeysToUnbind[i]);
+ KeysToUnbind.Clear();
- }
+ DeleteSavedBindings();
- public void ApplyAllBindings() {
+ for (int i = 0; i < KeyBindList.GetItemCount(); i++) {
+ KeyValues? item = KeyBindList.GetItemData(KeyBindList.GetItemIDFromRow(i));
+ if (item == null)
+ continue;
+ ReadOnlySpan binding = item.GetString("Binding", "");
+ if (binding.IsEmpty)
+ continue;
+
+ ReadOnlySpan keyName = item.GetString("Key", "");
+ if (!keyName.IsEmpty) {
+ BindKey(keyName, binding);
+ ButtonCode code = inputSystem.StringToButtonCode(keyName);
+ if (code != ButtonCode.Invalid)
+ KeyBindings[(int)code].Binding = new(binding);
+ }
+ }
+
+ engine.ClientCmd_Unrestricted("exec userconfig.cfg\nhost_writeconfig\n");
}
public void FillInDefaultBindings() {
@@ -276,7 +325,40 @@ public void FillInDefaultBindings() {
ClearBindItems();
- // todo
+ ReadOnlySpan data = fileData;
+ Span cmd = stackalloc char[1024];
+ Span keyName = stackalloc char[1024];
+ Span binding = stackalloc char[1024];
+
+ while (true) {
+ data = engine.ParseFile(data, cmd);
+ if (strlen(cmd) == 0)
+ break;
+
+ if (stricmp(cmd, "bind") == 0) {
+ data = engine.ParseFile(data, keyName);
+ if (strlen(keyName) == 0)
+ break;
+
+ data = engine.ParseFile(data, binding);
+ if (strlen(keyName) == 0)
+ break;
+
+ KeyValues? item = GetItemForBinding(binding[..(int)strlen(binding)]);
+ if (item != null)
+ AddBinding(item, keyName[..(int)strlen(keyName)]);
+ }
+ }
+
+ PostActionSignal(KV_ApplyButtonEnable);
+
+ KeyValues? consoleItem = GetItemForBinding("toggleconsole");
+ if (consoleItem != null)
+ AddBinding(consoleItem, "`");
+
+ KeyValues? escapeItem = GetItemForBinding("cancelselect");
+ if (escapeItem != null)
+ AddBinding(escapeItem, "ESCAPE");
}
[UiMessage("ItemSelected")]
@@ -294,7 +376,7 @@ public void ItemSelected(int itemID) {
else
ClearBindingButton.SetEnabled(false);
- if (kv.GetInt("Header") > 0)
+ if (kv.GetInt("Header") != 0)
SetBindingButton.SetEnabled(false);
}
}
@@ -333,8 +415,28 @@ public override void OnThink() {
}
public override void OnKeyCodePressed(ButtonCode code) {
- base.OnKeyCodePressed(code);
+ if (!KeyBindList.IsCapturing()) {
+ int r = KeyBindList.GetItemOfInterest();
+
+ bool visible = KeyBindList.GetCellBounds(r, 1, out _, out _, out _, out _);
+ if (visible) {
+ if (code == ButtonCode.KeyDelete) {
+ KeyValues? kv = KeyBindList.GetItemData(r);
+ ReadOnlySpan key = kv != null ? kv.GetString("Key", null) : null;
+ if (!key.IsEmpty)
+ RemoveKeyFromBindItems(null, key);
+
+ ClearBindingButton.SetEnabled(false);
+ KeyBindList.InvalidateItem(r);
+ PostActionSignal(KV_ApplyButtonEnable);
+
+ return;
+ }
+ }
+ }
+
+ base.OnKeyCodePressed(code);
}
[UiCommand("Advanced")]
@@ -355,6 +457,11 @@ public OptionsSubKeyboardAdvancedDlg(Panel? parent) : base(null, null) {
SetDeleteSelfOnClose(true);
}
+#if GMOD_DLL
+ public override void Activate() => base.Activate();
+
+ public void OnApplyData() { }
+#else
public override void Activate() {
base.Activate();
@@ -375,6 +482,7 @@ public void OnApplyData() {
ConVarRef hud_fastswitch = new("hud_fastswitch");
hud_fastswitch.SetValue(GetControlInt("FastSwitchCheck", 0));
}
+#endif
[UiCommand("OK")]
private void OnOK() {
diff --git a/Source.Common/Formats/Keyvalues/KeyValues.cs b/Source.Common/Formats/Keyvalues/KeyValues.cs
index a964f2211..1de5600d7 100644
--- a/Source.Common/Formats/Keyvalues/KeyValues.cs
+++ b/Source.Common/Formats/Keyvalues/KeyValues.cs
@@ -165,47 +165,63 @@ private void WriteStringToBuffer(StreamWriter writer, string value) {
writer.Write(value);
}
- private bool WriteToBuffer(StreamWriter writer, int recursionLevel = 0) {
- writer.Write(new string('\t', recursionLevel));
- writer.Write("\"");
+ private bool WriteToBuffer(StreamWriter writer, int indentLevel = 0) {
+ RecursiveSaveToFile(writer, indentLevel);
+ return true;
+ }
+
+ private static void WriteIndents(StreamWriter writer, int indentLevel) {
+ for (int i = 0; i < indentLevel; i++)
+ writer.Write('\t');
+ }
+
+ private void RecursiveSaveToFile(StreamWriter writer, int indentLevel) {
+ WriteIndents(writer, indentLevel);
+ writer.Write('"');
WriteStringToBuffer(writer, Name);
- writer.WriteLine("\"");
- if (children.Count != 0) {
- writer.WriteLine("\"");
- writer.WriteLine("{");
- foreach (var child in children)
- child.WriteToBuffer(writer, 1);
- writer.WriteLine("}");
+ writer.Write("\"\n");
+ WriteIndents(writer, indentLevel);
+ writer.Write("{\n");
+
+ foreach (KeyValues dat in children)
+ SaveKeyToFile(dat, writer, indentLevel);
+
+ WriteIndents(writer, indentLevel);
+ writer.Write("}\n");
+ }
+
+ private static void SaveKeyToFile(KeyValues dat, StreamWriter writer, int indentLevel) {
+ if (dat.children.Count != 0) {
+ dat.RecursiveSaveToFile(writer, indentLevel + 1);
+ return;
}
- else {
- switch (Type) {
- case Types.None:
- writer.WriteLine();
- break;
- case Types.String:
- writer.Write("\"");
- WriteStringToBuffer(writer, Value is string str ? (str ?? "") : "");
- writer.WriteLine("\"");
- break;
- case Types.Int:
- writer.Write("\"");
- WriteStringToBuffer(writer, (Value is long l ? l : Value is int i1 ? i1 : 0).ToString());
- writer.WriteLine("\"");
- break;
- case Types.Double:
- writer.Write("\"");
- WriteStringToBuffer(writer, ((float)(Value is double d ? d : Value is int i2 ? i2 : 0)).ToString("F6", CultureInfo.InvariantCulture));
- writer.WriteLine("\"");
- break;
- case Types.Pointer:
- throw new NotImplementedException();
- case Types.Color:
- throw new NotImplementedException();
- case Types.Uint64:
- throw new NotImplementedException();
- }
+
+ string value;
+ switch (dat.Type) {
+ case Types.String:
+ if (dat.Value is not string str || str.Length == 0)
+ return;
+ value = str;
+ break;
+ case Types.Int:
+ value = (dat.Value is long l ? l : dat.Value is int i ? i : 0).ToString(CultureInfo.InvariantCulture);
+ break;
+ case Types.Uint64:
+ value = $"0x{(dat.Value is ulong u ? u : 0):X16}";
+ break;
+ case Types.Double:
+ value = ((float)(dat.Value is double d ? d : dat.Value is int i2 ? i2 : 0)).ToString("F6", CultureInfo.InvariantCulture);
+ break;
+ default:
+ return;
}
- return true;
+
+ WriteIndents(writer, indentLevel + 1);
+ writer.Write('"');
+ dat.WriteStringToBuffer(writer, dat.Name);
+ writer.Write("\"\t\t\"");
+ dat.WriteStringToBuffer(writer, value);
+ writer.Write("\"\n");
}
@@ -623,6 +639,9 @@ public bool WriteToFile(string? filepath) {
public void ChainKeyValue(KeyValues? chain) => Chain = chain;
public KeyValues? FindKey(ReadOnlySpan searchStr, bool create = false) {
+ if (searchStr.IsEmpty || searchStr[0] == '\0')
+ return this;
+
foreach (var child in this.children) {
if (stricmp(child.Name, searchStr) == 0)
return child;
diff --git a/Source.Common/GarrysMod/Lua/LuaConVars.cs b/Source.Common/GarrysMod/Lua/LuaConVars.cs
index 8d4432a9b..63aa5405c 100644
--- a/Source.Common/GarrysMod/Lua/LuaConVars.cs
+++ b/Source.Common/GarrysMod/Lua/LuaConVars.cs
@@ -10,4 +10,5 @@ public interface ILuaConVars
void DestroyManaged();
void Cache(ReadOnlySpan name, ReadOnlySpan value);
void ClearCache();
+ void SaveManagedConVars();
}
diff --git a/Source.Common/Input/ButtonCode.cs b/Source.Common/Input/ButtonCode.cs
index 4e2148309..446aa8b8a 100644
--- a/Source.Common/Input/ButtonCode.cs
+++ b/Source.Common/Input/ButtonCode.cs
@@ -228,4 +228,12 @@ public static bool IsKeyCode(this ButtonCode code) {
public static bool IsMouseCode(this ButtonCode code) {
return (code >= ButtonCode.MouseFirst) && (code <= ButtonCode.MouseLast);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static bool IsNovintCode(this ButtonCode code) {
+ return (code >= ButtonCode.NovintFirst) && (code <= ButtonCode.NovintLast);
+ }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static bool IsJoystickCode(this ButtonCode code) {
+ return (code >= ButtonCode.JoystickFirst) && (code <= ButtonCode.JoystickLast);
+ }
}
diff --git a/Source.Common/Launcher/WindowEvent.cs b/Source.Common/Launcher/WindowEvent.cs
index 6b22a210a..10967bbca 100644
--- a/Source.Common/Launcher/WindowEvent.cs
+++ b/Source.Common/Launcher/WindowEvent.cs
@@ -7,6 +7,7 @@ public class WindowEvent
{
public WindowEventType EventType;
public int VirtualKeyCode;
+ public int WindowsVirtualKey;
public char UTF8Key;
public char UTF8KeyUnmodified;
public KeyModifier ModifierKeyMask;
diff --git a/Source.Engine/CvarUtilities.cs b/Source.Engine/CvarUtilities.cs
index 3ea6d7be7..db95c0c26 100644
--- a/Source.Engine/CvarUtilities.cs
+++ b/Source.Engine/CvarUtilities.cs
@@ -4,6 +4,8 @@
using Source.Engine.Client;
using Source.Engine.Server;
+using System.Text;
+
namespace Source.Engine;
public class CvarUtilities(ICvar cvar, Host Host, Cmd cmd)
@@ -40,6 +42,30 @@ public static void ConVarNetworkChangeCallback(IConVar conVar, in ConVarChangeCo
// SV_ReplicateConVarChange((ConVar)conVar, var.GetString());
}
+ public void WriteVariables(StringBuilder buff, bool allVars) {
+ foreach (ConCommandBase var in cvar.GetCommands()) {
+ if (var.IsCommand())
+ continue;
+
+ if (!var.IsFlagSet(FCvar.Archive))
+ continue;
+
+#if GMOD_DLL
+ if (var.GetName().AsSpan().IndexOfAny(";\"\n\r") >= 0)
+ continue;
+#endif
+
+ ConVar convar = (ConVar)var;
+ if (allVars || !streq(convar.GetString(), convar.GetDefault())) {
+#if GMOD_DLL
+ if (convar.GetString().AsSpan().IndexOfAny("\"\n\r") >= 0)
+ continue;
+#endif
+ buff.Append($"{var.GetName()} \"{convar.GetString()}\"\n");
+ }
+ }
+ }
+
public unsafe bool IsCommand(in TokenizedCommand args) {
int c = args.ArgC();
if (c == 0)
diff --git a/Source.Engine/Host.cs b/Source.Engine/Host.cs
index 39ea00c54..94fac476f 100644
--- a/Source.Engine/Host.cs
+++ b/Source.Engine/Host.cs
@@ -7,6 +7,7 @@
using Source.Common.Commands;
using Source.Common.Engine;
using Source.Common.Filesystem;
+using Source.Common.Formats.Keyvalues;
using Source.Common.Input;
using Source.Common.Networking;
using Source.Common.Server;
@@ -18,6 +19,7 @@
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
+using System.Text;
using static Source.Constants;
@@ -437,6 +439,8 @@ public void PostInit() {
this.clientDLL = clientDLL;
}
+ IInputSystem? inputSystem { get => field ??= services.GetService(); }
+
bool ConfigCfgExecuted = false;
public void ReadConfiguration() {
if (sv.IsDedicated())
@@ -467,6 +471,8 @@ public void ReadConfiguration() {
if (Key.NameForBinding("toggleconsole").IsEmpty)
Key.SetBinding(ButtonCode.KeyBackquote, "toggleconsole");
+ SetupDefaultAskConnectAcceptKey();
+
ConfigCfgExecuted = true;
if (saveconfig) {
@@ -477,33 +483,224 @@ public void ReadConfiguration() {
}
}
+#if !SWDS
+ static readonly ButtonCode[] InvalidKeyBindings = [
+ ButtonCode.KeyPad0, ButtonCode.KeyPad1, ButtonCode.KeyPad2, ButtonCode.KeyPad3, ButtonCode.KeyPad4,
+ ButtonCode.KeyPad5, ButtonCode.KeyPad6, ButtonCode.KeyPad7, ButtonCode.KeyPad8, ButtonCode.KeyPad9,
+ ButtonCode.KeyPadDivide, ButtonCode.KeyPadMultiply, ButtonCode.KeyPadMinus, ButtonCode.KeyPadPlus,
+ ButtonCode.KeyPadEnter, ButtonCode.KeyPadDecimal, ButtonCode.KeyEscape, ButtonCode.KeyScrollLock,
+ ButtonCode.KeyInsert, ButtonCode.KeyDelete, ButtonCode.KeyHome, ButtonCode.KeyEnd, ButtonCode.KeyPageUp,
+ ButtonCode.KeyPageDown, ButtonCode.KeyBreak, ButtonCode.KeyLShift, ButtonCode.KeyRShift, ButtonCode.KeyLAlt,
+ ButtonCode.KeyRAlt, ButtonCode.KeyLControl, ButtonCode.KeyRControl, ButtonCode.KeyLWin, ButtonCode.KeyRWin,
+ ButtonCode.KeyApp, ButtonCode.KeyUp, ButtonCode.KeyLeft, ButtonCode.KeyDown, ButtonCode.KeyRight,
+ ButtonCode.KeyCapsLockToggle, ButtonCode.KeyNumLockToggle, ButtonCode.KeyScrollLockToggle, ButtonCode.KeyBackquote,
+ ];
+#endif
+
private void SetupNewBindings() {
- // todo
+#if !SWDS
+ const string filename = "scripts\\newbindings.txt";
+ KeyValues newBindingsData = new(filename);
+ if (!newBindingsData.LoadFromFile(fileSystem, filename))
+ return;
+
+ for (KeyValues? subKey = newBindingsData.GetFirstTrueSubKey(); subKey != null; subKey = subKey.GetNextTrueSubKey()) {
+ string binding = subKey.Name;
+ if (binding == null)
+ continue;
+
+ if (subKey.FindKey("ideal_key") == null)
+ continue;
+ string idealKey = new(subKey.GetString("ideal_key"));
+
+ if (subKey.FindKey("override_if") != null) {
+ ReadOnlySpan overrideIfCmd = subKey.GetString("override_if");
+ string? currentBindingForKey = Key.BindingForKey(inputSystem!.StringToButtonCode(idealKey));
+ if (currentBindingForKey == null || stricmp(overrideIfCmd, currentBindingForKey) == 0) {
+ BindNewBinding(idealKey, binding);
+ continue;
+ }
+ }
+
+ if (!Key.NameForBinding(binding).IsEmpty)
+ continue;
+
+ if (Key.BindingForKey(inputSystem!.StringToButtonCode(idealKey)) == null) {
+ BindNewBinding(idealKey, binding);
+ continue;
+ }
+
+ bool found = false;
+ int numAttempts = 1;
+ for (int curButton = (int)ButtonCode.Key0; curButton <= (int)ButtonCode.KeyLast; ++curButton, ++numAttempts) {
+ if (Array.IndexOf(InvalidKeyBindings, (ButtonCode)curButton) >= 0)
+ continue;
+
+ if (Key.BindingForKey((ButtonCode)curButton) == null) {
+#if GMOD_DLL
+ if (binding.AsSpan().IndexOfAny(";\"\n\r") >= 0)
+ continue;
+#endif
+ Cbuf.AddText($"bind \"{inputSystem.ButtonCodeToString((ButtonCode)curButton)}\" \"{binding}\"");
+ found = true;
+ break;
+ }
+ }
+
+ if (!found)
+ Warning($"Unable to bind a key for command \"{binding}\" after {numAttempts} attempt(s).\n");
+ }
+#endif
+ }
+
+ private void BindNewBinding(string idealKey, string binding) {
+#if GMOD_DLL
+ if (idealKey.AsSpan().IndexOfAny(";\"\n\r") >= 0 || binding.AsSpan().IndexOfAny(";\"\n\r") >= 0)
+ return;
+#endif
+ Cbuf.AddText($"bind \"{idealKey}\" \"{binding}\"");
}
private void UseDefaultBindings() {
- // todo
+ const string fileName = "scripts/kb_def.lst";
+ using IFileHandle? f = fileSystem.Open(fileName, FileOpenOptions.Read);
+ if (f == null) {
+#if GMOD_DLL
+ ConMsg("Couldn't open kb_def.lst\n");
+#else
+ ConMsg($"Couldn't open {fileName}\n");
+#endif
+ return;
+ }
+
+ byte[] startbuf = new byte[f.Stream.Length];
+ f.Stream.ReadExactly(startbuf);
+
+ scoped ReadOnlySpan buf = startbuf;
+ Span token = stackalloc char[1024];
+ Span keyName = stackalloc char[1024];
+ while (true) {
+ buf = Common.ParseFile(buf, token);
+ if (strlen(token) == 0)
+ break;
+ strcpy(keyName, token);
+
+ buf = Common.ParseFile(buf, token);
+ if (strlen(token) == 0)
+ break;
+
+ Key.SetBinding(inputSystem!.StringToButtonCode(keyName[..(int)strlen(keyName)]), token[..(int)strlen(token)]);
+ }
+ }
+
+ private void SetupDefaultAskConnectAcceptKey() {
+ if (Key.NameForBinding("askconnect_accept").IsEmpty) {
+ if (Key.BindingForKey(ButtonCode.KeyF3) == null)
+ Key.SetBinding(ButtonCode.KeyF3, "askconnect_accept");
+ }
}
public void WriteConfiguration(ReadOnlySpan filename = default, bool allVars = false) {
+#if !GMOD_DLL
bool isUserRequested = !filename.IsEmpty;
+#endif
if (filename.IsEmpty)
filename = "config.cfg";
+ if (!ConfigCfgExecuted)
+ return;
+
if (!Initialized)
return;
+#if !GMOD_DLL
if (!isUserRequested && commandLine.CheckParm("-default"))
return;
+#endif
if (sv.IsDedicated())
return;
- using MemoryStream str = new();
- using StreamWriter configBuff = new(str);
+ if (Key.CountBindings() <= 1) {
+ ConMsg($"skipping {filename} output, no keys bound\n");
+ return;
+ }
+
+ MatSysInterface.UpdateMaterialSystemConfig();
- configBuff.Write($"cfg/{filename}");
+ string fileName = $"cfg/{filename}";
fileSystem.CreateDirHierarchy("cfg", "MOD");
+ if (fileSystem.FileExists(fileName, "MOD") && !fileSystem.IsFileWritable(fileName, "MOD")) {
+ ConMsg($"Config file {fileName} is read-only!!\n");
+ return;
+ }
+
+ StringBuilder configBuff = new();
+ configBuff.Append("unbindall\n");
+
+ Key.WriteBindings(configBuff);
+ services.GetRequiredService().WriteVariables(configBuff, allVars);
+
+#if !SWDS
+ if (clientDLL != null && clientDLL.IN_IsKeyDown("in_jlook", out bool down) && down)
+ configBuff.Append("+jlook\n");
+#endif
+
+ if (configBuff.Length == 0)
+ return;
+
+ // TODO: see if we are doing the steam cloud logic
+ fileSystem.WriteFile(fileName, "MOD", Encoding.UTF8.GetBytes(configBuff.ToString()));
+
+ ConMsg($"Host_WriteConfiguration: Wrote {fileName}\n");
+ }
+
+#if GMOD_DLL
+ [ConCommand(helpText: "Write Lua-defined FCVAR_ARCHIVE convars to disk.")]
+ void host_writeconfig_lua() => get.LuaConVars()?.SaveManagedConVars();
+#endif
+
+ [ConCommand(helpText: "Store current settings to config.cfg (or specified .cfg file).")]
+ void host_writeconfig(in TokenizedCommand args) {
+#if GMOD_DLL
+ if (args.ArgC() >= 3) {
+ ConMsg("Usage: writeconfig \n");
+ return;
+ }
+
+ if (args.ArgC() == 2) {
+ ReadOnlySpan filename = args[1];
+ if (filename.IsEmpty)
+ return;
+
+ string outfile = new(StrTools.FileBase(filename, stackalloc char[MAX_OSPATH]));
+ WriteConfiguration($"{outfile}.cfg");
+ }
+ else
+ WriteConfiguration();
+#else
+ if (args.ArgC() > 3) {
+ ConMsg("Usage: writeconfig [full]\n");
+ ConMsg(" is required, optionally specify \"full\" to write out all archived convars.\n");
+ ConMsg("By default, only non-default values are written out.\n");
+ return;
+ }
+
+ if (args.ArgC() >= 2) {
+ bool writeAll = args.ArgC() == 3 && stricmp(args[2], "full") == 0;
+
+ ReadOnlySpan filename = args[1];
+ if (filename.IsEmpty)
+ return;
+
+ string outfile = new(StrTools.FileBase(filename, stackalloc char[MAX_OSPATH]));
+ WriteConfiguration($"{outfile}.cfg", writeAll);
+ if (!writeAll)
+ ConMsg($"Wrote partial config file \"{outfile}\" out, to write full file use host_writeconfig \"{outfile}\" full\n");
+ }
+ else
+ WriteConfiguration(null, true);
+#endif
}
public bool IsSecureServerAllowed() => true;
@@ -595,6 +792,10 @@ public void Shutdown() {
OverlayText.IsDeadFn -= OverlayText_IsDeadFn;
OverlayText.SetEndTimeFn -= OverlayText_SetEndTimeFn;
+#if !SWDS
+ WriteConfiguration();
+#endif
+
Disconnect(true);
CM.FreeMap();
diff --git a/Source.Engine/Key.cs b/Source.Engine/Key.cs
index 51b5b415e..6aba1c451 100644
--- a/Source.Engine/Key.cs
+++ b/Source.Engine/Key.cs
@@ -6,6 +6,8 @@
using Source.Common.Commands;
using Source.Common.Input;
+using System.Text;
+
namespace Source.Engine;
public struct KeyInfo
@@ -51,6 +53,21 @@ public int CountBindings() {
return c;
}
+ public void WriteBindings(StringBuilder buf) {
+ for (int i = 0; i < (int)ButtonCode.Last; i++) {
+ string? keyBinding = KeyInfo[i].KeyBinding;
+ if (string.IsNullOrEmpty(keyBinding))
+ continue;
+
+#if GMOD_DLL
+ if (keyBinding.AsSpan().IndexOfAny("\"\n\r") >= 0)
+ continue;
+#endif
+
+ buf.Append($"bind \"{inputSystem!.ButtonCodeToString((ButtonCode)i)}\" \"{keyBinding}\"\n");
+ }
+ }
+
public ReadOnlySpan NameForBinding(ReadOnlySpan binding) {
int i;
@@ -62,11 +79,11 @@ public ReadOnlySpan NameForBinding(ReadOnlySpan binding) {
string? keyBinding = KeyInfo[i].KeyBinding;
if (!string.IsNullOrEmpty(keyBinding)) {
if (keyBinding[0] == '+') {
- if (bind.Equals(keyBinding.AsSpan()[1..], StringComparison.Ordinal))
+ if (bind.Equals(keyBinding.AsSpan()[1..], StringComparison.OrdinalIgnoreCase))
return inputSystem!.ButtonCodeToString((ButtonCode)i);
}
else {
- if (bind.Equals(keyBinding, StringComparison.Ordinal))
+ if (bind.Equals(keyBinding, StringComparison.OrdinalIgnoreCase))
return inputSystem!.ButtonCodeToString((ButtonCode)i);
}
@@ -80,7 +97,11 @@ public void SetBinding(ButtonCode keynum, ReadOnlySpan cmd) {
if (keynum == ButtonCode.Invalid)
return;
- KeyInfo[(int)keynum].KeyBinding = cmd.IsEmpty ? null : new(cmd);
+ string? current = KeyInfo[(int)keynum].KeyBinding;
+ if (current != null && streq(current, cmd))
+ return;
+
+ KeyInfo[(int)keynum].KeyBinding = new(cmd);
}
public void Event(in InputEvent ev) {
@@ -227,6 +248,50 @@ void bind(in TokenizedCommand args) {
BindKey(args[1], c == 2, cmd[..strcpy(cmd, args[2])]);
}
+ [ConCommand(flags: FCvar.DontRecord, helpText: "Unbind a key.")]
+ void unbind(in TokenizedCommand args) {
+ if (args.ArgC() != 2) {
+ ConMsg("unbind : remove commands from a key\n");
+ return;
+ }
+
+ if (inputSystem == null)
+ return;
+
+ ButtonCode b = inputSystem.StringToButtonCode(args[1]);
+ if (b == ButtonCode.Invalid) {
+ ConMsg($"\"{args[1]}\" isn't a valid key\n");
+ return;
+ }
+ if (b == ButtonCode.KeyEscape) {
+ ConMsg("Can't unbind ESCAPE key\n");
+ return;
+ }
+
+ SetBinding(b, "");
+ }
+
+ [ConCommand(flags: FCvar.DontRecord, helpText: "Bind this key but only on Mac, not win32")]
+ void bind_mac(in TokenizedCommand args) {
+#if OSX
+ Span cmd = stackalloc char[1024];
+ int c = args.ArgC();
+ if (c != 2 && c != 3) {
+ ConMsg("bind [command] : attach a command to a key\n");
+ return;
+ }
+
+ BindKey(args[1], c == 2, cmd[..strcpy(cmd, args[2])]);
+#endif
+ }
+
+ [ConCommand(flags: FCvar.DontRecord, helpText: "Unbind a key on the Mac only.")]
+ void unbind_mac(in TokenizedCommand args) {
+#if OSX
+ unbind(in args);
+#endif
+ }
+
[ConCommand(flags: FCvar.DontRecord, helpText: "Unbind all keys.")]
void unbindall(in TokenizedCommand args) {
for (int i = 0; i < (int)ButtonCode.Last; i++) {
@@ -281,11 +346,8 @@ internal void Shutdown() {
}
- public ReadOnlySpan BindingForKey(ButtonCode code) {
- if (code < 0 || code > ButtonCode.Last)
- return null;
-
- if (string.IsNullOrEmpty(KeyInfo[(int)code].KeyBinding))
+ public string? BindingForKey(ButtonCode code) {
+ if (code < 0 || code >= ButtonCode.Last)
return null;
return KeyInfo[(int)code].KeyBinding;
@@ -295,10 +357,9 @@ internal ReadOnlySpan NameForBindingExact(ReadOnlySpan binding) {
ButtonCode i;
for (i = 0; i < ButtonCode.Last; i++)
- if (KeyInfo[(int)i].KeyBinding != null)
- if (KeyInfo[(int)i].KeyBinding![0] != '\0')
- if (0 == strcmp(KeyInfo[(int)i].KeyBinding, binding))
- return inputSystem == null ? null : inputSystem.ButtonCodeToString(i);
+ if (!string.IsNullOrEmpty(KeyInfo[(int)i].KeyBinding))
+ if (0 == stricmp(KeyInfo[(int)i].KeyBinding, binding))
+ return inputSystem == null ? null : inputSystem.ButtonCodeToString(i);
return null;
}
diff --git a/Source.Filesystem/ZipPackFileSearchPath.cs b/Source.Filesystem/ZipPackFileSearchPath.cs
index 8da0b3680..c06e2d551 100644
--- a/Source.Filesystem/ZipPackFileSearchPath.cs
+++ b/Source.Filesystem/ZipPackFileSearchPath.cs
@@ -94,7 +94,7 @@ public override bool IsDirectory(ReadOnlySpan path) {
public override long Size(ReadOnlySpan path) {
if (Entries.TryGetValue(filesystem.FindOrAddFileName(path), out ZipArchiveEntry? entry))
return entry.Size;
- return 0;
+ return -1;
}
public override DateTime Time(ReadOnlySpan path) {
diff --git a/Source.GUI.Controls/SectionedListPanel.cs b/Source.GUI.Controls/SectionedListPanel.cs
index 08c733743..ac73cb1f1 100644
--- a/Source.GUI.Controls/SectionedListPanel.cs
+++ b/Source.GUI.Controls/SectionedListPanel.cs
@@ -1126,8 +1126,19 @@ public int GetRowFromItemID(int itemID) {
return -1;
}
- public void GetCellBounds() {
+ public bool GetCellBounds(int itemID, int column, out int x, out int y, out int wide, out int tall) {
+ x = y = wide = tall = 0;
+ if (!IsItemIDValid(itemID))
+ return false;
+
+ ItemButton item = Items[itemID];
+ if (!item.IsVisible())
+ return false;
+
+ item.GetBounds(out x, out y, out wide, out tall);
+ item.GetCellBounds(column, ref x, ref wide);
+ return true;
}
public void GetSectionHeaderBounds() {
diff --git a/Source.SDLInputSystem/SDL3_InputSystem.cs b/Source.SDLInputSystem/SDL3_InputSystem.cs
index 48dcb9121..1fb498394 100644
--- a/Source.SDLInputSystem/SDL3_InputSystem.cs
+++ b/Source.SDLInputSystem/SDL3_InputSystem.cs
@@ -4,9 +4,12 @@
using SDL;
using Source;
+using Source.Common.Commands;
using Source.Common.Input;
using Source.Common.Launcher;
+using System.Runtime.InteropServices;
+
namespace Nucleus.SDL3Window;
public class InputState
@@ -175,9 +178,88 @@ static SDL3_InputSystem() {
scantokey[(int)SDL_Scancode.SDL_SCANCODE_RALT] = ButtonCode.KeyRAlt;
scantokey[(int)SDL_Scancode.SDL_SCANCODE_RGUI] = ButtonCode.KeyRWin;
+ scantokey_QWERTY = (ButtonCode[])scantokey.Clone();
+
ButtonCode_InitKeyTranslationTable();
+ ButtonCode_UpdateScanCodeLayout();
+ }
+
+ static ButtonCode[] scantokey_QWERTY;
+
+#if WIN32
+ static readonly ButtonCode[] s_pScanToButtonCode_QWERTY = [
+ ButtonCode.None, ButtonCode.KeyEscape, ButtonCode.Key1, ButtonCode.Key2, ButtonCode.Key3, ButtonCode.Key4, ButtonCode.Key5, ButtonCode.Key6,
+ ButtonCode.Key7, ButtonCode.Key8, ButtonCode.Key9, ButtonCode.Key0, ButtonCode.KeyMinus, ButtonCode.KeyEqual, ButtonCode.KeyBackspace, ButtonCode.KeyTab,
+ ButtonCode.KeyQ, ButtonCode.KeyW, ButtonCode.KeyE, ButtonCode.KeyR, ButtonCode.KeyT, ButtonCode.KeyY, ButtonCode.KeyU, ButtonCode.KeyI,
+ ButtonCode.KeyO, ButtonCode.KeyP, ButtonCode.KeyLBracket, ButtonCode.KeyRBracket, ButtonCode.KeyEnter, ButtonCode.KeyLControl, ButtonCode.KeyA, ButtonCode.KeyS,
+ ButtonCode.KeyD, ButtonCode.KeyF, ButtonCode.KeyG, ButtonCode.KeyH, ButtonCode.KeyJ, ButtonCode.KeyK, ButtonCode.KeyL, ButtonCode.KeySemicolon,
+ ButtonCode.KeyApostrophe, ButtonCode.KeyBackquote, ButtonCode.KeyLShift, ButtonCode.KeyBackslash, ButtonCode.KeyZ, ButtonCode.KeyX, ButtonCode.KeyC, ButtonCode.KeyV,
+ ButtonCode.KeyB, ButtonCode.KeyN, ButtonCode.KeyM, ButtonCode.KeyComma, ButtonCode.KeyPeriod, ButtonCode.KeySlash, ButtonCode.KeyRShift, ButtonCode.KeyPadMultiply,
+ ButtonCode.KeyLAlt, ButtonCode.KeySpace, ButtonCode.KeyCapsLock, ButtonCode.KeyF1, ButtonCode.KeyF2, ButtonCode.KeyF3, ButtonCode.KeyF4, ButtonCode.KeyF5,
+ ButtonCode.KeyF6, ButtonCode.KeyF7, ButtonCode.KeyF8, ButtonCode.KeyF9, ButtonCode.KeyF10, ButtonCode.KeyNumLock, ButtonCode.KeyScrollLock, ButtonCode.KeyHome,
+ ButtonCode.KeyUp, ButtonCode.KeyPageUp, ButtonCode.KeyPadMinus, ButtonCode.KeyLeft, ButtonCode.KeyPad5, ButtonCode.KeyRight, ButtonCode.KeyPadPlus, ButtonCode.KeyEnd,
+ ButtonCode.KeyDown, ButtonCode.KeyPageDown, ButtonCode.KeyInsert, ButtonCode.KeyDelete, ButtonCode.None, ButtonCode.None, ButtonCode.None, ButtonCode.KeyF11,
+ ButtonCode.KeyF12, ButtonCode.KeyBreak,
+ ];
+
+ static readonly SDL_Scancode[] s_pScanToSDLScancode = [
+ SDL_Scancode.SDL_SCANCODE_UNKNOWN, SDL_Scancode.SDL_SCANCODE_ESCAPE, SDL_Scancode.SDL_SCANCODE_1, SDL_Scancode.SDL_SCANCODE_2, SDL_Scancode.SDL_SCANCODE_3, SDL_Scancode.SDL_SCANCODE_4, SDL_Scancode.SDL_SCANCODE_5, SDL_Scancode.SDL_SCANCODE_6,
+ SDL_Scancode.SDL_SCANCODE_7, SDL_Scancode.SDL_SCANCODE_8, SDL_Scancode.SDL_SCANCODE_9, SDL_Scancode.SDL_SCANCODE_0, SDL_Scancode.SDL_SCANCODE_MINUS, SDL_Scancode.SDL_SCANCODE_EQUALS, SDL_Scancode.SDL_SCANCODE_BACKSPACE, SDL_Scancode.SDL_SCANCODE_TAB,
+ SDL_Scancode.SDL_SCANCODE_Q, SDL_Scancode.SDL_SCANCODE_W, SDL_Scancode.SDL_SCANCODE_E, SDL_Scancode.SDL_SCANCODE_R, SDL_Scancode.SDL_SCANCODE_T, SDL_Scancode.SDL_SCANCODE_Y, SDL_Scancode.SDL_SCANCODE_U, SDL_Scancode.SDL_SCANCODE_I,
+ SDL_Scancode.SDL_SCANCODE_O, SDL_Scancode.SDL_SCANCODE_P, SDL_Scancode.SDL_SCANCODE_LEFTBRACKET, SDL_Scancode.SDL_SCANCODE_RIGHTBRACKET, SDL_Scancode.SDL_SCANCODE_RETURN, SDL_Scancode.SDL_SCANCODE_LCTRL, SDL_Scancode.SDL_SCANCODE_A, SDL_Scancode.SDL_SCANCODE_S,
+ SDL_Scancode.SDL_SCANCODE_D, SDL_Scancode.SDL_SCANCODE_F, SDL_Scancode.SDL_SCANCODE_G, SDL_Scancode.SDL_SCANCODE_H, SDL_Scancode.SDL_SCANCODE_J, SDL_Scancode.SDL_SCANCODE_K, SDL_Scancode.SDL_SCANCODE_L, SDL_Scancode.SDL_SCANCODE_SEMICOLON,
+ SDL_Scancode.SDL_SCANCODE_APOSTROPHE, SDL_Scancode.SDL_SCANCODE_GRAVE, SDL_Scancode.SDL_SCANCODE_LSHIFT, SDL_Scancode.SDL_SCANCODE_BACKSLASH, SDL_Scancode.SDL_SCANCODE_Z, SDL_Scancode.SDL_SCANCODE_X, SDL_Scancode.SDL_SCANCODE_C, SDL_Scancode.SDL_SCANCODE_V,
+ SDL_Scancode.SDL_SCANCODE_B, SDL_Scancode.SDL_SCANCODE_N, SDL_Scancode.SDL_SCANCODE_M, SDL_Scancode.SDL_SCANCODE_COMMA, SDL_Scancode.SDL_SCANCODE_PERIOD, SDL_Scancode.SDL_SCANCODE_SLASH, SDL_Scancode.SDL_SCANCODE_RSHIFT, SDL_Scancode.SDL_SCANCODE_KP_MULTIPLY,
+ SDL_Scancode.SDL_SCANCODE_LALT, SDL_Scancode.SDL_SCANCODE_SPACE, SDL_Scancode.SDL_SCANCODE_CAPSLOCK, SDL_Scancode.SDL_SCANCODE_F1, SDL_Scancode.SDL_SCANCODE_F2, SDL_Scancode.SDL_SCANCODE_F3, SDL_Scancode.SDL_SCANCODE_F4, SDL_Scancode.SDL_SCANCODE_F5,
+ SDL_Scancode.SDL_SCANCODE_F6, SDL_Scancode.SDL_SCANCODE_F7, SDL_Scancode.SDL_SCANCODE_F8, SDL_Scancode.SDL_SCANCODE_F9, SDL_Scancode.SDL_SCANCODE_F10, SDL_Scancode.SDL_SCANCODE_NUMLOCKCLEAR, SDL_Scancode.SDL_SCANCODE_SCROLLLOCK, SDL_Scancode.SDL_SCANCODE_KP_7,
+ SDL_Scancode.SDL_SCANCODE_KP_8, SDL_Scancode.SDL_SCANCODE_KP_9, SDL_Scancode.SDL_SCANCODE_KP_MINUS, SDL_Scancode.SDL_SCANCODE_KP_4, SDL_Scancode.SDL_SCANCODE_KP_5, SDL_Scancode.SDL_SCANCODE_KP_6, SDL_Scancode.SDL_SCANCODE_KP_PLUS, SDL_Scancode.SDL_SCANCODE_KP_1,
+ SDL_Scancode.SDL_SCANCODE_KP_2, SDL_Scancode.SDL_SCANCODE_KP_3, SDL_Scancode.SDL_SCANCODE_KP_0, SDL_Scancode.SDL_SCANCODE_KP_PERIOD, SDL_Scancode.SDL_SCANCODE_UNKNOWN, SDL_Scancode.SDL_SCANCODE_UNKNOWN, SDL_Scancode.SDL_SCANCODE_NONUSBACKSLASH, SDL_Scancode.SDL_SCANCODE_F11,
+ SDL_Scancode.SDL_SCANCODE_F12,
+ ];
+
+ [DllImport("user32.dll")] static extern nint GetKeyboardLayout(uint idThread);
+ [DllImport("user32.dll")] static extern int GetKeyboardLayoutList(int nBuff, [Out] nint[] lpList);
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern nint LoadKeyboardLayoutW(string pwszKLID, uint flags);
+ [DllImport("user32.dll")] static extern bool UnloadKeyboardLayout(nint hkl);
+ [DllImport("user32.dll")] static extern uint MapVirtualKeyExW(uint uCode, uint uMapType, nint dwhkl);
+#endif
+
+ static void ButtonCode_UpdateScanCodeLayout() {
+ Array.Copy(scantokey_QWERTY, scantokey, scantokey.Length);
+
+#if WIN32
+ nint[] layoutList = new nint[128];
+ int layoutCount = GetKeyboardLayoutList(layoutList.Length, layoutList);
+ nint currentKb = GetKeyboardLayout(0);
+ nint englishKb = LoadKeyboardLayoutW("00000409", 0);
+
+ if (englishKb != 0 && englishKb != currentKb) {
+ for (uint i = 0; i < 128; i++) {
+ ButtonCode code = i < s_pScanToButtonCode_QWERTY.Length ? s_pScanToButtonCode_QWERTY[i] : ButtonCode.None;
+
+ if (code != ButtonCode.None && code != ButtonCode.KeyBackquote && code >= ButtonCode.Key0 && code <= ButtonCode.KeyEqual) {
+ uint vk = MapVirtualKeyExW(i, 1, englishKb);
+ uint newScanCode = MapVirtualKeyExW(vk, 0, currentKb) & 0x0000007F;
+
+ if (newScanCode < s_pScanToSDLScancode.Length) {
+ SDL_Scancode sdlScanCode = s_pScanToSDLScancode[newScanCode];
+ if (sdlScanCode != SDL_Scancode.SDL_SCANCODE_UNKNOWN)
+ scantokey[(int)sdlScanCode] = code;
+ }
+ }
+ }
+
+ if (Array.IndexOf(layoutList, englishKb, 0, Math.Max(layoutCount, 0)) < 0)
+ UnloadKeyboardLayout(englishKb);
+ }
+#endif
+
+ scantokey[(int)SDL_Scancode.SDL_SCANCODE_UNKNOWN] = ButtonCode.None;
}
+ [ConCommand(helpText: "Updates game keyboard layout to current windows keyboard setting.")]
+ static void key_updatelayout() => ButtonCode_UpdateScanCodeLayout();
+
static ButtonCode[] virtualKeyToButtonCode = null!;
static int[] buttonCodeToVirtual = null!;
@@ -253,17 +335,54 @@ static void ButtonCode_InitKeyTranslationTable() {
}
+#if OSX
+ static readonly ButtonCode[] s_pCocoaKeyToButtonCode = [
+ ButtonCode.KeyA, ButtonCode.KeyS, ButtonCode.KeyD, ButtonCode.KeyF, ButtonCode.KeyH, ButtonCode.KeyG, ButtonCode.KeyZ, ButtonCode.KeyX,
+ ButtonCode.KeyC, ButtonCode.KeyV, ButtonCode.KeyBackquote, ButtonCode.KeyB, ButtonCode.KeyQ, ButtonCode.KeyW, ButtonCode.KeyE, ButtonCode.KeyR,
+ ButtonCode.KeyY, ButtonCode.KeyT, ButtonCode.Key1, ButtonCode.Key2, ButtonCode.Key3, ButtonCode.Key4, ButtonCode.Key6, ButtonCode.Key5,
+ ButtonCode.KeyEqual, ButtonCode.Key9, ButtonCode.Key7, ButtonCode.KeyMinus, ButtonCode.Key8, ButtonCode.Key0, ButtonCode.KeyRBracket, ButtonCode.KeyO,
+ ButtonCode.KeyU, ButtonCode.KeyLBracket, ButtonCode.KeyI, ButtonCode.KeyP, ButtonCode.KeyEnter, ButtonCode.KeyL, ButtonCode.KeyJ, ButtonCode.KeyApostrophe,
+ ButtonCode.KeyK, ButtonCode.KeySemicolon, ButtonCode.KeyBackslash, ButtonCode.KeyComma, ButtonCode.KeySlash, ButtonCode.KeyN, ButtonCode.KeyM, ButtonCode.KeyPeriod,
+ ButtonCode.KeyTab, ButtonCode.KeySpace, ButtonCode.KeyBackquote, ButtonCode.KeyBackspace, ButtonCode.None, ButtonCode.KeyEscape, ButtonCode.KeyRWin, ButtonCode.KeyLWin,
+ ButtonCode.KeyLShift, ButtonCode.KeyCapsLock, ButtonCode.KeyLAlt, ButtonCode.KeyLControl, ButtonCode.KeyLShift, ButtonCode.None, ButtonCode.KeyRControl, ButtonCode.None,
+ ButtonCode.None, ButtonCode.KeyPadDecimal, ButtonCode.None, ButtonCode.KeyPadMultiply, ButtonCode.None, ButtonCode.KeyPadPlus, ButtonCode.None, ButtonCode.KeyNumLock,
+ ButtonCode.None, ButtonCode.None, ButtonCode.None, ButtonCode.KeyPadDivide, ButtonCode.KeyPadEnter, ButtonCode.None, ButtonCode.KeyPadMinus, ButtonCode.None,
+ ButtonCode.None, ButtonCode.KeyPadDivide, ButtonCode.KeyPad0, ButtonCode.KeyPad1, ButtonCode.KeyPad2, ButtonCode.KeyPad3, ButtonCode.KeyPad4, ButtonCode.KeyPad5,
+ ButtonCode.KeyPad6, ButtonCode.KeyPad7, ButtonCode.None, ButtonCode.KeyPad8, ButtonCode.KeyPad9, ButtonCode.None, ButtonCode.None, ButtonCode.None,
+ ButtonCode.KeyF5, ButtonCode.KeyF6, ButtonCode.KeyF7, ButtonCode.KeyF3, ButtonCode.KeyF8, ButtonCode.KeyF9, ButtonCode.None, ButtonCode.KeyF11,
+ ButtonCode.None, ButtonCode.None, ButtonCode.None, ButtonCode.None, ButtonCode.None, ButtonCode.KeyF10, ButtonCode.KeyApp, ButtonCode.KeyF12,
+ ButtonCode.None, ButtonCode.None, ButtonCode.KeyInsert, ButtonCode.KeyHome, ButtonCode.KeyPageUp, ButtonCode.KeyDelete, ButtonCode.KeyF4, ButtonCode.KeyEnd,
+ ButtonCode.KeyF2, ButtonCode.KeyPageDown, ButtonCode.KeyF1, ButtonCode.KeyLeft, ButtonCode.KeyRight, ButtonCode.KeyDown, ButtonCode.KeyUp, ButtonCode.None,
+ ];
+#endif
+
static bool MapVirtualKeyToButtonCode(int virtualKeyCode, out ButtonCode pOut) {
if (virtualKeyCode < 0)
pOut = (ButtonCode)(-1 * virtualKeyCode);
else {
+#if OSX
+ if (virtualKeyCode >= s_pCocoaKeyToButtonCode.Length) {
+ pOut = ButtonCode.None;
+ return false;
+ }
+ pOut = s_pCocoaKeyToButtonCode[virtualKeyCode];
+#else
virtualKeyCode &= 0x000000ff;
pOut = (ButtonCode)scantokey[virtualKeyCode];
+#endif
}
return true;
}
+ static ButtonCode WindowEventVirtualCode(WindowEvent ev, ButtonCode scanCode) {
+#if WIN32
+ if (ev.WindowsVirtualKey > 0)
+ return virtualKeyToButtonCode[ev.WindowsVirtualKey];
+#endif
+ return scanCode;
+ }
+
public void PostButtonPressedEvent(InputEventType type, int tick, ButtonCode scanCode, ButtonCode virtualCode) {
InputState state = InputState;
@@ -354,21 +473,21 @@ public void PollInputState_Platform() {
newEv.Data = ev.WasWindowFocused ? 1 : 0;
PostUserEvent(in newEv);
- if (ev.ModifierKeyMask == 0) {
+ if (!ev.WasWindowFocused) {
ResetInputState();
}
}
break;
case WindowEventType.KeyDown: {
- if (MapVirtualKeyToButtonCode(ev.VirtualKeyCode, out ButtonCode virtualCode)) {
- ButtonCode scancode = virtualCode;
+ if (MapVirtualKeyToButtonCode(ev.VirtualKeyCode, out ButtonCode scancode)) {
+ ButtonCode virtualCode = WindowEventVirtualCode(ev, scancode);
if (scancode != ButtonCode.None)
PostButtonPressedEvent(InputEventType.IE_ButtonPressed, LastSampleTick, scancode, virtualCode);
InputEvent newEv = new() {
Tick = GetPollTick(),
Type = InputEventType.Gui_KeyCodeTyped,
- Data = (int)scancode
+ Data = (int)virtualCode
};
PostUserEvent(newEv);
}
@@ -385,8 +504,8 @@ public void PollInputState_Platform() {
break;
case WindowEventType.KeyUp: {
- if (MapVirtualKeyToButtonCode(ev.VirtualKeyCode, out ButtonCode virtualCode)) {
- ButtonCode scancode = virtualCode;
+ if (MapVirtualKeyToButtonCode(ev.VirtualKeyCode, out ButtonCode scancode)) {
+ ButtonCode virtualCode = WindowEventVirtualCode(ev, scancode);
if (scancode != ButtonCode.None)
PostButtonReleasedEvent(InputEventType.IE_ButtonReleased, LastSampleTick, scancode, virtualCode);
}
diff --git a/Source.SDLManager/SDL3_Window.cs b/Source.SDLManager/SDL3_Window.cs
index ed6c0bac3..b2d3be4b1 100644
--- a/Source.SDLManager/SDL3_Window.cs
+++ b/Source.SDLManager/SDL3_Window.cs
@@ -5,6 +5,8 @@
using System.Collections.Concurrent;
using System.Numerics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
namespace Source.SDLManager;
@@ -256,9 +258,16 @@ private void HandleKeyEvent(ref SDL_Event ev) {
bool pressed = ev.Type == SDL_EventType.SDL_EVENT_KEY_DOWN;
WindowEvent newEvent = new WindowEvent();
newEvent.EventType = pressed ? WindowEventType.KeyDown : WindowEventType.KeyUp;
- newEvent.VirtualKeyCode = (int)ev.key.scancode;
newEvent.UTF8Key = '\0';
newEvent.UTF8KeyUnmodified = '\0';
+#if OSX
+ if (!HandleCocoaKeyEvent(ref ev, newEvent, pressed))
+ return;
+#else
+ newEvent.VirtualKeyCode = (int)ev.key.scancode;
+#if WIN32
+ newEvent.WindowsVirtualKey = WindowsVirtualKeys[WindowsScanCodeIndex(ev.key.raw)];
+#endif
switch (ev.key.key) {
case SDL_Keycode.SDLK_CAPSLOCK: KeySymCase(newEvent, GranularKeyModifier.CapsLock, pressed, ButtonCode.KeyCapsLock); break;
@@ -275,6 +284,7 @@ private void HandleKeyEvent(ref SDL_Event ev) {
case SDL_Keycode.SDLK_LALT: KeySymCase(newEvent, GranularKeyModifier.AltL, pressed, ButtonCode.KeyLAlt); break;
case SDL_Keycode.SDLK_RALT: KeySymCase(newEvent, GranularKeyModifier.AltR, pressed, ButtonCode.KeyRAlt); break;
}
+#endif
KeyModifierMask = 0;
@@ -294,6 +304,45 @@ private void HandleKeyEvent(ref SDL_Event ev) {
PostEvent(newEvent);
}
+#if OSX
+ private bool HandleCocoaKeyEvent(ref SDL_Event ev, WindowEvent newEvent, bool pressed) {
+ switch (ev.key.key) {
+ case SDL_Keycode.SDLK_CAPSLOCK: {
+ if (!pressed)
+ return false;
+ bool locked = (ev.key.mod & SDL_Keymod.SDL_KMOD_CAPS) != 0;
+ newEvent.EventType = locked ? WindowEventType.KeyDown : WindowEventType.KeyUp;
+ KeySymCase(newEvent, GranularKeyModifier.CapsLock, locked, ButtonCode.KeyCapsLock);
+ return true;
+ }
+
+ case SDL_Keycode.SDLK_LSHIFT: return CocoaModifierCase(newEvent, GranularKeyModifier.ShiftL, GranularKeyModifier.ShiftR, pressed, ButtonCode.KeyLShift);
+ case SDL_Keycode.SDLK_RSHIFT: return CocoaModifierCase(newEvent, GranularKeyModifier.ShiftR, GranularKeyModifier.ShiftL, pressed, ButtonCode.KeyLShift);
+
+ case SDL_Keycode.SDLK_LCTRL: return CocoaModifierCase(newEvent, GranularKeyModifier.ControlL, GranularKeyModifier.ControlR, pressed, ButtonCode.KeyLControl);
+ case SDL_Keycode.SDLK_RCTRL: return CocoaModifierCase(newEvent, GranularKeyModifier.ControlR, GranularKeyModifier.ControlL, pressed, ButtonCode.KeyLControl);
+
+ case SDL_Keycode.SDLK_LGUI: return CocoaModifierCase(newEvent, GranularKeyModifier.CommandL, GranularKeyModifier.CommandR, pressed, ButtonCode.KeyLWin);
+ case SDL_Keycode.SDLK_RGUI: return CocoaModifierCase(newEvent, GranularKeyModifier.CommandR, GranularKeyModifier.CommandL, pressed, ButtonCode.KeyLWin);
+
+ case SDL_Keycode.SDLK_LALT: return CocoaModifierCase(newEvent, GranularKeyModifier.AltL, GranularKeyModifier.AltR, pressed, ButtonCode.KeyLAlt);
+ case SDL_Keycode.SDLK_RALT: return CocoaModifierCase(newEvent, GranularKeyModifier.AltR, GranularKeyModifier.AltL, pressed, ButtonCode.KeyLAlt);
+ }
+
+ if (ev.key.raw == 0 && ev.key.scancode != SDL_Scancode.SDL_SCANCODE_A)
+ return false;
+
+ newEvent.VirtualKeyCode = ev.key.raw;
+ return true;
+ }
+
+ private bool CocoaModifierCase(WindowEvent ev, GranularKeyModifier side, GranularKeyModifier otherSide, bool pressed, ButtonCode key) {
+ bool otherSideHeld = (KeyModifiers & otherSide) != 0;
+ KeySymCase(ev, side, pressed, key);
+ return !otherSideHeld;
+ }
+#endif
+
private ConcurrentQueue Events = [];
private WindowEvent PostEvent(WindowEvent newEvent, bool debugEvent = false) {
Events.Enqueue(newEvent);
@@ -302,7 +351,36 @@ private WindowEvent PostEvent(WindowEvent newEvent, bool debugEvent = false) {
public SDL3_Window Create(string title, int width, int height, SDL_WindowFlags flags) {
window = SDL3.SDL_CreateWindow(title, width, height, flags);
+#if WIN32
+ SDL3.SDL_SetWindowsMessageHook(&WindowsMessageHook, 0);
+#endif
return this;
}
+
+#if WIN32
+ const uint WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105;
+ const int KF_EXTENDED = 0x0100;
+
+ static readonly int[] WindowsVirtualKeys = new int[512];
+
+ static int WindowsScanCodeIndex(int scanCode) => (scanCode & 0xFF) | ((scanCode & 0xFF00) != 0 ? 0x100 : 0);
+
+ [UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
+ static SDLBool WindowsMessageHook(nint userdata, MSG* msg) {
+ uint message = msg->message;
+ if (message == WM_KEYDOWN || message == WM_KEYUP || message == WM_SYSKEYDOWN || message == WM_SYSKEYUP) {
+ int keyFlags = (int)(((long)msg->lParam >> 16) & 0xFFFF);
+ int scanCode = keyFlags & 0x7F;
+ if (scanCode != 0) {
+ if ((keyFlags & KF_EXTENDED) == KF_EXTENDED)
+ scanCode |= 0xE000;
+ else if (scanCode == 0x45)
+ scanCode = 0xE046;
+ WindowsVirtualKeys[WindowsScanCodeIndex(scanCode)] = (int)(nuint)msg->wParam & 0xFF;
+ }
+ }
+ return true;
+ }
+#endif
}
\ No newline at end of file