1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
private Font _font = new Font("Tahoma", 9f);
protected override void OnKeyEvent(KeyEvent e)
{
if(e.Key == Microsoft.Xna.Framework.Input.Keys.Left)
{
if (_index > 0)
_index--;
}
if (e.Key == Microsoft.Xna.Framework.Input.Keys.Right)
if (_index < _text.Length)
_index++;
if (e.KeyChar != '\0') {
_text = _text.Insert(_index, e.KeyChar.ToString());
_index++;
}
CalculateVisibleText();
Invalidate();
base.OnKeyEvent(e);
}
private int textInputOffset = 0;
private int maxCanFit = 5;
string visibleText = "";
float caretPos = 2f;
protected void CalculateVisibleText()
{
visibleText = "";
caretPos = -1f;
using (var gfx = Graphics.FromImage(new Bitmap(1, 1)))
{
for (int i = textInputOffset; i < _text.Length; i++)
{
visibleText += _text[i];
var measure = gfx.MeasureString(visibleText, _font);
if (measure.Width > Width)
{
maxCanFit = visibleText.Length;
if(_index < textInputOffset)
{
textInputOffset = MathHelper.Clamp(_index - (maxCanFit / 2), 0, _text.Length - 1);
}
if(_index > textInputOffset + maxCanFit)
{
textInputOffset = MathHelper.Clamp(_index + (maxCanFit / 2), 0, _text.Length - 1) - maxCanFit;
}
break;
}
Height = (int)measure.Height + 4;
}
}
}
protected override void OnPaint(Graphics gfx)
{
gfx.Clear(LoadedSkin.ControlColor);
gfx.DrawString(visibleText, _font, new SolidBrush(LoadedSkin.ControlTextColor), 2, 2);
if (IsFocusedControl)
{
//Draw caret.
gfx.FillRectangle(new SolidBrush(LoadedSkin.ControlTextColor), new RectangleF(caretPos, 2, 2, Height - 4));
}
gfx.DrawRectangle(new Pen(new SolidBrush(LoadedSkin.ControlTextColor), 1), new Rectangle(0, 0, Width - 1, Height - 1));
}
}
}
|