CrabUI
Loading...
Searching...
No Matches
CUIDragHandle.cs
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Reflection;
5
6using Barotrauma;
7using Microsoft.Xna.Framework;
8using Microsoft.Xna.Framework.Input;
9using Microsoft.Xna.Framework.Graphics;
10
11namespace CrabUI
12{
13 public class CUIDragHandle : ICUIVitalizable
14 {
15 public void SetHost(CUIComponent host) => Host = host;
16 public CUIComponent Host;
17 public Vector2 GrabOffset;
18 public bool Grabbed;
19 public bool Draggable;
20 public CUIMouseEvent Trigger = CUIMouseEvent.Down;
21 /// <summary>
22 /// If true, will change relative prop instead of Absolute
23 /// </summary>
24 public bool DragRelative { get; set; } = false;
25 public bool OutputRealPos { get; set; } = false;
26
27 public bool ShouldStart(CUIInput input)
28 {
29 return Draggable && (
30 (Trigger == CUIMouseEvent.Down && input.MouseDown) ||
31 (Trigger == CUIMouseEvent.DClick && input.DoubleClick)
32 );
33 }
34 public void BeginDrag(Vector2 cursorPos)
35 {
36 Grabbed = true;
37 GrabOffset = cursorPos - CUIAnchor.PosIn(Host);
38 }
39
40 public void EndDrag()
41 {
42 Grabbed = false;
43 Host.MainComponent?.OnDragEnd(this);
44 }
45
46 //TODO test in 3d child offset
47 public void DragTo(Vector2 to)
48 {
49 Vector2 pos = Host.Parent.ChildrenOffset.ToPlaneCoords(
50 to - GrabOffset - CUIAnchor.PosIn(Host.Parent.Real, Host.ParentAnchor ?? Host.Anchor)
51 );
52
53 if (DragRelative)
54 {
55 Vector2 newRelPos = new Vector2(
56 pos.X / Host.Parent.Real.Width,
57 pos.Y / Host.Parent.Real.Height
58 );
59 Host.CUIProps.Relative.SetValue(Host.Relative with { Position = newRelPos });
60 Host.InvokeOnDrag(newRelPos.X, newRelPos.Y);
61 }
62 else
63 {
64 Host.CUIProps.Absolute.SetValue(Host.Absolute with { Position = pos });
65 if (OutputRealPos) Host.InvokeOnDrag(to.X, to.Y);
66 else Host.InvokeOnDrag(pos.X, pos.Y);
67 }
68 }
69
70 public CUIDragHandle() { }
71 public CUIDragHandle(CUIComponent host) => Host = host;
72 }
73}