ShiftOS_TheReturn/ShiftOS.Frontend/GUI/TextInput.cs

140 lines
3.9 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
2017-07-03 15:29:54 +00:00
using Microsoft.Xna.Framework;
using ShiftOS.Frontend.GraphicsSubsystem;
using static ShiftOS.Engine.SkinEngine;
namespace ShiftOS.Frontend.GUI
{
public class TextInput : Control
{
private string _label = "Type here!";
private string _text = "";
private int _index = 0;
2017-07-03 15:29:54 +00:00
private Font _font = new Font("Tahoma", 9f);
public int Index
{
get
{
return _index;
}
set
{
if (_index == value)
return;
if(_text.Length == 0)
{
_index = 0;
return;
}
2017-07-04 13:52:49 +00:00
_index = MathHelper.Clamp(value, 0, _text.Length);
Invalidate();
}
}
public string Text
{
get
{
return _text;
}
set
{
if (_text == value)
return;
_text = value;
if(_index >= _text.Length)
{
_index = _text.Length - 1;
}
Invalidate();
}
}
protected override void OnKeyEvent(KeyEvent e)
{
if(e.Key == Microsoft.Xna.Framework.Input.Keys.Left)
{
if (_index > 0)
_index--;
2017-07-03 15:29:54 +00:00
}
if(e.Key == Microsoft.Xna.Framework.Input.Keys.Back)
{
if(_index > 0)
{
_text = _text.Remove(_index - 1, 1);
_index--;
}
}
if(e.Key == Microsoft.Xna.Framework.Input.Keys.Delete)
{
if(_index < _text.Length - 1)
{
_text = _text.Remove(_index, 1);
}
}
if (e.Key == Microsoft.Xna.Framework.Input.Keys.Right)
if (_index < _text.Length)
_index++;
2017-07-03 15:29:54 +00:00
if (e.KeyChar != '\0') {
_text = _text.Insert(_index, e.KeyChar.ToString());
_index++;
}
CalculateVisibleText();
Invalidate();
base.OnKeyEvent(e);
}
2017-07-03 15:29:54 +00:00
float caretPos = 2f;
protected void CalculateVisibleText()
{
using(var gfx = Graphics.FromImage(new Bitmap(1, 1)))
2017-07-03 15:29:54 +00:00
{
string toCaret = _text.Substring(0, _index);
var measure = gfx.MeasureString(toCaret, _font);
caretPos = 2 + measure.Width;
while(caretPos - _textDrawOffset < 0)
2017-07-03 15:29:54 +00:00
{
_textDrawOffset -= 0.01f;
2017-07-03 15:29:54 +00:00
}
while(caretPos - _textDrawOffset > Width)
{
_textDrawOffset += 0.01f;
}
2017-07-03 15:29:54 +00:00
}
}
private float _textDrawOffset = 0;
2017-07-03 15:29:54 +00:00
2017-07-03 12:55:21 +00:00
protected override void OnPaint(Graphics gfx)
{
gfx.Clear(LoadedSkin.ControlColor);
gfx.DrawString(_text, _font, new SolidBrush(LoadedSkin.ControlTextColor), 2 - _textDrawOffset, 2);
2017-07-03 15:29:54 +00:00
if (IsFocusedControl)
{
//Draw caret.
gfx.FillRectangle(new SolidBrush(LoadedSkin.ControlTextColor), new RectangleF(caretPos - _textDrawOffset, 2, 2, Height - 4));
}
else
{
if (string.IsNullOrEmpty(_text))
{
gfx.DrawString(_label, _font, Brushes.Gray, 2, 2);
}
2017-07-03 15:29:54 +00:00
}
gfx.DrawRectangle(new Pen(new SolidBrush(LoadedSkin.ControlTextColor), 1), new System.Drawing.Rectangle(0, 0, Width - 1, Height - 1));
2017-07-03 15:29:54 +00:00
}
}
}