Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
#nullable enable
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.EventSystems;

using io.github.hatayama.UnityCliLoop.Runtime;
using io.github.hatayama.UnityCliLoop.ToolContracts;

namespace io.github.hatayama.UnityCliLoop.FirstPartyTools
{
/// <summary>
/// Executes pointer event mechanics shared by one-shot and incremental UI drags.
/// </summary>
internal static class MouseUiDragEventExecutor
{
internal static PointerEventData InitiateDrag(
EventSystem eventSystem,
Vector2 screenPos,
RaycastResult raycastResult,
GameObject dragTarget,
PointerEventData.InputButton inputButton)
{
PointerEventData pointerData = new(eventSystem)
{
position = screenPos,
pressPosition = screenPos,
button = inputButton,
pointerCurrentRaycast = raycastResult,
pointerPressRaycast = raycastResult,
pointerDrag = dragTarget,
rawPointerPress = raycastResult.gameObject
};

// Slider.OnPointerDown initializes m_Offset for handle positioning
GameObject? pressTarget = ExecuteEvents.ExecuteHierarchy(
raycastResult.gameObject, pointerData, ExecuteEvents.pointerDownHandler);
pointerData.pointerPress = pressTarget;

// ScrollRect.OnInitializePotentialDrag clears inertia, Slider sets useDragThreshold=false
ExecuteEvents.Execute(dragTarget, pointerData, ExecuteEvents.initializePotentialDrag);

return pointerData;
}

// Lifecycle must match StandaloneInputModule: raycast → pointerUp → drop → endDrag
internal static void FinalizeDrag(
PointerEventData pointerData,
GameObject target,
GameObject? explicitDropTarget)
{
if (explicitDropTarget != null)
{
pointerData.pointerCurrentRaycast = MouseUiPointerTargetResolver.CreateDirectRaycastResult(explicitDropTarget);
}
else
{
UpdatePointerRaycast(pointerData);
}

if (pointerData.pointerPress != null)
{
ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerUpHandler);
}

// Standard IDropHandler dispatch so Unity drop targets respond without manual workarounds
GameObject? dropTarget = pointerData.pointerCurrentRaycast.gameObject;
if (dropTarget != null)
{
ExecuteEvents.ExecuteHierarchy(dropTarget, pointerData, ExecuteEvents.dropHandler);
}

pointerData.dragging = false;
ExecuteEvents.Execute(target, pointerData, ExecuteEvents.endDragHandler);
}

private static void UpdatePointerRaycast(PointerEventData pointerData)
{
RaycastResult? hit = UiRaycastHelper.RaycastUI(pointerData.position, EventSystem.current);
pointerData.pointerCurrentRaycast = hit ?? new RaycastResult();
}

internal static async Task<bool> InterpolateDragPosition(
PointerEventData pointerData,
GameObject target,
Vector2 endPos,
float dragSpeed,
CancellationToken ct)
{
Debug.Assert(dragSpeed >= 0f, "dragSpeed must be non-negative");

Vector2 startPos = pointerData.position;
float distance = Vector2.Distance(startPos, endPos);
float duration = dragSpeed > 0f ? distance / dragSpeed : 0f;

if (duration <= 0f)
{
bool frameReady = await MouseUiEditorFrameWaiter.WaitForEditorFrameAndSwitchToMainThreadAsync(ct).ConfigureAwait(false);
if (!frameReady)
{
return false;
}
await MainThreadSwitcher.SwitchToMainThread(ct);

Vector2 previousPosition = pointerData.position;
pointerData.position = endPos;
pointerData.delta = endPos - previousPosition;
ExecuteEvents.Execute(target, pointerData, ExecuteEvents.dragHandler);

SimulateMouseUiOverlayState.UpdatePosition(MouseUiCoordinateConverter.ScreenToInput(endPos));
return true;
}

float startTime = Time.realtimeSinceStartup;
float t;

do
{
bool frameReady = await MouseUiEditorFrameWaiter.WaitForEditorFrameAndSwitchToMainThreadAsync(ct).ConfigureAwait(false);
if (!frameReady)
{
return false;
}
await MainThreadSwitcher.SwitchToMainThread(ct);

float elapsed = Time.realtimeSinceStartup - startTime;
t = Mathf.Clamp01(elapsed / duration);
Vector2 previousPosition = pointerData.position;
Vector2 currentPosition = Vector2.Lerp(startPos, endPos, t);

pointerData.position = currentPosition;
pointerData.delta = currentPosition - previousPosition;

ExecuteEvents.Execute(target, pointerData, ExecuteEvents.dragHandler);

SimulateMouseUiOverlayState.UpdatePosition(MouseUiCoordinateConverter.ScreenToInput(currentPosition));
}
while (t < 1.0f);

return true;
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
#nullable enable
Comment thread
hatayama marked this conversation as resolved.
using System.Threading;
using System.Threading.Tasks;
using UnityEditor;
using UnityEngine;
using UnityEngine.EventSystems;

using io.github.hatayama.UnityCliLoop.Runtime;
using io.github.hatayama.UnityCliLoop.ToolContracts;

namespace io.github.hatayama.UnityCliLoop.FirstPartyTools
{
/// <summary>
/// Executes a complete mouse UI drag in one request.
/// </summary>
internal static class MouseUiOneShotDragExecutor
{
internal static async Task<SimulateMouseUiResponse> ExecuteDragOneShot(
MouseUiSimulationCommand parameters,
EventSystem eventSystem,
MouseUiMainThreadCleanupScheduler cleanupScheduler,
CancellationToken ct)
{
Vector2 inputStart = new(parameters.FromX, parameters.FromY);
Vector2 inputEnd = new(parameters.X, parameters.Y);
Vector2 screenStart = MouseUiCoordinateConverter.InputToScreen(inputStart);
Vector2 screenEnd = MouseUiCoordinateConverter.InputToScreen(inputEnd);
RaycastResult? hit = parameters.BypassRaycast ? null : UiRaycastHelper.RaycastUI(screenStart, eventSystem);
RaycastResult startRaycast = new();
GameObject? rawTarget = null;

if (parameters.BypassRaycast)
{
if (!MouseUiPointerTargetResolver.TryResolveGameObjectPath(
parameters.TargetPath,
"TargetPath",
MouseAction.Drag,
inputStart,
out rawTarget,
out SimulateMouseUiResponse? failureResponse))
{
return failureResponse!;
}

startRaycast = MouseUiPointerTargetResolver.CreateDirectRaycastResult(rawTarget!);
}
else if (hit != null)
{
rawTarget = hit.Value.gameObject;
startRaycast = hit.Value;
}

GameObject? explicitDropTarget = null;
if (!MouseUiPointerTargetResolver.TryResolveDropTargetPath(
parameters,
MouseAction.Drag,
inputEnd,
out explicitDropTarget,
out SimulateMouseUiResponse? dropFailureResponse))
{
return dropFailureResponse!;
}

// Execute dispatches only to the exact target; resolve the actual drag handler up the hierarchy
GameObject? target = rawTarget != null
? ExecuteEvents.GetEventHandler<IDragHandler>(rawTarget)
: null;

if (target == null)
{
SimulateMouseUiOverlayState.Update(
MouseAction.Drag, inputStart, null, null, Handles.GetMainGameViewSize());
bool expandCompleted = await MouseUiOverlayAnimator.PlayExpandAnimation(ct).ConfigureAwait(false);
if (!expandCompleted)
{
cleanupScheduler.QueueOverlayClear();
return MouseUiSimulationResponseFactory.CreateFrameTimeoutResult(MouseAction.Drag, inputStart, inputEnd, null);
}
await MainThreadSwitcher.SwitchToMainThread(ct);

bool dissipateCompleted = await MouseUiOverlayAnimator.PlayDissipateAnimation(ct).ConfigureAwait(false);
if (!dissipateCompleted)
{
cleanupScheduler.QueueOverlayClear();
return MouseUiSimulationResponseFactory.CreateFrameTimeoutResult(MouseAction.Drag, inputStart, inputEnd, null);
}
await MainThreadSwitcher.SwitchToMainThread(ct);

return new SimulateMouseUiResponse
{
Success = false,
Message = parameters.BypassRaycast
? $"TargetPath '{parameters.TargetPath}' has no drag handler."
: $"No draggable UI element at ({inputStart.x:F1}, {inputStart.y:F1}). Use find-game-objects or screenshot to verify positions.",
Action = MouseAction.Drag.ToString(),
PositionX = inputStart.x,
PositionY = inputStart.y,
EndPositionX = inputEnd.x,
EndPositionY = inputEnd.y
};
}

// uGUI drag controls (ScrollRect, Slider) only respond to left-button drags
PointerEventData pointerData = MouseUiDragEventExecutor.InitiateDrag(eventSystem, screenStart, startRaycast, target, PointerEventData.InputButton.Left);
ExecuteEvents.Execute(target, pointerData, ExecuteEvents.beginDragHandler);
pointerData.dragging = true;

string targetName = target.name;
SimulateMouseUiOverlayState.Update(
MouseAction.Drag, inputStart, inputStart, targetName, Handles.GetMainGameViewSize());

try
{
bool expandCompleted = await MouseUiOverlayAnimator.PlayExpandAnimation(ct).ConfigureAwait(false);
if (!expandCompleted)
{
cleanupScheduler.QueueOverlayClear();
return MouseUiSimulationResponseFactory.CreateFrameTimeoutResult(MouseAction.Drag, inputStart, inputEnd, targetName);
}
await MainThreadSwitcher.SwitchToMainThread(ct);

bool dragCompleted = await MouseUiDragEventExecutor.InterpolateDragPosition(pointerData, target, screenEnd, parameters.DragSpeed, ct)
.ConfigureAwait(false);
if (!dragCompleted)
{
cleanupScheduler.QueueOverlayClear();
return MouseUiSimulationResponseFactory.CreateFrameTimeoutResult(MouseAction.Drag, inputStart, inputEnd, targetName);
}
await MainThreadSwitcher.SwitchToMainThread(ct);

bool frameReady = await MouseUiEditorFrameWaiter.WaitForEditorFrameAndSwitchToMainThreadAsync(ct).ConfigureAwait(false);
if (!frameReady)
{
cleanupScheduler.QueueOverlayClear();
return MouseUiSimulationResponseFactory.CreateFrameTimeoutResult(MouseAction.Drag, inputStart, inputEnd, targetName);
}
await MainThreadSwitcher.SwitchToMainThread(ct);
}
finally
{
cleanupScheduler.ExecuteCleanupOnMainThread(() => MouseUiDragEventExecutor.FinalizeDrag(pointerData, target, explicitDropTarget));
}

SimulateMouseUiOverlayState.Update(
MouseAction.Drag, inputEnd, inputStart, targetName, Handles.GetMainGameViewSize());

bool completedDissipate = await MouseUiOverlayAnimator.PlayDissipateAnimation(ct).ConfigureAwait(false);
if (!completedDissipate)
{
cleanupScheduler.QueueOverlayClear();
return MouseUiSimulationResponseFactory.CreateDragResult(parameters, inputStart, inputEnd, targetName);
}
await MainThreadSwitcher.SwitchToMainThread(ct);

return MouseUiSimulationResponseFactory.CreateDragResult(parameters, inputStart, inputEnd, targetName);
}
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading