Explorar el Código

Hacked around text input

Ewwww/yay!
Luna Stadler %!s(int64=4) %!d(string=hace) años
padre
commit
37f9af47b2
Se han modificado 1 ficheros con 50 adiciones y 13 borrados
  1. 50 13
      c/sdl/hello_sdl.c

+ 50 - 13
c/sdl/hello_sdl.c

@ -1,7 +1,15 @@
1
// Playing around with SDL + TTF.
2
//
3
// Resources:
4
// - http://wiki.libsdl.org/CategoryAPI
5
// - https://www.libsdl.org/projects/SDL_ttf/docs/SDL_ttf.html
6
7
#include <sys/param.h>
8
1 9
#include <SDL.h>
2 10
#include <SDL_ttf.h>
3 11
4
char *font_file = "./NotoColorEmoji.ttf";
12
char *font_file = "./FantasqueSansMono-Regular.ttf";
5 13
6 14
int main(int argc, char *argv[]) {
7 15
	printf("hello, world!\n");
@ -41,13 +49,7 @@ int main(int argc, char *argv[]) {
41 49
42 50
	SDL_Surface *surface = SDL_GetWindowSurface(window);
43 51
44
	char *msg = "🐘";
45
46
	// thanks to https://stackoverflow.com/questions/22886500/how-to-render-text-in-sdl2 for some actually useful code here
47
	SDL_Color white = {255, 255, 255, 255};
48
	SDL_Color black = {0, 0, 0};
49
	SDL_Surface* text = TTF_RenderUTF8_Shaded(font, msg, white, black);
50
	SDL_BlitSurface(text, NULL, surface, NULL);
52
	char msg[100] = "howdy there, enby! 🐘                                          ";
51 53
52 54
	// monospace -> fixed width (duh)
53 55
	int advance = 0;
@ -56,14 +58,49 @@ int main(int argc, char *argv[]) {
56 58
		printf("advance '%c': %d\n", msg[i], advance);
57 59
	}
58 60
61
	SDL_StartTextInput();
62
63
	int pos = 0;
64
	int max_chars = MIN(surface->w / advance, sizeof(msg));
65
66
	SDL_bool quit = SDL_FALSE;
67
59 68
	SDL_Event event;
60
	while (1) {
61
		SDL_PollEvent(&event);
62
		if (event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) {
63
			printf("quit received\n");
64
			break;
69
	while (!quit) {
70
		while(SDL_PollEvent(&event)) {
71
			if (event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) {
72
				printf("quit received\n");
73
				quit = SDL_TRUE;
74
				break;
75
			}
76
77
			if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_BACKSPACE) {
78
				if (pos == 0) {
79
					pos = max_chars-1;
80
				} else {
81
					pos = (pos - 1) % (max_chars - 1);
82
				}
83
				msg[pos] = '_';
84
				printf("back to %d\n", pos);
85
				continue;
86
			}
87
88
			if (event.type == SDL_TEXTINPUT) {
89
				if (strlen(event.text.text) > 0) {
90
					printf("key: %s\n", event.text.text);
91
92
					msg[pos] = event.text.text[0];
93
					pos = (pos + 1) % (max_chars - 1);
94
				}
95
			}
65 96
		}
66 97
98
		// thanks to https://stackoverflow.com/questions/22886500/how-to-render-text-in-sdl2 for some actually useful code here
99
		SDL_Color white = {255, 255, 255, 255};
100
		SDL_Color black = {0, 0, 0};
101
		SDL_Surface* text = TTF_RenderUTF8_Shaded(font, msg, white, black);
102
		SDL_BlitSurface(text, NULL, surface, NULL);
103
67 104
		SDL_UpdateWindowSurface(window);
68 105
		SDL_Delay(16);
69 106
	}