Implement Clipboard and Notifications, misc cleanups

This commit is contained in:
Sinai
2022-01-18 20:19:20 +11:00
parent c79223f537
commit ea7b91f7fd
30 changed files with 518 additions and 333 deletions

View File

@ -1,22 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UnityExplorer.UI
{
public static class Clipboard
{
public static object Current { get; private set; }
public static void Init()
{
}
public static void Copy(object obj)
{
Current = obj;
}
}
}

55
src/UI/Notification.cs Normal file
View File

@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UniverseLib.Input;
using UniverseLib.UI;
namespace UnityExplorer.UI
{
public static class Notification
{
private static Text popupLabel;
private static string _currentNotification;
private static float _timeOfLastNotification;
public static void Init()
{
ConstructUI();
}
public static void ShowMessage(string message)
{
popupLabel.text = message;
_currentNotification = message;
_timeOfLastNotification = Time.realtimeSinceStartup;
popupLabel.transform.localPosition = UIManager.UIRootRect.InverseTransformPoint(InputManager.MousePosition) + (Vector3.up * 25);
}
public static void Update()
{
if (_currentNotification != null)
{
if (Time.realtimeSinceStartup - _timeOfLastNotification > 2f)
{
_currentNotification = null;
popupLabel.text = "";
}
}
}
private static void ConstructUI()
{
popupLabel = UIFactory.CreateLabel(UIManager.UIRoot, "ClipboardNotification", "", TextAnchor.MiddleCenter);
popupLabel.rectTransform.sizeDelta = new(500, 100);
popupLabel.gameObject.AddComponent<Outline>();
var popupGroup = popupLabel.gameObject.AddComponent<CanvasGroup>();
popupGroup.blocksRaycasts = false;
}
}
}

View File

@ -0,0 +1,120 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.CacheObject;
using UnityExplorer.CacheObject.Views;
using UnityExplorer.Config;
using UniverseLib;
using UniverseLib.Input;
using UniverseLib.UI;
using UniverseLib.UI.Widgets;
namespace UnityExplorer.UI.Panels
{
public class ClipboardPanel : UIPanel
{
public static object Current { get; private set; }
public override UIManager.Panels PanelType => UIManager.Panels.Clipboard;
public override string Name => "Clipboard";
public override int MinWidth => 500;
public override int MinHeight => 95;
public override bool CanDragAndResize => true;
public override bool NavButtonWanted => true;
public override bool ShouldSaveActiveState => true;
public override bool ShowByDefault => true;
public override string GetSaveDataFromConfigManager() => ConfigManager.ClipboardData.Value;
public override void DoSaveToConfigElement() => ConfigManager.ClipboardData.Value = this.ToSaveData();
private static Text CurrentPasteLabel;
public static void Copy(object obj)
{
Current = obj;
Notification.ShowMessage("Copied!");
UpdateCurrentPasteInfo();
}
public static bool TryPaste(Type targetType, out object paste)
{
paste = Current;
var pasteType = Current?.GetActualType();
if (Current != null && !targetType.IsAssignableFrom(pasteType))
{
Notification.ShowMessage($"Cannot assign '{pasteType.Name}' to '{targetType.Name}'!");
return false;
}
Notification.ShowMessage("Pasted!");
return true;
}
public static void ClearClipboard()
{
Current = null;
UpdateCurrentPasteInfo();
}
private static void UpdateCurrentPasteInfo()
{
CurrentPasteLabel.text = ToStringUtility.ToStringWithType(Current, typeof(object), false);
}
private static void InspectClipboard()
{
if (Current.IsNullOrDestroyed())
{
Notification.ShowMessage("Cannot inspect a null or destroyed object!");
return;
}
InspectorManager.Inspect(Current);
}
protected internal override void DoSetDefaultPosAndAnchors()
{
this.Rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, MinWidth);
this.Rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, MinHeight);
this.Rect.anchorMin = new Vector2(0.1f, 0.05f);
this.Rect.anchorMax = new Vector2(0.4f, 0.15f);
}
public override void ConstructPanelContent()
{
this.UIRoot.GetComponent<Image>().color = new(0.1f, 0.1f, 0.1f);
// Actual panel content
var firstRow = UIFactory.CreateHorizontalGroup(UIRoot, "FirstRow", false, false, true, true, 5, new(2,2,2,2), new(1,1,1,0));
UIFactory.SetLayoutElement(firstRow, minHeight: 25, flexibleWidth: 999);
// Title for "Current Paste:"
var currentPasteTitle = UIFactory.CreateLabel(firstRow, "CurrentPasteTitle", "Current paste:", TextAnchor.MiddleLeft, color: Color.grey);
UIFactory.SetLayoutElement(currentPasteTitle.gameObject, minHeight: 25, minWidth: 100, flexibleWidth: 999);
// Clear clipboard button
var clearButton = UIFactory.CreateButton(firstRow, "ClearPasteButton", "Clear Clipboard");
UIFactory.SetLayoutElement(clearButton.Component.gameObject, minWidth: 120, minHeight: 25, flexibleWidth: 0);
clearButton.OnClick += () => Copy(null);
// Current Paste info row
var currentPasteHolder = UIFactory.CreateHorizontalGroup(UIRoot, "SecondRow", false, false, true, true, 0,
new(2, 2, 2, 2), childAlignment: TextAnchor.UpperCenter);
// Actual current paste info label
CurrentPasteLabel = UIFactory.CreateLabel(currentPasteHolder, "CurrentPasteInfo", "not set", TextAnchor.UpperLeft);
UIFactory.SetLayoutElement(CurrentPasteLabel.gameObject, minHeight: 25, minWidth: 100, flexibleWidth: 999, flexibleHeight: 999);
UpdateCurrentPasteInfo();
// Inspect button
var inspectButton = UIFactory.CreateButton(currentPasteHolder, "InspectButton", "Inspect");
UIFactory.SetLayoutElement(inspectButton.Component.gameObject, minHeight: 25, flexibleHeight: 0, minWidth: 80, flexibleWidth: 0);
inspectButton.OnClick += InspectClipboard;
}
}
}

