1
0
mirror of https://github.com/ppy/osu.git synced 2024-12-27 12:22:54 +08:00
osu-lazer/osu.Game/Screens/Edit/Compose/Components/BlueprintContainer.cs

613 lines
23 KiB
C#
Raw Normal View History

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
2018-04-13 17:19:50 +08:00
2022-06-17 15:37:17 +08:00
#nullable disable
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
2018-10-18 15:36:06 +08:00
using System.Linq;
using JetBrains.Annotations;
2018-04-13 17:19:50 +08:00
using osu.Framework.Allocation;
using osu.Framework.Bindables;
2018-04-13 17:19:50 +08:00
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
2018-10-02 11:02:47 +08:00
using osu.Framework.Input.Events;
using osu.Game.Graphics.UserInterface;
2018-04-13 17:19:50 +08:00
using osu.Game.Rulesets.Edit;
2019-10-16 19:34:16 +08:00
using osuTK;
using osuTK.Input;
2018-04-13 17:19:50 +08:00
2018-11-06 17:28:22 +08:00
namespace osu.Game.Screens.Edit.Compose.Components
2018-04-13 17:19:50 +08:00
{
/// <summary>
/// A container which provides a "blueprint" display of items.
/// Includes selection and manipulation support via a <see cref="Components.SelectionHandler{T}"/>.
/// </summary>
2022-11-24 13:32:20 +08:00
public abstract partial class BlueprintContainer<T> : CompositeDrawable, IKeyBindingHandler<PlatformAction>
where T : class
2018-04-13 17:19:50 +08:00
{
2020-01-16 10:54:03 +08:00
protected DragBox DragBox { get; private set; }
public Container<SelectionBlueprint<T>> SelectionBlueprints { get; private set; }
protected SelectionHandler<T> SelectionHandler { get; private set; }
private readonly Dictionary<T, SelectionBlueprint<T>> blueprintMap = new Dictionary<T, SelectionBlueprint<T>>();
[Resolved(canBeNull: true)]
private IPositionSnapProvider snapProvider { get; set; }
[Resolved(CanBeNull = true)]
private IEditorChangeHandler changeHandler { get; set; }
protected readonly BindableList<T> SelectedItems = new BindableList<T>();
/// <summary>
/// Whether to allow cyclic selection on clicking multiple times.
/// </summary>
/// <remarks>
/// Disabled by default as it does not work well with editors that support double-clicking or other advanced interactions.
/// Can probably be made to work with more thought.
/// </remarks>
protected virtual bool AllowCyclicSelection => false;
protected BlueprintContainer()
{
2018-04-13 17:19:50 +08:00
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load()
2018-04-13 17:19:50 +08:00
{
2022-06-24 20:25:23 +08:00
SelectedItems.CollectionChanged += (_, args) =>
{
switch (args.Action)
{
case NotifyCollectionChangedAction.Add:
Debug.Assert(args.NewItems != null);
foreach (object o in args.NewItems)
{
if (blueprintMap.TryGetValue((T)o, out var blueprint))
blueprint.Select();
}
break;
case NotifyCollectionChangedAction.Remove:
Debug.Assert(args.OldItems != null);
foreach (object o in args.OldItems)
{
if (blueprintMap.TryGetValue((T)o, out var blueprint))
blueprint.Deselect();
}
break;
}
};
SelectionHandler = CreateSelectionHandler();
SelectionHandler.DeselectAll = DeselectAll;
SelectionHandler.SelectedItems.BindTo(SelectedItems);
2018-04-13 17:19:50 +08:00
AddRangeInternal(new[]
2018-04-13 17:19:50 +08:00
{
DragBox = CreateDragBox(),
SelectionHandler,
2020-02-07 17:04:10 +08:00
SelectionBlueprints = CreateSelectionBlueprintContainer(),
SelectionHandler.CreateProxy(),
2020-01-16 10:54:03 +08:00
DragBox.CreateProxy().With(p => p.Depth = float.MinValue)
});
2019-08-29 15:06:40 +08:00
}
protected virtual Container<SelectionBlueprint<T>> CreateSelectionBlueprintContainer() => new Container<SelectionBlueprint<T>> { RelativeSizeAxes = Axes.Both };
2020-01-24 16:50:36 +08:00
2020-01-16 10:54:03 +08:00
/// <summary>
/// Creates a <see cref="Components.SelectionHandler{T}"/> which outlines items and handles movement of selections.
2020-01-16 10:54:03 +08:00
/// </summary>
protected abstract SelectionHandler<T> CreateSelectionHandler();
2020-01-16 10:54:03 +08:00
/// <summary>
/// Creates a <see cref="SelectionBlueprint{T}"/> for a specific item.
2020-01-16 10:54:03 +08:00
/// </summary>
/// <param name="item">The item to create the overlay for.</param>
[CanBeNull]
protected virtual SelectionBlueprint<T> CreateBlueprintFor(T item) => null;
2020-01-16 10:54:03 +08:00
protected virtual DragBox CreateDragBox() => new DragBox();
2020-01-16 10:54:03 +08:00
protected override bool OnMouseDown(MouseDownEvent e)
{
bool selectionPerformed = performMouseDownActions(e);
bool movementPossible = prepareSelectionMovement();
// check if selection has occurred
if (selectionPerformed)
{
2021-10-27 04:24:53 +08:00
// only unmodified right click should show context menu
bool shouldShowContextMenu = e.Button == MouseButton.Right && !e.ShiftPressed && !e.AltPressed && !e.SuperPressed;
2021-10-27 04:24:53 +08:00
// stop propagation if not showing context menu
return !shouldShowContextMenu;
}
// even if a selection didn't occur, a drag event may still move the selection.
return e.Button == MouseButton.Left && movementPossible;
}
protected SelectionBlueprint<T> ClickedBlueprint { get; private set; }
protected override bool OnClick(ClickEvent e)
{
if (e.Button == MouseButton.Right)
return false;
// store for double-click handling
ClickedBlueprint = SelectionHandler.SelectedBlueprints.FirstOrDefault(b => b.IsHovered);
2019-10-24 15:14:29 +08:00
// Deselection should only occur if no selected blueprints are hovered
// A special case for when a blueprint was selected via this click is added since OnClick() may occur outside the item and should not trigger deselection
if (endClickSelection(e) || ClickedBlueprint != null)
return true;
DeselectAll();
return true;
}
protected override bool OnDoubleClick(DoubleClickEvent e)
{
if (e.Button == MouseButton.Right)
return false;
// ensure the blueprint which was hovered for the first click is still the hovered blueprint.
if (ClickedBlueprint == null || SelectionHandler.SelectedBlueprints.FirstOrDefault(b => b.IsHovered) != ClickedBlueprint)
return false;
return true;
}
protected override void OnMouseUp(MouseUpEvent e)
{
2019-10-24 15:14:29 +08:00
// Special case for when a drag happened instead of a click
Schedule(() =>
{
endClickSelection(e);
clickSelectionHandled = false;
isDraggingBlueprint = false;
wasDragStarted = false;
});
finishSelectionMovement();
}
2022-10-11 21:39:53 +08:00
private MouseButtonEvent lastDragEvent;
protected override bool OnDragStart(DragStartEvent e)
{
if (e.Button == MouseButton.Right)
return false;
2022-10-11 21:39:53 +08:00
lastDragEvent = e;
wasDragStarted = true;
2022-10-11 21:39:53 +08:00
if (movementBlueprints != null)
{
isDraggingBlueprint = true;
changeHandler?.BeginChange();
return true;
}
DragBox.HandleDrag(e);
DragBox.Show();
return true;
}
protected override void OnDrag(DragEvent e)
{
2022-10-11 21:39:53 +08:00
lastDragEvent = e;
moveCurrentSelection(e);
}
protected override void OnDragEnd(DragEndEvent e)
{
2022-10-11 21:39:53 +08:00
lastDragEvent = null;
if (isDraggingBlueprint)
{
DragOperationCompleted();
changeHandler?.EndChange();
}
DragBox.Hide();
}
2022-10-11 21:39:53 +08:00
protected override void Update()
{
base.Update();
if (lastDragEvent != null && DragBox.State == Visibility.Visible)
{
lastDragEvent.Target = this;
DragBox.HandleDrag(lastDragEvent);
UpdateSelectionFromDragBox();
}
}
/// <summary>
/// Called whenever a drag operation completes, before any change transaction is committed.
/// </summary>
protected virtual void DragOperationCompleted()
{
}
protected override bool OnKeyDown(KeyDownEvent e)
{
switch (e.Key)
{
case Key.Escape:
if (!SelectionHandler.SelectedBlueprints.Any())
return false;
DeselectAll();
return true;
}
return false;
}
2021-09-16 17:26:12 +08:00
public bool OnPressed(KeyBindingPressEvent<PlatformAction> e)
{
if (e.Repeat)
return false;
2021-09-16 17:26:12 +08:00
switch (e.Action)
{
2021-07-20 13:23:34 +08:00
case PlatformAction.SelectAll:
SelectAll();
return true;
}
return false;
}
2021-09-16 17:26:12 +08:00
public void OnReleased(KeyBindingReleaseEvent<PlatformAction> e)
{
}
#region Blueprint Addition/Removal
protected virtual void AddBlueprintFor(T item)
2018-10-18 15:36:06 +08:00
{
if (blueprintMap.ContainsKey(item))
return;
var blueprint = CreateBlueprintFor(item);
if (blueprint == null)
2018-10-18 15:36:06 +08:00
return;
blueprintMap[item] = blueprint;
blueprint.Selected += OnBlueprintSelected;
blueprint.Deselected += OnBlueprintDeselected;
SelectionBlueprints.Add(blueprint);
if (SelectionHandler.SelectedItems.Contains(item))
blueprint.Select();
OnBlueprintAdded(blueprint.Item);
}
protected void RemoveBlueprintFor(T item)
{
if (!blueprintMap.Remove(item, out var blueprint))
return;
blueprint.Deselect();
blueprint.Selected -= OnBlueprintSelected;
blueprint.Deselected -= OnBlueprintDeselected;
SelectionBlueprints.Remove(blueprint, true);
if (movementBlueprints?.Contains(blueprint) == true)
finishSelectionMovement();
OnBlueprintRemoved(blueprint.Item);
}
/// <summary>
/// Called after an item's blueprint has been added.
/// </summary>
/// <param name="item">The item for which the blueprint has been added.</param>
protected virtual void OnBlueprintAdded(T item)
2019-08-29 15:06:40 +08:00
{
}
/// <summary>
/// Called after an item's blueprint has been removed.
/// </summary>
/// <param name="item">The item for which the blueprint has been removed.</param>
protected virtual void OnBlueprintRemoved(T item)
{
2019-08-29 15:06:40 +08:00
}
2021-05-13 20:16:19 +08:00
/// <summary>
/// Retrieves an item's blueprint.
/// </summary>
/// <param name="item">The item to retrieve the blueprint of.</param>
/// <returns>The blueprint.</returns>
protected SelectionBlueprint<T> GetBlueprintFor(T item) => blueprintMap[item];
#endregion
2019-08-29 15:06:40 +08:00
#region Selection
/// <summary>
/// Whether a blueprint was selected by a previous click event.
/// </summary>
private bool clickSelectionHandled;
/// <summary>
/// Whether the selected blueprint(s) were already selected on mouse down. Generally used to perform selection cycling on mouse up in such a case.
/// </summary>
private bool selectedBlueprintAlreadySelectedOnMouseDown;
/// <summary>
/// Attempts to select any hovered blueprints.
/// </summary>
/// <param name="e">The input event that triggered this selection.</param>
2020-11-04 16:53:03 +08:00
/// <returns>Whether a selection was performed.</returns>
private bool performMouseDownActions(MouseButtonEvent e)
{
2020-11-18 12:37:15 +08:00
// Iterate from the top of the input stack (blueprints closest to the front of the screen first).
// Priority is given to already-selected blueprints.
foreach (SelectionBlueprint<T> blueprint in SelectionBlueprints.AliveChildren.Reverse().OrderByDescending(b => b.IsSelected))
{
if (!blueprint.IsHovered) continue;
selectedBlueprintAlreadySelectedOnMouseDown = blueprint.State == SelectionState.Selected;
return clickSelectionHandled = SelectionHandler.MouseDownSelectionRequested(blueprint, e);
}
return false;
}
/// <summary>
/// Finishes the current blueprint selection.
/// </summary>
/// <param name="e">The mouse event which triggered end of selection.</param>
2019-10-24 15:14:29 +08:00
/// <returns>Whether a click selection was active.</returns>
private bool endClickSelection(MouseButtonEvent e)
{
// If already handled a selection or drag, we don't want to perform a mouse up / click action.
if (clickSelectionHandled || isDraggingBlueprint) return true;
if (e.Button != MouseButton.Left) return false;
if (e.ControlPressed)
{
// if a selection didn't occur, we may want to trigger a deselection.
// Iterate from the top of the input stack (blueprints closest to the front of the screen first).
// Priority is given to already-selected blueprints.
foreach (SelectionBlueprint<T> blueprint in SelectionBlueprints.AliveChildren.Where(b => b.IsHovered).OrderByDescending(b => b.IsSelected))
return clickSelectionHandled = SelectionHandler.MouseUpSelectionRequested(blueprint, e);
return false;
}
if (!wasDragStarted && selectedBlueprintAlreadySelectedOnMouseDown && SelectedItems.Count == 1 && AllowCyclicSelection)
{
// If a click occurred and was handled by the currently selected blueprint but didn't result in a drag,
// cycle between other blueprints which are also under the cursor.
// The depth of blueprints is constantly changing (see above where selected blueprints are brought to the front).
// For this logic, we want a stable sort order so we can correctly cycle, thus using the blueprintMap instead.
IEnumerable<SelectionBlueprint<T>> cyclingSelectionBlueprints = blueprintMap.Values;
// If there's already a selection, let's start from the blueprint after the selection.
cyclingSelectionBlueprints = cyclingSelectionBlueprints.SkipWhile(b => !b.IsSelected).Skip(1);
// Add the blueprints from before the selection to the end of the enumerable to allow for cyclic selection.
cyclingSelectionBlueprints = cyclingSelectionBlueprints.Concat(blueprintMap.Values.TakeWhile(b => !b.IsSelected));
foreach (SelectionBlueprint<T> blueprint in cyclingSelectionBlueprints)
{
if (!blueprint.IsHovered) continue;
// We are performing a mouse up, but selection handlers perform selection on mouse down, so we need to call that instead.
return clickSelectionHandled = SelectionHandler.MouseDownSelectionRequested(blueprint, e);
}
}
2019-10-24 15:14:29 +08:00
return false;
}
/// <summary>
/// Select all blueprints in a selection area specified by <see cref="DragBox"/>.
/// </summary>
protected virtual void UpdateSelectionFromDragBox()
{
var quad = DragBox.Box.ScreenSpaceDrawQuad;
2020-02-07 17:04:10 +08:00
foreach (var blueprint in SelectionBlueprints)
{
switch (blueprint.State)
{
case SelectionState.Selected:
// Selection is preserved even after blueprint becomes dead.
if (!quad.Contains(blueprint.ScreenSpaceSelectionPoint))
blueprint.Deselect();
break;
case SelectionState.NotSelected:
if (blueprint.IsAlive && blueprint.IsPresent && quad.Contains(blueprint.ScreenSpaceSelectionPoint))
blueprint.Select();
break;
}
}
}
/// <summary>
/// Select all currently-present items.
/// </summary>
protected abstract void SelectAll();
/// <summary>
/// Deselect all selected items.
/// </summary>
protected void DeselectAll() => SelectedItems.Clear();
protected virtual void OnBlueprintSelected(SelectionBlueprint<T> blueprint)
{
SelectionHandler.HandleSelected(blueprint);
2020-02-07 17:04:10 +08:00
SelectionBlueprints.ChangeChildDepth(blueprint, 1);
}
protected virtual void OnBlueprintDeselected(SelectionBlueprint<T> blueprint)
{
2020-02-07 17:04:10 +08:00
SelectionBlueprints.ChangeChildDepth(blueprint, 0);
SelectionHandler.HandleDeselected(blueprint);
}
#endregion
#region Selection Movement
2023-01-19 04:34:23 +08:00
private Vector2[][] movementBlueprintsOriginalPositions;
private SelectionBlueprint<T>[] movementBlueprints;
/// <summary>
/// Whether a blueprint is currently being dragged.
/// </summary>
2023-03-08 18:24:03 +08:00
private bool isDraggingBlueprint;
/// <summary>
/// Whether a drag operation was started at all.
/// </summary>
private bool wasDragStarted;
/// <summary>
/// Attempts to begin the movement of any selected blueprints.
/// </summary>
/// <returns>Whether a movement is possible.</returns>
private bool prepareSelectionMovement()
{
if (!SelectionHandler.SelectedBlueprints.Any())
return false;
// Any selected blueprint that is hovered can begin the movement of the group, however only the first item (according to SortForMovement) is used for movement.
2019-10-24 15:14:29 +08:00
// A special case is added for when a click selection occurred before the drag
if (!clickSelectionHandled && !SelectionHandler.SelectedBlueprints.Any(b => b.IsHovered))
return false;
// Movement is tracked from the blueprint of the earliest item, since it only makes sense to distance snap from that item
movementBlueprints = SortForMovement(SelectionHandler.SelectedBlueprints).ToArray();
2023-01-19 05:00:39 +08:00
movementBlueprintsOriginalPositions = movementBlueprints.Select(m => m.ScreenSpaceSnapPoints).ToArray();
return true;
}
/// <summary>
/// Apply sorting of selected blueprints before performing movement. Generally used to surface the "main" item to the beginning of the collection.
/// </summary>
/// <param name="blueprints">The blueprints to be moved.</param>
/// <returns>Sorted blueprints.</returns>
protected virtual IEnumerable<SelectionBlueprint<T>> SortForMovement(IReadOnlyList<SelectionBlueprint<T>> blueprints) => blueprints;
/// <summary>
/// Moves the current selected blueprints.
/// </summary>
/// <param name="e">The <see cref="DragEvent"/> defining the movement event.</param>
/// <returns>Whether a movement was active.</returns>
private bool moveCurrentSelection(DragEvent e)
{
if (movementBlueprints == null)
return false;
2023-01-19 04:34:23 +08:00
Debug.Assert(movementBlueprintsOriginalPositions != null);
2023-01-18 22:54:24 +08:00
Vector2 distanceTravelled = e.ScreenSpaceMousePosition - e.ScreenSpaceMouseDownPosition;
if (snapProvider != null)
{
2023-01-19 04:34:23 +08:00
for (int i = 0; i < movementBlueprints.Length; i++)
{
if (checkSnappingBlueprintToNearbyObjects(movementBlueprints[i], distanceTravelled, movementBlueprintsOriginalPositions[i]))
return true;
}
}
// if no positional snapping could be performed, try unrestricted snapping from the earliest
// item in the selection.
// The final movement position, relative to movementBlueprintOriginalPosition.
2023-01-19 04:34:23 +08:00
Vector2 movePosition = movementBlueprintsOriginalPositions.First().First() + distanceTravelled;
// Retrieve a snapped position.
var result = snapProvider?.FindSnappedPositionAndTime(movePosition, ~SnapType.NearbyObjects);
if (result == null)
{
return SelectionHandler.HandleMovement(new MoveSelectionEvent<T>(movementBlueprints.First(), movePosition - movementBlueprints.First().ScreenSpaceSelectionPoint));
}
2019-10-16 19:34:02 +08:00
return ApplySnapResult(movementBlueprints, result);
}
2023-01-18 03:41:49 +08:00
/// <summary>
2023-01-19 04:34:23 +08:00
/// Check for positional snap for given blueprint.
2023-01-18 03:41:49 +08:00
/// </summary>
2023-01-24 04:22:18 +08:00
/// <param name="blueprint">The blueprint to check for snapping.</param>
/// <param name="distanceTravelled">Distance travelled since start of dragging action.</param>
/// <param name="originalPositions">The snap positions of blueprint before start of dragging action.</param>
/// <returns>Whether an object to snap to was found.</returns>
2023-01-19 04:34:23 +08:00
private bool checkSnappingBlueprintToNearbyObjects(SelectionBlueprint<T> blueprint, Vector2 distanceTravelled, Vector2[] originalPositions)
2023-01-18 03:41:49 +08:00
{
2023-01-19 05:00:39 +08:00
var currentPositions = blueprint.ScreenSpaceSnapPoints;
2023-01-19 04:34:23 +08:00
2023-01-18 03:41:49 +08:00
for (int i = 0; i < originalPositions.Length; i++)
{
Vector2 originalPosition = originalPositions[i];
2023-01-18 22:54:24 +08:00
var testPosition = originalPosition + distanceTravelled;
2023-01-18 03:41:49 +08:00
var positionalResult = snapProvider.FindSnappedPositionAndTime(testPosition, SnapType.NearbyObjects);
if (positionalResult.ScreenSpacePosition == testPosition) continue;
var delta = positionalResult.ScreenSpacePosition - currentPositions[i];
// attempt to move the objects, and abort any time based snapping if we can.
2023-01-19 04:34:23 +08:00
if (SelectionHandler.HandleMovement(new MoveSelectionEvent<T>(blueprint, delta)))
2023-01-18 03:41:49 +08:00
return true;
}
2023-01-19 05:00:39 +08:00
2023-01-18 03:41:49 +08:00
return false;
}
protected virtual bool ApplySnapResult(SelectionBlueprint<T>[] blueprints, SnapResult result) =>
SelectionHandler.HandleMovement(new MoveSelectionEvent<T>(blueprints.First(), result.ScreenSpacePosition - blueprints.First().ScreenSpaceSelectionPoint));
/// <summary>
/// Finishes the current movement of selected blueprints.
/// </summary>
/// <returns>Whether a movement was active.</returns>
private bool finishSelectionMovement()
{
if (movementBlueprints == null)
return false;
2023-01-19 04:34:23 +08:00
movementBlueprintsOriginalPositions = null;
movementBlueprints = null;
2019-10-16 19:34:16 +08:00
return true;
}
#endregion
2018-04-13 17:19:50 +08:00
}
}