Skip to content

Commit

Permalink
Fix scaling overlap + add install script and partial send (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
nyakowint authored Nov 29, 2023
1 parent 0a576d5 commit adcb329
Show file tree
Hide file tree
Showing 7 changed files with 177 additions and 92 deletions.
26 changes: 18 additions & 8 deletions KeyboardOSC/ChatModeManager.cs → KeyboardOSC/ChatMode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@

namespace KeyboardOSC;

public static class ChatModeManager
public static class ChatMode
{
private static bool _isSilentMsg;
private static bool _allowPartialSend;
private static string _currentText = "";
private static string _lastMsg = "";
private static DateTime _lastTypingTime;
Expand Down Expand Up @@ -54,16 +55,17 @@ private static void ProcessKey(VirtualKeyCode key, KeyboardKey.VirtualKeyEventDa
var lastSpaceIndex = _currentText.LastIndexOf(' ');
_currentText = lastSpaceIndex >= 0 ? _currentText.Substring(0, lastSpaceIndex) : "";
UpdateChatText(_currentText);
#if DEBUG
Logger.LogInfo("bulk deleting chat text: " + _currentText);
#endif
return;
}

_currentText = _currentText.Remove(key is VirtualKeyCode.DELETE ? 0 : _currentText.Length - 1, 1);
UpdateChatText(_currentText);
Logger.LogInfo("deleting chat text: " + _currentText);
return;
}
// silent switch (no pop sound)
// silent switch (no sound on send, no typing indicator)
case VirtualKeyCode.TAB:
_isSilentMsg = !_isSilentMsg;
UpdateChatColor();
Expand All @@ -72,7 +74,7 @@ private static void ProcessKey(VirtualKeyCode key, KeyboardKey.VirtualKeyEventDa
case VirtualKeyCode.ESCAPE:
_currentText = "";
UpdateChatText(_currentText);
Logger.LogInfo("clearing chat text");
Logger.LogInfo("INPUT CLEARED");
SendTyping(false);
return;
case VirtualKeyCode.END:
Expand All @@ -92,15 +94,20 @@ private static void ProcessKey(VirtualKeyCode key, KeyboardKey.VirtualKeyEventDa
_currentText += GUIUtility.systemCopyBuffer;
UpdateChatText(_currentText);
return;
// that silly "send as you're typing" quirk some other osc apps do
// no idea if this will break to the rate limit like my old method did, we'll see
case VirtualKeyCode.F6:
_allowPartialSend = !_allowPartialSend;
break;
}


if (key is VirtualKeyCode.RETURN)
{
if (_currentText.Length <= 0) return;
Logger.LogInfo("sending chat text: " + _currentText);
Logger.LogInfo("CHAT SENT: " + _currentText);
_lastMsg = _currentText;
SendMessage("/chatbox/input", _currentText, true, _isSilentMsg);
SendMessage("/chatbox/input", _currentText, true, !_isSilentMsg);
UpdateChatText("");
_currentText = "";
_isSilentMsg = false;
Expand All @@ -114,7 +121,6 @@ private static void ProcessKey(VirtualKeyCode key, KeyboardKey.VirtualKeyEventDa
SendTyping(true);
_currentText += character;
UpdateChatText(_currentText);
Logger.LogInfo("updating chat text with " + _currentText);
}

private static void SendMessage(string address, string msg, bool now, bool sound)
Expand All @@ -124,9 +130,13 @@ private static void SendMessage(string address, string msg, bool now, bool sound

private static void SendTyping(bool typing)
{
if (typing && (DateTime.Now - _lastTypingTime).TotalSeconds <= 2) return;
if (typing && (DateTime.Now - _lastTypingTime).TotalSeconds <= 2 || _isSilentMsg) return;
_lastTypingTime = DateTime.Now;
Tools.SendOsc("/chatbox/typing", typing);
if (_allowPartialSend)
{
SendMessage("/chatbox/input", _currentText, true, false);
}
}

public static void Setup(TextMeshProUGUI obText)
Expand Down
23 changes: 11 additions & 12 deletions KeyboardOSC/Patches.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
using System.Collections.Generic;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
using WindowsInput;
using WindowsInput.Native;
using XSOverlay;

// ReSharper disable SwitchStatementHandlesSomeKnownEnumValuesWithDefault

namespace KeyboardOSC;

// ReSharper disable InconsistentNaming
public static class Patches
{
private static readonly ManualLogSource Logger = Plugin.PluginLogger;
public static Harmony Harmony;
private static Harmony Harmony;

public static void PatchAll()
{
Expand All @@ -39,16 +37,17 @@ public static void PatchAll()
Harmony.Patch(keyPress, prefix: blockInputPatch);
Harmony.Patch(keyDown, prefix: blockInputPatch);
Harmony.Patch(keyUp, prefix: blockInputPatch);

// Disable analytics by default (Xiexe loves seeing plugin errors im sure XD)

// Disable analytics by default (Xiexe loves seeing my plugin errors im sure XD)
// can be turned back on after launching if you want to send him stuff for some reason
var initAnalytics = AccessTools.Method(typeof(AnalyticsManager), "Initialize");
var analyticsPatch = new HarmonyMethod(typeof(Patches).GetMethod(nameof(AnalyticsPatch)));
Harmony.Patch(initAnalytics, postfix: analyticsPatch);
}

public static bool KeyboardPatch(KeyboardKey.VirtualKeyEventData keyEventData)
{
if (Plugin.IsChatModeActive) ChatModeManager.HandleKey(keyEventData);
if (Plugin.IsChatModeActive) ChatMode.HandleKey(keyEventData);
return true;
}

Expand All @@ -60,14 +59,15 @@ public static void AnalyticsPatch()
public static void ScalePatch(float dist, Unity_Overlay activeOverlay, float StartingWidth)
{
if (!Plugin.IsChatModeActive || activeOverlay.overlayKey != "xso.overlay.keyboard") return;
var barOverlay = Plugin.Instance.oscBarWindowObj.GetComponent<Unity_Overlay>();
barOverlay.widthInMeters = activeOverlay.widthInMeters - 0.01f;
var chatBar = Plugin.Instance.oscBarWindowObj.GetComponent<Unity_Overlay>();
chatBar.opacity = activeOverlay.opacity;
Plugin.Instance.RepositionBar(chatBar, activeOverlay);
}

public static bool BlockInput(VirtualKeyCode keyCode)
{
if (!Plugin.IsChatModeActive) return true;

// small caveat with the way i'm doing this:
// modifier keys still get passed to windows so that i don't have to reimplement xso's logic for them
var passthroughKeys = new List<VirtualKeyCode>
Expand All @@ -76,7 +76,6 @@ public static bool BlockInput(VirtualKeyCode keyCode)
VirtualKeyCode.LSHIFT, VirtualKeyCode.RSHIFT,
VirtualKeyCode.LCONTROL, VirtualKeyCode.RCONTROL,
VirtualKeyCode.LALT, VirtualKeyCode.RALT,
// printscreen key cause screenshots sharex ftw
VirtualKeyCode.CAPITAL, VirtualKeyCode.PRNTSCRN, // aka VirtualKeyCode.SNAPSHOT

// windows keys and media keys so the wrist one still functions+
Expand Down
118 changes: 70 additions & 48 deletions KeyboardOSC/Plugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@
using KeyboardOSC.XScripts;
using TMPro;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.UI;
using XSOverlay;

namespace KeyboardOSC
{
[BepInPlugin("nwnt.keyboardosc", "KeyboardOSC", "1.0.1.1")]
[BepInPlugin("nwnt.keyboardosc", "KeyboardOSC", "1.1.0.0")]
public class Plugin : BaseUnityPlugin
{
public static Plugin Instance;
Expand All @@ -23,7 +24,9 @@ public class Plugin : BaseUnityPlugin
public static bool IsChatModeActive;
public Overlay_Manager overlayManager;
public KeyboardInputHandler inputHandler;
public GameObject chatButtonObj;

public GameObject toggleBarObj;

public GameObject oscBarWindowObj;
public GameObject oscBarCanvas;

Expand All @@ -45,9 +48,9 @@ private void Awake()

private void Start()
{
Logger.LogWarning("It works! Starting Pre-setup");
Instance = this;
Console.Title = "XSO BepInEx Console";
Logger.LogInfo("hi!");
Console.Title = "KeyboardOSC - XSOverlay";

ReleaseStickyKeys = AccessTools.Method(typeof(KeyboardInputHandler), "ReleaseStickyKeys");
Patches.PatchAll();
Expand All @@ -62,38 +65,41 @@ private void Start()
public void InitializeKeyboard()
{
// Plugin startup logic
Logger.LogInfo("Initializing Keyboard OSC Plugin.");
Logger.LogInfo("Keyboard opened for the first time, initializing KeyboardOSC Plugin.");
overlayManager = Overlay_Manager.Instance;

inputHandler = overlayManager.Keyboard.GetComponent<KeyboardInputHandler>();
SetupAdditionalGameObjects();

SetupToggleButton();
SetupBar();

ServerBridge.Instance.CommandMap["Keyboard"] = delegate { Overlay_Manager.Instance.EnableKeyboard(); };
}

private void SetupAdditionalGameObjects()
private void SetupToggleButton()
{
var lockButtonObj = overlayManager.Keyboard.GetComponentInChildren<LockKeyboardButton>(true).gameObject;
toggleBarObj = Instantiate(lockButtonObj, lockButtonObj.transform.parent);
toggleBarObj.DestroyComponent<LockKeyboardButton>();
toggleBarObj.AddComponent<ToggleChatButton>();
toggleBarObj.transform.Find("Image").GetComponent<Image>().sprite = "chat".GetSprite();
toggleBarObj.Rename("KeyboardOSC Toggle");
}

private void SetupBar()
{
// Copy existing lock keyboard to create new button
var keyboardOverlay = overlayManager.Keyboard;
var keyboard = overlayManager.Keyboard;
var keyboardWindow = overlayManager.Keyboard_Overlay;
var keyboardWindowObj = overlayManager.Keyboard_Overlay.gameObject;

var lockKeyboard = keyboardOverlay.GetComponentInChildren<LockKeyboardButton>(true).gameObject;
chatButtonObj = Instantiate(lockKeyboard, lockKeyboard.transform.parent);
chatButtonObj.DestroyComponent<LockKeyboardButton>();
chatButtonObj.AddComponent<ToggleChatButton>();
chatButtonObj.transform.Find("Image").GetComponent<Image>().sprite = "chat".GetSprite();
chatButtonObj.Rename("OSC Keyboard Mode");

keyboardWindowObj.SetActive(false);

// Create typing bar
var oscBarRoot = new GameObject("TypingBarOverlay");
var oscBarRoot = new GameObject("KeyboardOSC Root");
oscBarRoot.SetActive(false);
keyboardWindowObj.SetActive(false);
oscBarRoot.AddComponent<OverlayTopLevelObject>();


oscBarWindowObj = Instantiate(keyboardWindow.gameObject, oscBarRoot.transform);
oscBarWindowObj.Rename("TypingBar Overlay");
oscBarWindowObj.Rename("KeyboardOSC Window");
oscBarWindowObj.DestroyComponent<KeyboardGlobalManager>();
oscBarWindowObj.DestroyComponent<ReparentToTarget>();
oscBarWindowObj.AddComponent<ReparentBar>();
Expand All @@ -102,27 +108,26 @@ private void SetupAdditionalGameObjects()
oscBarWindowObj.GetComponent<OverlayIdentifier>().OverlayTopLevelObject = oscBarRoot;
oscBarWindow.overlayName = "chatbar";
oscBarWindow.overlayKey = "chatbar";

oscBarWindow.isMoveable = false;


oscBarCanvas = Instantiate(keyboardOverlay.transform.Find("Keyboard Canvas | Manager"),
oscBarCanvas = Instantiate(keyboard.transform.Find("Keyboard Canvas | Manager"),
oscBarRoot.transform, true).gameObject;
var kbBackground = oscBarCanvas.transform.Find("Keyboard Background").gameObject;
oscBarCanvas.Rename("OSCBar Canvas");
oscBarCanvas.Rename("KeyboardOSC Bar Canvas");
oscBarCanvas.GetComponent<Canvas>().referencePixelsPerUnit = 420;
Destroy(oscBarCanvas.transform.Find("KeyboardToolbar").gameObject);
Destroy(oscBarCanvas.transform.Find("Keyboard Background/KeyboardLayout").gameObject);
var kbBackground = oscBarCanvas.transform.Find("Keyboard Background").gameObject;

foreach (Transform child in oscBarCanvas.transform.Find("Keyboard Background/KeyboardSettings/Options"))
foreach (Transform child in kbBackground.transform.Find("KeyboardSettings/Options"))
{
if (child.transform.GetSiblingIndex() > 0)
{
Destroy(child.gameObject);
}
}

var oscBarCameraObj = Instantiate(keyboardOverlay.GetComponentInChildren<Camera>().gameObject,
var oscBarCameraObj = Instantiate(keyboard.GetComponentInChildren<Camera>().gameObject,
oscBarRoot.transform);
var oscBarCamera = oscBarCameraObj.GetComponent<Camera>();
var camTrans = oscBarCamera.transform;
Expand All @@ -134,7 +139,7 @@ private void SetupAdditionalGameObjects()
rescaleToCanvas.canvas = oscBarCanvas.GetComponent<RectTransform>();
rescaleToCanvas.camera = oscBarCamera;

// 100 1000

oscBarWindow.renderTexHeightOverride = 60;
oscBarWindow.renderTexWidthOverride = 730;
oscBarWindow.widthInMeters = 0.55f;
Expand All @@ -143,59 +148,76 @@ private void SetupAdditionalGameObjects()

oscBarWindow.canvasGraphicsCaster = oscBarCanvas.GetComponent<GraphicRaycaster>();

// KEEP or the bar's camera will be borked
oscBarRoot.transform.position = new Vector3(0.3f, 1, 0);

var keyboardPos = Overlay_Manager.Instance.Keyboard_Overlay.transform.position;
var keyboardPos = Overlay_Manager.Instance.Keyboard_Overlay.transform;
var obwTransform = oscBarWindow.transform;
obwTransform.position = new Vector3(keyboardPos.x, keyboardPos.y + 0.01f, keyboardPos.z);
obwTransform.position = keyboardPos.TransformDirection(0, 0.01f, 0);
obwTransform.rotation = new Quaternion(0, 0, 0, 0);

XSOEventSystem.OnGrabbedOrDroppedOverlay += (overlay, _, grabbed) =>
XSOEventSystem.OnGrabbedOrDroppedOverlay += (targetOverlay, _, grabbed) =>
{
if (overlay.overlayKey != "xso.overlay.keyboard" || grabbed) return;
var newTrans = overlay.transform;
var newPos = newTrans.position;
const float offset = 0.155f;
obwTransform.position = newPos + newTrans.up * offset;
obwTransform.rotation = newTrans.rotation;
if (targetOverlay.overlayKey != "xso.overlay.keyboard" || grabbed) return;
RepositionBar(oscBarWindow, targetOverlay);
};

kbBackground.transform.localPosition = Vector3.zero;

kbBackground.GetComponent<RectTransform>().sizeDelta = new Vector2(4130, 475);

camTrans.position = canvasTrans.position;
camTrans.rotation = canvasTrans.rotation;

var oscBarTextObj = Instantiate(keyboardOverlay.transform
//
var oscBarTextObj = Instantiate(keyboard.transform
.Find("Keyboard Canvas | Manager/Keyboard Background/KeyboardSettings/Options/Audio Toggle/Text (TMP)")
.gameObject, kbBackground.transform);
Destroy(oscBarCanvas.transform.Find("Keyboard Background/KeyboardSettings").gameObject);
oscBarTextObj.Rename("TypingBar Text");
oscBarTextObj.Rename("KeyboardOSC Bar Text");

var oscbarText = oscBarTextObj.GetComponent<TextMeshProUGUI>();
XSTools.SetTMPUIText(oscbarText, "Type something silly! \"I bet you can't even read.\"");
XSTools.SetTMPUIText(oscbarText, "type something silly!");

oscbarText.fontSize = 250f;
oscbarText.fontSizeMax = 250f;
oscbarText.horizontalAlignment = HorizontalAlignmentOptions.Center;
oscbarText.verticalAlignment = VerticalAlignmentOptions.Middle;

ChatModeManager.Setup(oscbarText);



ChatMode.Setup(oscbarText);
oscBarRoot.SetActive(true);
keyboardWindowObj.SetActive(true);
WindowMovementManager.MoveToEdgeOfWindowAndInheritRotation(oscBarWindow, keyboardWindow,
-0.1f, 0f, 1);
}

public void ToggleChatMode()
public void RepositionBar(Unity_Overlay barOverlay, Unity_Overlay keebOverlay)
{
var chatButton = chatButtonObj.GetComponent<Button>();
var buttonColors = chatButton.colors;
WindowMovementManager.ScaleOverlayToScale(keebOverlay.widthInMeters - 0.1f, 0.1f, barOverlay);
WindowMovementManager.MoveToEdgeOfWindowAndInheritRotation(barOverlay, keebOverlay,
Vector3.Distance(keebOverlay.transform.position, barOverlay.transform.position) * 0.05f, 0f, 1);
}

public void ToggleChatMode()
{
ReleaseStickyKeys.Invoke(inputHandler, null);

IsChatModeActive = !IsChatModeActive;
oscBarWindowObj.SetActive(IsChatModeActive);

var barOverlay = oscBarWindowObj.GetComponent<Unity_Overlay>();
if (IsChatModeActive)
{
RepositionBar(barOverlay, overlayManager.Keyboard_Overlay);
}

SetToggleColor();
}

private void SetToggleColor()
{
var chatButton = toggleBarObj.GetComponent<Button>();
var buttonColors = chatButton.colors;

buttonColors.normalColor = (IsChatModeActive
? UIThemeHandler.Instance.T_HiTone
: UIThemeHandler.Instance.T_DarkTone);
Expand Down
Loading

0 comments on commit adcb329

Please sign in to comment.