View File

@ -46,10 +46,7 @@ namespace UnityExplorer.UI.Panels
public override string GetSaveDataFromConfigManager() => ConfigManager.InspectorData.Value;
public override void DoSaveToConfigElement()
{
ConfigManager.InspectorData.Value = this.ToSaveData();
}
public override void DoSaveToConfigElement() => ConfigManager.InspectorData.Value = this.ToSaveData();
protected internal override void DoSetDefaultPosAndAnchors()
{

View File

@ -15,15 +15,33 @@ namespace UnityExplorer.UI.Panels
{
public class PanelDragger
{
private enum MouseState
{
Down,
Held,
NotPressed
}
#region Static
public static bool Resizing { get; private set; }
public static bool ResizePrompting => resizeCursorObj && resizeCursorObj.activeSelf;
public static bool ResizePrompting => s_resizeCursorObj && s_resizeCursorObj.activeSelf;
public static GameObject resizeCursorObj;
internal static bool wasAnyDragging;
internal static List<PanelDragger> Instances = new();
private static bool handledInstanceThisFrame;
static PanelDragger()
{
UIPanel.OnPanelsReordered += OnPanelsReordered;
}
internal static void ForceEnd()
{
s_resizeCursorObj.SetActive(false);
resizeCursorObj.SetActive(false);
wasAnyDragging = false;
Resizing = false;
@ -34,13 +52,6 @@ namespace UnityExplorer.UI.Panels
}
}
internal static List<PanelDragger> Instances = new List<PanelDragger>();
static PanelDragger()
{
UIPanel.OnPanelsReordered += OnPanelsReordered;
}
public static void OnPanelsReordered()
{
Instances.Sort((a, b) => b.Panel.GetSiblingIndex().CompareTo(a.Panel.GetSiblingIndex()));
@ -54,18 +65,9 @@ namespace UnityExplorer.UI.Panels
}
}
private enum MouseState
{
Down,
Held,
NotPressed
}
private static bool handledInstanceThisFrame;
public static void UpdateInstances()
{
if (!s_resizeCursorObj)
if (!resizeCursorObj)
CreateCursorUI();
MouseState state;
@ -99,10 +101,6 @@ namespace UnityExplorer.UI.Panels
#endregion
public static GameObject s_resizeCursorObj;
internal static bool wasAnyDragging;
// Instance
public UIPanel UIPanel { get; private set; }
@ -112,27 +110,23 @@ namespace UnityExplorer.UI.Panels
public event Action<RectTransform> OnFinishResize;
public event Action<RectTransform> OnFinishDrag;
private readonly RectTransform canvasTransform;
// Dragging
public RectTransform DragableArea { get; set; }
public bool WasDragging { get; set; }
private Vector2 m_lastDragPosition;
private Vector2 lastDragPosition;
// Resizing
private const int RESIZE_THICKNESS = 10;
//internal readonly Vector2 minResize = new Vector2(200, 50);
private bool WasResizing { get; set; }
private ResizeTypes m_currentResizeType = ResizeTypes.NONE;
private Vector2 m_lastResizePos;
private ResizeTypes currentResizeType = ResizeTypes.NONE;
private Vector2 lastResizePos;
private bool WasHoveringResize => s_resizeCursorObj.activeInHierarchy;
private bool WasHoveringResize => resizeCursorObj.activeInHierarchy;
private ResizeTypes m_lastResizeHoverType;
private ResizeTypes lastResizeHoverType;
private Rect m_totalResizeRect;
private Rect totalResizeRect;
public PanelDragger(RectTransform dragArea, RectTransform panelToDrag, UIPanel panel)
{
@ -141,16 +135,13 @@ namespace UnityExplorer.UI.Panels
DragableArea = dragArea;
Panel = panelToDrag;
if (!canvasTransform)
canvasTransform = Panel.GetComponentInParent<Canvas>().GetComponent<RectTransform>();
UpdateResizeCache();
}
public void Destroy()
{
if (s_resizeCursorObj)
GameObject.Destroy(s_resizeCursorObj);
if (resizeCursorObj)
GameObject.Destroy(resizeCursorObj);
if (Instances.Contains(this))
Instances.Remove(this);
@ -166,7 +157,7 @@ namespace UnityExplorer.UI.Panels
Vector3 dragPos = DragableArea.InverseTransformPoint(rawMousePos);
bool inDragPos = DragableArea.rect.Contains(dragPos);
if (WasHoveringResize && s_resizeCursorObj)
if (WasHoveringResize && resizeCursorObj)
UpdateHoverImagePos();
switch (state)
@ -243,15 +234,15 @@ namespace UnityExplorer.UI.Panels
{
wasAnyDragging = true;
WasDragging = true;
m_lastDragPosition = InputManager.MousePosition;
lastDragPosition = InputManager.MousePosition;
}
public void OnDrag()
{
var mousePos = InputManager.MousePosition;
Vector2 diff = (Vector2)mousePos - m_lastDragPosition;
m_lastDragPosition = mousePos;
Vector2 diff = (Vector2)mousePos - lastDragPosition;
lastDragPosition = mousePos;
Panel.localPosition = Panel.localPosition + (Vector3)diff;
@ -296,7 +287,7 @@ namespace UnityExplorer.UI.Panels
private void UpdateResizeCache()
{
m_totalResizeRect = new Rect(Panel.rect.x - RESIZE_THICKNESS + 1,
totalResizeRect = new Rect(Panel.rect.x - RESIZE_THICKNESS + 1,
Panel.rect.y - RESIZE_THICKNESS + 1,
Panel.rect.width + DBL_THICKESS - 2,
Panel.rect.height + DBL_THICKESS - 2);
@ -305,34 +296,34 @@ namespace UnityExplorer.UI.Panels
if (AllowDragAndResize)
{
m_resizeMask[ResizeTypes.Bottom] = new Rect(
m_totalResizeRect.x,
m_totalResizeRect.y,
m_totalResizeRect.width,
totalResizeRect.x,
totalResizeRect.y,
totalResizeRect.width,
RESIZE_THICKNESS);
m_resizeMask[ResizeTypes.Left] = new Rect(
m_totalResizeRect.x,
m_totalResizeRect.y,
totalResizeRect.x,
totalResizeRect.y,
RESIZE_THICKNESS,
m_totalResizeRect.height);
totalResizeRect.height);
m_resizeMask[ResizeTypes.Top] = new Rect(
m_totalResizeRect.x,
totalResizeRect.x,
Panel.rect.y + Panel.rect.height - 2,
m_totalResizeRect.width,
totalResizeRect.width,
RESIZE_THICKNESS);
m_resizeMask[ResizeTypes.Right] = new Rect(
m_totalResizeRect.x + Panel.rect.width + RESIZE_THICKNESS - 2,
m_totalResizeRect.y,
totalResizeRect.x + Panel.rect.width + RESIZE_THICKNESS - 2,
totalResizeRect.y,
RESIZE_THICKNESS,
m_totalResizeRect.height);
totalResizeRect.height);
}
}
private bool MouseInResizeArea(Vector2 mousePos)
{
return m_totalResizeRect.Contains(mousePos);
return totalResizeRect.Contains(mousePos);
}
private ResizeTypes GetResizeType(Vector2 mousePos)
@ -361,16 +352,16 @@ namespace UnityExplorer.UI.Panels
public void OnHoverResize(ResizeTypes resizeType)
{
if (WasHoveringResize && m_lastResizeHoverType == resizeType)
if (WasHoveringResize && lastResizeHoverType == resizeType)
return;
// we are entering resize, or the resize type has changed.
//WasHoveringResize = true;
m_lastResizeHoverType = resizeType;
lastResizeHoverType = resizeType;
s_resizeCursorObj.SetActive(true);
s_resizeCursorObj.transform.SetAsLastSibling();
resizeCursorObj.SetActive(true);
resizeCursorObj.transform.SetAsLastSibling();
// set the rotation for the resize icon
float iconRotation = 0f;
@ -387,9 +378,9 @@ namespace UnityExplorer.UI.Panels
iconRotation = 135f; break;
}
Quaternion rot = s_resizeCursorObj.transform.rotation;
Quaternion rot = resizeCursorObj.transform.rotation;
rot.eulerAngles = new Vector3(0, 0, iconRotation);
s_resizeCursorObj.transform.rotation = rot;
resizeCursorObj.transform.rotation = rot;
UpdateHoverImagePos();
}
@ -397,19 +388,19 @@ namespace UnityExplorer.UI.Panels
// update the resize icon position to be above the mouse
private void UpdateHoverImagePos()
{
s_resizeCursorObj.transform.localPosition = canvasTransform.InverseTransformPoint(InputManager.MousePosition);
resizeCursorObj.transform.localPosition = UIManager.UIRootRect.InverseTransformPoint(InputManager.MousePosition);
}
public void OnHoverResizeEnd()
{
//WasHoveringResize = false;
s_resizeCursorObj.SetActive(false);
resizeCursorObj.SetActive(false);
}
public void OnBeginResize(ResizeTypes resizeType)
{
m_currentResizeType = resizeType;
m_lastResizePos = InputManager.MousePosition;
currentResizeType = resizeType;
lastResizePos = InputManager.MousePosition;
WasResizing = true;
Resizing = true;
}
@ -417,15 +408,15 @@ namespace UnityExplorer.UI.Panels
public void OnResize()
{
Vector3 mousePos = InputManager.MousePosition;
Vector2 diff = m_lastResizePos - (Vector2)mousePos;
Vector2 diff = lastResizePos - (Vector2)mousePos;
if ((Vector2)mousePos == m_lastResizePos)
if ((Vector2)mousePos == lastResizePos)
return;
if (mousePos.x < 0 || mousePos.y < 0 || mousePos.x > Screen.width || mousePos.y > Screen.height)
return;
m_lastResizePos = mousePos;
lastResizePos = mousePos;
float diffX = (float)((decimal)diff.x / Screen.width);
float diffY = (float)((decimal)diff.y / Screen.height);
@ -433,14 +424,14 @@ namespace UnityExplorer.UI.Panels
Vector2 anchorMin = Panel.anchorMin;
Vector2 anchorMax = Panel.anchorMax;
if (m_currentResizeType.HasFlag(ResizeTypes.Left))
if (currentResizeType.HasFlag(ResizeTypes.Left))
anchorMin.x -= diffX;
else if (m_currentResizeType.HasFlag(ResizeTypes.Right))
else if (currentResizeType.HasFlag(ResizeTypes.Right))
anchorMax.x -= diffX;
if (m_currentResizeType.HasFlag(ResizeTypes.Top))
if (currentResizeType.HasFlag(ResizeTypes.Top))
anchorMax.y -= diffY;
else if (m_currentResizeType.HasFlag(ResizeTypes.Bottom))
else if (currentResizeType.HasFlag(ResizeTypes.Bottom))
anchorMin.y -= diffY;
var prevMin = Panel.anchorMin;
@ -475,13 +466,13 @@ namespace UnityExplorer.UI.Panels
try
{
var text = UIFactory.CreateLabel(UIManager.UIRoot, "ResizeCursor", "↔", TextAnchor.MiddleCenter, Color.white, true, 35);
s_resizeCursorObj = text.gameObject;
resizeCursorObj = text.gameObject;
RectTransform rect = s_resizeCursorObj.GetComponent<RectTransform>();
RectTransform rect = resizeCursorObj.GetComponent<RectTransform>();
rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 64);
rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, 64);
s_resizeCursorObj.SetActive(false);
resizeCursorObj.SetActive(false);
}
catch (Exception e)
{

View File

@ -23,8 +23,8 @@ namespace UnityExplorer.UI.Panels
public static event Action OnPanelsReordered;
public static event Action OnClickedOutsidePanels;
internal static readonly List<UIPanel> instances = new List<UIPanel>();
internal static readonly Dictionary<int, UIPanel> transformToPanelDict = new Dictionary<int, UIPanel>();
internal static readonly List<UIPanel> instances = new();
internal static readonly Dictionary<int, UIPanel> transformToPanelDict = new();
public static void UpdateFocus()
{

View File

@ -27,17 +27,6 @@ namespace UnityExplorer.UI.Panels
private ButtonListHandler<GameObject, ButtonCell> dataHandler;
private ScrollPool<ButtonCell> buttonScrollPool;
public override void ConstructPanelContent()
{
dataHandler = new ButtonListHandler<GameObject, ButtonCell>(buttonScrollPool, GetEntries, SetCell, ShouldDisplayCell, OnCellClicked);
buttonScrollPool = UIFactory.CreateScrollPool<ButtonCell>(this.content, "ResultsList", out GameObject scrollObj,
out GameObject scrollContent);
buttonScrollPool.Initialize(dataHandler);
UIFactory.SetLayoutElement(scrollObj, flexibleHeight: 9999);
}
public void ShowResults()
{
dataHandler.RefreshData();
@ -65,6 +54,17 @@ namespace UnityExplorer.UI.Panels
cell.Button.ButtonText.text = $"<color=cyan>{obj.name}</color> ({obj.transform.GetTransformPath(true)})";
}
public override void ConstructPanelContent()
{
dataHandler = new ButtonListHandler<GameObject, ButtonCell>(buttonScrollPool, GetEntries, SetCell, ShouldDisplayCell, OnCellClicked);
buttonScrollPool = UIFactory.CreateScrollPool<ButtonCell>(this.content, "ResultsList", out GameObject scrollObj,
out GameObject scrollContent);
buttonScrollPool.Initialize(dataHandler);
UIFactory.SetLayoutElement(scrollObj, flexibleHeight: 9999);
}
protected internal override void DoSetDefaultPosAndAnchors()
{
this.Rect.anchorMin = new Vector2(0.5f, 0.5f);

View File

@ -35,6 +35,7 @@ namespace UnityExplorer.UI
MouseInspector,
UIInspectorResults,
HookManager,
Clipboard
}
public enum VerticalAnchor
@ -49,12 +50,15 @@ namespace UnityExplorer.UI
private static UIBase uiBase;
public static GameObject UIRoot => uiBase?.RootObject;
public static RectTransform UIRootRect => _uiRootRect ??= UIRoot.GetComponent<RectTransform>();
private static RectTransform _uiRootRect;
internal static GameObject PanelHolder { get; private set; }
private static readonly Dictionary<Panels, UIPanel> UIPanels = new Dictionary<Panels, UIPanel>();
private static readonly Dictionary<Panels, UIPanel> UIPanels = new();
public static RectTransform NavBarRect;
public static GameObject NavbarTabButtonHolder;
private static readonly Vector2 NAVBAR_DIMENSIONS = new(1020f, 35f);
private static ButtonRef closeBtn;
private static ButtonRef pauseBtn;
@ -62,6 +66,9 @@ namespace UnityExplorer.UI
private static bool pauseButtonPausing;
private static float lastTimeScale;
private static int lastScreenWidth;
private static int lastScreenHeight;
public static bool ShowMenu
{
get => uiBase != null && uiBase.Enabled;
@ -83,6 +90,7 @@ namespace UnityExplorer.UI
lastScreenWidth = Screen.width;
lastScreenHeight = Screen.height;
// Create UI.
CreatePanelHolder();
CreateTopNavBar();
@ -93,6 +101,7 @@ namespace UnityExplorer.UI
UIPanels.Add(Panels.Inspector, new InspectorPanel());
UIPanels.Add(Panels.CSConsole, new CSConsolePanel());
UIPanels.Add(Panels.HookManager, new HookManagerPanel());
UIPanels.Add(Panels.Clipboard, new ClipboardPanel());
UIPanels.Add(Panels.ConsoleLog, new LogPanel());
UIPanels.Add(Panels.Options, new OptionsPanel());
UIPanels.Add(Panels.UIInspectorResults, new UiInspectorResultsPanel());
@ -102,8 +111,8 @@ namespace UnityExplorer.UI
panel.ConstructUI();
// Call some initialize methods
Notification.Init();
ConsoleController.Init();
Clipboard.Init();
// Add this listener to prevent ScrollPool doing anything while we are resizing panels
ScrollPool<ICell>.writingLockedListeners.Add(() => !PanelDragger.Resizing);
@ -120,9 +129,6 @@ namespace UnityExplorer.UI
// Main UI Update loop
private static int lastScreenWidth;
private static int lastScreenHeight;
public static void Update()
{
if (!UIRoot)
@ -135,6 +141,9 @@ namespace UnityExplorer.UI
return;
}
// Update Notification modal
Notification.Update();
// Check forceUnlockMouse toggle
if (InputManager.GetKeyDown(ConfigManager.Force_Unlock_Toggle.Value))
UniverseLib.Config.ConfigManager.Force_Unlock_Mouse = !UniverseLib.Config.ConfigManager.Force_Unlock_Mouse;
@ -208,14 +217,14 @@ namespace UnityExplorer.UI
NavBarRect.anchorMin = new Vector2(0.5f, 1f);
NavBarRect.anchorMax = new Vector2(0.5f, 1f);
NavBarRect.anchoredPosition = new Vector2(NavBarRect.anchoredPosition.x, 0);
NavBarRect.sizeDelta = new Vector2(1080f, 35f);
NavBarRect.sizeDelta = NAVBAR_DIMENSIONS;
break;
case VerticalAnchor.Bottom:
NavBarRect.anchorMin = new Vector2(0.5f, 0f);
NavBarRect.anchorMax = new Vector2(0.5f, 0f);
NavBarRect.anchoredPosition = new Vector2(NavBarRect.anchoredPosition.x, 35);
NavBarRect.sizeDelta = new Vector2(1080f, 35f);
NavBarRect.sizeDelta = NAVBAR_DIMENSIONS;
break;
}
}

View File

@ -42,8 +42,6 @@ namespace UnityExplorer.UI.Widgets
SetArgRows();
this.UIRoot.SetActive(true);
InspectorManager.OnInspectedTabsChanged += InspectorManager_OnInspectedTabsChanged;
}
public void OnReturnToPool()
@ -63,14 +61,6 @@ namespace UnityExplorer.UI.Widgets
genericHandlers = null;
this.Owner = null;
InspectorManager.OnInspectedTabsChanged -= InspectorManager_OnInspectedTabsChanged;
}
private void InspectorManager_OnInspectedTabsChanged()
{
foreach (var handler in this.paramHandlers)
handler.PopulateDropdown();
}
public Type[] TryParseGenericArguments()

