Browse code

Switched from non-blocking read to thread and custom SDL event

Andrew Alderwick authored on 28/06/2021 20:46:50
Showing 2 changed files
... ...
@@ -104,7 +104,7 @@ start(Uxn *u)
104 104
 {
105 105
 	if(!evaluxn(u, PAGE_PROGRAM))
106 106
 		return error("Reset", "Failed");
107
-	while(mempeek16(devconsole->dat, 0))
107
+	if(mempeek16(devconsole->dat, 0))
108 108
 		while(read(0, &devconsole->dat[0x2], 1) > 0)
109 109
 			evaluxn(u, mempeek16(devconsole->dat, 0));
110 110
 	return 1;
... ...
@@ -1,7 +1,6 @@
1 1
 #include <stdio.h>
2 2
 #include <unistd.h>
3 3
 #include <time.h>
4
-#include <fcntl.h>
5 4
 #include "uxn.h"
6 5
 
7 6
 #pragma GCC diagnostic push
... ...
@@ -30,6 +29,7 @@ static SDL_Rect gRect;
30 29
 static Ppu ppu;
31 30
 static Apu apu[POLYPHONY];
32 31
 static Device *devscreen, *devmouse, *devctrl, *devaudio0, *devconsole;
32
+static Uint32 stdin_event;
33 33
 
34 34
 #define PAD 16
35 35
 
... ...
@@ -329,6 +329,17 @@ nil_talk(Device *d, Uint8 b0, Uint8 w)
329 329
 
330 330
 #pragma mark - Generics
331 331
 
332
+static int
333
+in_reader(void *p)
334
+{
335
+	SDL_Event event;
336
+	event.type = stdin_event;
337
+	while(read(0, &event.cbutton.button, 1) > 0)
338
+		SDL_PushEvent(&event);
339
+	return 0;
340
+	(void)p;
341
+}
342
+
332 343
 static int
333 344
 start(Uxn *u)
334 345
 {
... ...
@@ -367,10 +378,13 @@ start(Uxn *u)
367 378
 				if(event.window.event == SDL_WINDOWEVENT_EXPOSED)
368 379
 					redraw(u);
369 380
 				break;
381
+			default:
382
+				if(event.type == stdin_event) {
383
+					devconsole->dat[0x2] = event.cbutton.button;
384
+					evaluxn(u, mempeek16(devconsole->dat, 0));
385
+				}
370 386
 			}
371 387
 		}
372
-		while(read(0, &devconsole->dat[0x2], 1) > 0)
373
-			evaluxn(u, mempeek16(devconsole->dat, 0));
374 388
 		evaluxn(u, mempeek16(devscreen->dat, 0));
375 389
 		if(reqdraw)
376 390
 			redraw(u);
... ...
@@ -388,8 +402,8 @@ main(int argc, char **argv)
388 402
 	Uxn u;
389 403
 	zoom = 2;
390 404
 
391
-	/* set stdin nonblocking */
392
-	fcntl(0, F_SETFL, fcntl(0, F_GETFL, 0) | O_NONBLOCK);
405
+	stdin_event = SDL_RegisterEvents(1);
406
+	SDL_CreateThread(in_reader, "stdin", NULL);
393 407
 
394 408
 	if(argc < 2)
395 409
 		return error("Input", "Missing");