using System; using Xui.Core.Abstract.Events; using Xui.Core.Canvas; using Xui.Core.Math2D; using Xui.Core.UI; using Xui.Core.UI.Input; public sealed class ActionToggle : View { private int? pointer; private bool enabled = true; private bool isOn; public ActionToggle() { HorizontalAlignment = HorizontalAlignment.Center; VerticalAlignment = VerticalAlignment.Middle; MinimumWidth = 240; MinimumHeight = 80; } public event Action? Changed; public bool IsOn => isOn; public override bool Focusable => enabled; public bool Enabled { get => enabled; set { if (enabled == value) return; enabled = value; if (!enabled) { CancelPress(); Blur(); } InvalidateRender(); } } private void Toggle() { isOn = !isOn; InvalidateRender(); Changed?.Invoke(isOn); } public override void OnPointerEvent(ref PointerEventRef e, EventPhase phase) { if (phase != EventPhase.Bubble || !enabled) return; if (e.Type == PointerEventType.Down && pointer is null && e.State.Button == PointerButton.Left) { Focus(); pointer = e.PointerId; CapturePointer(e.PointerId, PointerGestures.Tap); InvalidateRender(); } else if (pointer == e.PointerId && e.Type == PointerEventType.Up) { bool inside = Frame.Contains(e.State.Position); CancelPress(); if (inside) Toggle(); } else if (pointer == e.PointerId && e.Type is PointerEventType.Cancel or PointerEventType.LostCapture) CancelPress(); } public override void OnKeyDown(ref KeyEventRef e) { if (enabled && e.Key is VirtualKey.Return or VirtualKey.Space) { if (!e.IsRepeat) Toggle(); e.Handled = true; } } private void CancelPress() { int? captured = pointer; pointer = null; if (captured is int id) ReleasePointer(id); InvalidateRender(); } protected override void OnDeactivate() => CancelPress(); protected override void OnFocus() => InvalidateRender(); protected override void OnBlur() => InvalidateRender(); protected override void RenderCore(IContext context) { context.SetFill(new Color(!enabled ? 0xB6ADBFFFu : pointer is not null ? 0x59218AFFu : 0x8538CEFFu)); context.BeginPath(); context.RoundRect(Frame, 20); context.Fill(); if (IsFocused) { context.SetStroke(new Color(0xD957A8FF)); context.LineWidth = 3; context.Stroke(); } context.SetFill(Colors.White); context.SetFont(new Font(22, "Inter")); context.TextAlign = TextAlign.Center; context.TextBaseline = TextBaseline.Middle; context.FillText(isOn ? "Playing - tap to pause" : "Paused - tap to play", Frame.Center); } }