View File

@ -1,9 +1,12 @@
using System;
using HarmonyLib;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;
using UnityExplorer.CacheObject.IValues;
using UnityExplorer.UI.Panels;
using UnityExplorer.UI.Widgets.AutoComplete;
using UniverseLib;
using UniverseLib.UI;
@ -15,11 +18,15 @@ namespace UnityExplorer.UI.Widgets
private ParameterInfo paramInfo;
private Type paramType;
internal Dropdown dropdown;
private bool usingDropdown;
internal EnumCompleter enumCompleter;
private ButtonRef enumHelperButton;
private bool usingBasicLabel;
private object basicValue;
private GameObject basicLabelHolder;
private Text basicLabel;
private ButtonRef pasteButton;
public void OnBorrowed(EvaluateWidget evaluator, ParameterInfo paramInfo)
{
this.evaluator = evaluator;
@ -34,8 +41,10 @@ namespace UnityExplorer.UI.Widgets
if (ParseUtility.CanParse(paramType) || typeof(Type).IsAssignableFrom(paramType))
{
usingBasicLabel = false;
this.inputField.Component.gameObject.SetActive(true);
this.dropdown.gameObject.SetActive(false);
this.basicLabelHolder.SetActive(false);
this.typeCompleter.Enabled = typeof(Type).IsAssignableFrom(paramType);
this.enumCompleter.Enabled = paramType.IsEnum;
this.enumHelperButton.Component.gameObject.SetActive(paramType.IsEnum);
@ -63,16 +72,15 @@ namespace UnityExplorer.UI.Widgets
else
{
// non-parsable, and not a Type
usingBasicLabel = true;
this.inputField.Component.gameObject.SetActive(false);
this.dropdown.gameObject.SetActive(true);
this.basicLabelHolder.SetActive(true);
this.typeCompleter.Enabled = false;
this.enumCompleter.Enabled = false;
this.enumHelperButton.Component.gameObject.SetActive(false);
usingDropdown = true;
PopulateDropdown();
InspectorManager.OnInspectedTabsChanged += PopulateDropdown;
SetDisplayedValueFromPaste();
}
}
@ -81,109 +89,89 @@ namespace UnityExplorer.UI.Widgets
this.evaluator = null;
this.paramInfo = null;
usingDropdown = false;
this.enumCompleter.Enabled = false;
this.typeCompleter.Enabled = false;
this.inputField.Text = "";
InspectorManager.OnInspectedTabsChanged -= PopulateDropdown;
this.usingBasicLabel = false;
this.basicValue = null;
}
public object Evaluate()
{
if (!usingDropdown)
if (usingBasicLabel)
return basicValue;
var input = this.inputField.Text;
if (typeof(Type).IsAssignableFrom(paramType))
return ReflectionUtility.GetTypeByName(input);
if (paramType == typeof(string))
return input;
if (string.IsNullOrEmpty(input))
{
var input = this.inputField.Text;
if (typeof(Type).IsAssignableFrom(paramType))
return ReflectionUtility.GetTypeByName(input);
if (paramType == typeof(string))
return input;
if (string.IsNullOrEmpty(input))
{
if (paramInfo.IsOptional)
return paramInfo.DefaultValue;
else
return null;
}
if (!ParseUtility.TryParse(input, paramType, out object parsed, out Exception ex))
{
ExplorerCore.LogWarning($"Cannot parse argument '{paramInfo.Name}' ({paramInfo.ParameterType.Name})" +
$"{(ex == null ? "" : $", {ex.GetType().Name}: {ex.Message}")}");
return null;
}
if (paramInfo.IsOptional)
return paramInfo.DefaultValue;
else
return parsed;
return null;
}
if (!ParseUtility.TryParse(input, paramType, out object parsed, out Exception ex))
{
ExplorerCore.LogWarning($"Cannot parse argument '{paramInfo.Name}' ({paramInfo.ParameterType.Name})" +
$"{(ex == null ? "" : $", {ex.GetType().Name}: {ex.Message}")}");
return null;
}
else
return parsed;
}
private void OnPasteClicked()
{
if (ClipboardPanel.TryPaste(this.paramType, out object paste))
{
if (dropdown.value == 0)
return null;
basicValue = paste;
SetDisplayedValueFromPaste();
}
}
private void SetDisplayedValueFromPaste()
{
if (usingBasicLabel)
basicLabel.text = ToStringUtility.ToStringWithType(basicValue, paramType, false);
else
{
if (typeof(Type).IsAssignableFrom(paramType))
inputField.Text = (basicValue as Type).FullDescription();
else
return dropdownUnderlyingValues[dropdown.value];
inputField.Text = ParseUtility.ToStringForInput(basicValue, paramType);
}
}
private object[] dropdownUnderlyingValues;
internal void PopulateDropdown()
{
if (!usingDropdown)
return;
dropdown.options.Clear();
var underlyingValues = new List<object>();
dropdown.options.Add(new Dropdown.OptionData("null"));
underlyingValues.Add(null);
var argType = paramType;
int tabIndex = 0;
foreach (var tab in InspectorManager.Inspectors)
{
tabIndex++;
if (argType.IsAssignableFrom(tab.Target.GetActualType()))
{
dropdown.options.Add(new Dropdown.OptionData($"Tab {tabIndex}: {tab.Tab.TabText.text}"));
underlyingValues.Add(tab.Target);
}
}
dropdownUnderlyingValues = underlyingValues.ToArray();
}
private void EnumHelper_OnClick()
{
enumCompleter.HelperButtonClicked();
}
public override void CreateSpecialContent()
{
enumCompleter = new(paramType, this.inputField)
{
Enabled = false
};
enumHelperButton = UIFactory.CreateButton(UIRoot, "EnumHelper", "▼");
UIFactory.SetLayoutElement(enumHelperButton.Component.gameObject, minWidth: 25, minHeight: 25, flexibleWidth: 0, flexibleHeight: 0);
enumHelperButton.OnClick += EnumHelper_OnClick;
enumHelperButton.OnClick += enumCompleter.HelperButtonClicked;
var dropdownObj = UIFactory.CreateDropdown(UIRoot, out dropdown, "Select argument...", 14, (int val) =>
{
//ArgDropdownChanged(val);
});
UIFactory.SetLayoutElement(dropdownObj, minHeight: 25, flexibleHeight: 50, minWidth: 100, flexibleWidth: 1000);
dropdownObj.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
basicLabelHolder = UIFactory.CreateHorizontalGroup(UIRoot, "BasicLabelHolder", true, true, true, true, bgColor: new(0.1f, 0.1f, 0.1f));
UIFactory.SetLayoutElement(basicLabelHolder, minHeight: 25, flexibleHeight: 50, minWidth: 100, flexibleWidth: 1000);
basicLabel = UIFactory.CreateLabel(basicLabelHolder, "BasicLabel", "null", TextAnchor.MiddleLeft);
basicLabel.gameObject.AddComponent<ContentSizeFitter>().verticalFit = ContentSizeFitter.FitMode.PreferredSize;
enumCompleter = new EnumCompleter(paramType, this.inputField);
enumCompleter.Enabled = false;
pasteButton = UIFactory.CreateButton(UIRoot, "PasteButton", "Paste", new Color(0.13f, 0.13f, 0.13f, 1f));
UIFactory.SetLayoutElement(pasteButton.Component.gameObject, minHeight: 25, minWidth: 28, flexibleWidth: 0);
pasteButton.ButtonText.color = Color.green;
pasteButton.ButtonText.fontSize = 10;
pasteButton.OnClick += OnPasteClicked;
}
//private void ArgDropdownChanged(int value)
//{
// // not needed
//}
}
}