1 module ws.gui.inputFieldSimple;
2 
3 import
4 	std.conv,
5 	ws.event,
6 	ws.io,
7 	ws.time,
8 	ws.math.math,
9 	ws.gl.draw,
10 	ws.gui.base,
11 	ws.gui.text;
12 
13 
14 class InputField: Base {
15 	
16 	bool hasFocus = false;
17 	Event!string onEnter;
18 
19 	string text;
20 	size_t cursor;
21 
22 	string error;
23 	double errorTime;
24 	bool blockChar;
25 
26 	this(){
27 		setCursor(Mouse.cursor.text);
28 		onEnter = new Event!string;
29 	}
30 
31 	override void onKeyboard(dchar c){
32 		if(!blockChar){
33 			text = text[0..cursor] ~ c.to!string ~ text[cursor..$];
34 			cursor++;
35 			blockChar = false;
36 		}
37 	}
38 
39 	override void onKeyboard(Keyboard.key key, bool pressed){
40 		if(!pressed)
41 			return;
42 		blockChar = true;
43 		switch(key){
44 			case Keyboard.backspace:
45 				if(cursor > 0){
46 					text = text[0..cursor-1] ~ text[cursor..$];
47 					cursor--;
48 				}
49 				break;
50 				
51 			case Keyboard.del:
52 				if(cursor < text.length){
53 					text = text[0..cursor] ~ text[cursor+1..$];
54 				}
55 				break;
56 				
57 			case Keyboard.enter:
58 				try
59 					onEnter(text);
60 				catch(InputException e){
61 					error = e.msg;
62 					errorTime = now;
63 				}
64 				break;
65 				
66 			case Keyboard.right:
67 				if(Keyboard.get(Keyboard.control))
68 					while(cursor < text.length && text[cursor+1] != ' ')
69 						++cursor;
70 				else if(cursor < text.length)
71 					++cursor;
72 				break;
73 				
74 			case Keyboard.left:
75 				if(Keyboard.get(Keyboard.control))
76 					while(cursor > 0 && text[cursor-1] != ' ')
77 						--cursor;
78 				else if(cursor > 0)
79 					--cursor;
80 				break;
81 				
82 			default:
83 				blockChar = false;
84 				break;
85 		}
86 
87 	}
88 
89 
90 	override void onKeyboardFocus(bool hasFocus){
91 		this.hasFocus = hasFocus;
92 	}
93 
94 
95 	override void onDraw(){
96 		draw.setColor([0.867,0.514,0]);
97 		draw.rectOutline(pos, size);
98 		auto color = style.fg.normal;
99 		if(hasFocus || hasMouseFocus){
100 			auto alpha = (sin(now*PI*2)+0.5).min(1).max(0)*0.9+0.1;
101 			draw.setColor([1*alpha,1*alpha,1*alpha]);
102 			int x = draw.width(text[0..cursor]);
103 			draw.rect(pos.a + [x+4, 4], [1, size.h-8]);
104 		}
105 		auto t = now;
106 		if(errorTime+2 > t){
107 			auto alpha = clamp!float(errorTime+2 - t, 0, 1)/1;
108 			draw.setColor([1,0,0,alpha]);
109 			draw.rect(pos, size);
110 			draw.setFont("Consolas", 9);
111 			draw.setColor([1,1,1,alpha]);
112 			draw.text(pos.a + [2, 0], size.h, error);
113 		}
114 		draw.setColor([1,1,1]);
115 		draw.text(pos, size.h, text);
116 	}
117 
118 
119 }
120 
121 
122 class InputException: Exception {
123 	InputField text;
124 	this(InputField t, string msg, string file = __FILE__, size_t line = __LINE__){
125 		text = t;
126 		super(msg, null, file, line);
127 	}
128 	this(InputField t, string msg, Exception cause, string file = __FILE__, size_t line = __LINE__){
129 		text = t;
130 		super(msg, cause, file, line);
131 	}
132 }