Keyboard.current.keyboardLayout Always return us
I'm try to switch keyboard layout from us to fr and from fr to us but Keyboard.current.keyboardLayout always return us.
with command on below:
setxkbmap -query | grep layout
On French keyboard i get : layout: fr,us
On English (US) keyboard i get : layout: us
EDIT:
Windows and Mac OS X same problem
Hmm, can't reproduce on Windows or Mac. Any more details you can provide about your setup? Is this in the editor or in the player or both?
@mrdev023 Would you be able to provide a minimal repro project? That would help us to see the issue better. Thanks!
Work fine on Windows but on linux and mac return always us.
My current workaround:
jslib
mergeInto(LibraryManager.library, {
[...]
GetKeyboardLayout: function (callback) {
window.navigator.keyboard.getLayoutMap().then(function (keyboard) {
var keyboardLayout = keyboard.get('KeyQ') + keyboard.get('KeyW') + keyboard.get('KeyE') + keyboard.get('KeyR') + keyboard.get('KeyT') + keyboard.get('KeyY');
if (keyboardLayout === 'azerty') {
Runtime.dynCall('vi', callback, [getPtrFromString('fr')]);
} else {
Runtime.dynCall('vi', callback, [getPtrFromString('us')]);
}
}).catch(function () {
Runtime.dynCall('vi', callback, [getPtrFromString('us')]);
});
function getPtrFromString(str) {
var buffer = _malloc(lengthBytesUTF8(str) + 1);
writeStringToMemory(str, buffer);
return buffer;
}
}
});
Temporary Script:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Xml;
using System.Text;
using Limouzik.PlatformUtilsManager;
using UnityEngine;
using UnityEngine.InputSystem;
using Debug = UnityEngine.Debug;
using AOT;
public class KeyboardKeyLabel
{
public delegate void KeyboardLayoutCallback(string layout);
private static string currentKeyboardLayout = "us";
private static SortedDictionary<string, SortedDictionary<string, string>> keyboardLayoutKeyLabels;
private static SortedDictionary<string, SortedDictionary<string, string>> keyboardLayoutKeyLabelsMac;
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
private static Dictionary<byte, string> primaryLanguageIds = new Dictionary<byte, string> // https://docs.microsoft.com/fr-fr/windows/desktop/Intl/language-identifier-constants-and-strings
{
{0x0c, "fr"}
};
[DllImport("user32.dll")]
private static extern IntPtr GetKeyboardLayout(int idThread); // https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-getkeyboardlayout
#endif
#if UNITY_WEBGL && !UNITY_EDITOR
public delegate void SimpleCallback(System.IntPtr ptr);
[DllImport("__Internal")]
private static extern void GetKeyboardLayout(SimpleCallback callback); // return layout
public static KeyboardLayoutCallback callbackInstance = (layout) => { };
[MonoPInvokeCallback(typeof(SimpleCallback))]
public static void Callback(System.IntPtr ptr)
{
string result = Marshal.PtrToStringAuto(ptr);
Debug.Log("__Internal result :" + result);
if (result != null)
{
callbackInstance(result.ToLower().Substring(0, 2));
return;
}
}
#endif
private static string RunBashCommand(string command)
{
Process myProcess = new Process();
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.FileName = "bash";
myProcess.StartInfo.Arguments = "-c \"" + command + "\"";
myProcess.EnableRaisingEvents = true;
myProcess.Start();
StringBuilder standardOutput = new StringBuilder();
while (!myProcess.HasExited)
{
standardOutput.Append(myProcess.StandardOutput.ReadToEnd());
}
standardOutput.Append(myProcess.StandardOutput.ReadToEnd());
int ExitCode = myProcess.ExitCode;
if (ExitCode == 0)
{
return standardOutput.ToString().ToLower().Substring(0, 2);
}
return null;
}
private static void GetCurrentKeyboardLayout(Keyboard keyboard, KeyboardLayoutCallback callback)
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
IntPtr HKL = GetKeyboardLayout(0);
byte primaryLanguageId = (byte)(HKL.ToInt32() & 0xff);
if (primaryLanguageIds.ContainsKey(primaryLanguageId))
{
callback(primaryLanguageIds[primaryLanguageId]);
return;
}
#elif UNITY_EDITOR_LINUX || UNITY_STANDALONE_LINUX // InputSystem Issue active #609 (https://github.com/Unity-Technologies/InputSystem/issues/609)
string command = "setxkbmap -query | grep layout | cut -d: -f2 | sed \\\"s/ //g\\\" | cut -d, -f1";
string result = RunBashCommand(command);
if (result != null) {
callback(result.ToLower().Substring(0, 2));
return;
}
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX // InputSystem Issue active #609 (https://github.com/Unity-Technologies/InputSystem/issues/609)
string command = "defaults read com.apple.HIToolbox AppleCurrentKeyboardLayoutInputSourceID | sed 's/com.apple.keylayout.//g'";
string result = RunBashCommand(command);
if (result != null) {
callback(result.ToLower().Substring(0, 2));
return;
}
#elif UNITY_WEBGL
callbackInstance = callback;
GetKeyboardLayout(Callback);
#endif
if (keyboard != null) callback(keyboard.keyboardLayout);
return;
}
public static string GetCurrentKeyboardLayout()
{
return currentKeyboardLayout;
}
private static void SetCurrentKeyboardLayout(string layout)
{
if (!keyboardLayoutKeyLabels.ContainsKey(layout))
{
Debug.Log(layout + " layout not supported return back to us");
layout = "us";
}
currentKeyboardLayout = layout;
Debug.Log("CurrentKeyboardLayout:" + currentKeyboardLayout);
}
public static void Init()
{
InputSystem.onDeviceChange += (device, change) =>
{
if (change == InputDeviceChange.ConfigurationChanged && device.layout.Equals("Keyboard"))
{
Keyboard keyboard = (Keyboard) device;
GetCurrentKeyboardLayout(Keyboard.current, (layout) => {
SetCurrentKeyboardLayout(layout);
});
}
};
keyboardLayoutKeyLabels = new SortedDictionary<string, SortedDictionary<string, string>>();
keyboardLayoutKeyLabelsMac = new SortedDictionary<string, SortedDictionary<string, string>>();
TextAsset[] assets = Resources.LoadAll<TextAsset>("KeyboardKeyLabel/Default");
foreach (TextAsset asset in assets)
{
keyboardLayoutKeyLabels.Add(asset.name, LoadKeyboardKeyLabel(asset.text));
}
TextAsset[] assetsMac = Resources.LoadAll<TextAsset>("KeyboardKeyLabel/Mac");
foreach (TextAsset asset in assetsMac)
{
keyboardLayoutKeyLabelsMac.Add(asset.name, LoadKeyboardKeyLabel(asset.text));
}
GetCurrentKeyboardLayout(Keyboard.current, (layout) => {
SetCurrentKeyboardLayout(layout);
});
}
public static string GetKeyboardLabel(string key)
{
if (PlatformUtils.IsOnMacScene())
{
if (!keyboardLayoutKeyLabelsMac[currentKeyboardLayout].ContainsKey(key)) return "";
return keyboardLayoutKeyLabelsMac[currentKeyboardLayout][key];
}
else
{
if (!keyboardLayoutKeyLabels[currentKeyboardLayout].ContainsKey(key)) return "";
return keyboardLayoutKeyLabels[currentKeyboardLayout][key];
}
}
private static SortedDictionary<string, string> LoadKeyboardKeyLabel(string text) {
XmlDocument xml = new XmlDocument();
xml.LoadXml(text);
XmlNodeList resources = xml.SelectNodes("Keys/Key");
SortedDictionary<string, string> dic = new SortedDictionary<string, string>();
foreach (XmlNode node in resources)
{
dic.Add(node.Attributes["name"].Value, node.InnerText);
}
return dic;
}
}
InputSystem.onDeviceChange is not call on WebGL
This is on Mac with French keyboard.
And it is indeed a bug on Linux. Filed: https://issuetracker.unity3d.com/product/unity/issues/guid/1167021/ Closing.