1
0
mirror of https://github.com/ppy/osu.git synced 2024-09-30 16:07:31 +08:00
osu-lazer/osu.Game/Graphics/UserInterface/HistoryTextBox.cs

119 lines
3.3 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.
2022-11-16 06:51:57 +08:00
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Input.Events;
using osuTK.Input;
namespace osu.Game.Graphics.UserInterface
{
2022-11-15 23:12:24 +08:00
public class HistoryTextBox : FocusedTextBox
{
2022-11-16 06:51:57 +08:00
private readonly int historyLimit;
private bool everythingSelected;
public int HistoryLength => messageHistory.Count;
2022-11-15 23:12:24 +08:00
private readonly List<string> messageHistory;
public IReadOnlyList<string> MessageHistory =>
Enumerable.Range(0, HistoryLength).Select(GetOldMessage).ToList();
private string originalMessage = string.Empty;
2022-11-16 06:51:57 +08:00
private int historyIndex = -1;
private int startIndex;
private int getNormalizedIndex(int index) =>
(HistoryLength + startIndex - index - 1) % HistoryLength;
2022-11-16 06:51:57 +08:00
public HistoryTextBox(int historyLimit = 100)
{
2022-11-16 06:51:57 +08:00
this.historyLimit = historyLimit;
messageHistory = new List<string>(historyLimit);
Current.ValueChanged += text =>
{
if (string.IsNullOrEmpty(text.NewValue) || everythingSelected)
{
historyIndex = -1;
everythingSelected = false;
}
};
}
protected override void OnTextSelectionChanged(TextSelectionType selectionType)
{
everythingSelected = SelectedText == Text;
base.OnTextSelectionChanged(selectionType);
}
2022-11-16 06:51:57 +08:00
public string GetOldMessage(int index)
{
if (index < 0 || index >= HistoryLength)
2022-11-16 06:51:57 +08:00
throw new ArgumentOutOfRangeException();
return HistoryLength == 0 ? string.Empty : messageHistory[getNormalizedIndex(index)];
2022-11-16 06:51:57 +08:00
}
protected override bool OnKeyDown(KeyDownEvent e)
{
switch (e.Key)
{
case Key.Up:
if (historyIndex == HistoryLength - 1)
return true;
if (historyIndex == -1)
originalMessage = Text;
Text = messageHistory[getNormalizedIndex(++historyIndex)];
return true;
case Key.Down:
if (historyIndex == -1)
return true;
if (historyIndex == 0)
{
historyIndex = -1;
Text = originalMessage;
return true;
}
Text = messageHistory[getNormalizedIndex(--historyIndex)];
return true;
}
return base.OnKeyDown(e);
}
protected override void Commit()
{
if (!string.IsNullOrEmpty(Text))
2022-11-16 06:51:57 +08:00
{
if (HistoryLength == historyLimit)
2022-11-16 06:51:57 +08:00
{
messageHistory[startIndex++] = Text;
startIndex %= historyLimit;
2022-11-16 06:51:57 +08:00
}
else
{
messageHistory.Add(Text);
}
}
historyIndex = -1;
base.Commit();
}
}
}