1 /// module containing the text UI element
2 module ysge.ui.text;
3 
4 import std.string;
5 import ysge.project;
6 
7 class Text : UIElement {
8 	private string       text;
9 	private SDL_Texture* texture;
10 	SDL_Color            colour;
11 	Vec2!int             pos;
12 	float                scale = 1.0;
13 
14 	/// sets the text that is rendered
15 	void SetText(string newText) {
16 		if (text != newText) {
17 			texture = null;
18 		}
19 
20 		text = newText;
21 	}
22 
23 	/// returns the size in pixels of the text
24 	Vec2!int GetTextSize(Project project) {
25 		Vec2!int ret;
26 		
27 		CreateTexture(project);
28 		SDL_QueryTexture(texture, null, null, &ret.x, &ret.y);
29 		return ret;
30 	}
31 
32 	private void CreateTexture(Project project) {
33 		if (texture is null) {
34 			SDL_Surface* surface = TTF_RenderText_Solid(
35 				project.font, toStringz(text), colour
36 			);
37 
38 			if (surface is null) {
39 				throw new ProjectException("Failed to render text");
40 			}
41 
42 			texture = SDL_CreateTextureFromSurface(project.renderer, surface);
43 
44 			if (texture is null) {
45 				throw new ProjectException("Failed to create text texture");
46 			}
47 		}
48 	}
49 
50 	override bool HandleEvent(Project project, SDL_Event e) {
51 		return false;
52 	}
53 
54 	override void Render(Project project) {
55 		CreateTexture(project);
56 	
57 		SDL_Rect textBox;
58 		textBox.x = pos.x;
59 		textBox.y = pos.y;
60 
61 		SDL_QueryTexture(texture, null, null, &textBox.w, &textBox.h);
62 
63 		textBox.w = cast(int) ((cast(float) textBox.w) * scale);
64 		textBox.h = cast(int) ((cast(float) textBox.h) * scale);
65 
66 		SDL_RenderCopy(project.renderer, texture, null, &textBox);
67 	}
68 }