Skip to content

Commit

Permalink
console: Read stdin as console input
Browse files Browse the repository at this point in the history
  • Loading branch information
mrannanj committed Nov 28, 2024
1 parent c2df47c commit 2d5cead
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
29 changes: 28 additions & 1 deletion src/console/console.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@
#include "game/gui/menu_background.h"
#include "game/utils/settings.h"
#include "utils/allocator.h"
#include "utils/log.h"
#include "video/video.h"
#include <stdio.h>

#if !defined(WIN32) && !defined(_WIN32)
#include <fcntl.h>
#include <unistd.h>
#endif

#define HISTORY_MAX 100
#define BUFFER_INC(b) (((b) + 1) % sizeof(con->output))
#define BUFFER_DEC(b) (((b) + sizeof(con->output) - 1) % sizeof(con->output))
Expand Down Expand Up @@ -223,6 +229,11 @@ bool console_init(void) {
menu_transparent_bg_create(&con->background1, 322, 101);
menu_background_create(&con->background2, 322, 101);

// Read from stdin needs to be nonblocking
#if !defined(WIN32) && !defined(_WIN32)
fcntl(0, F_SETFL, fcntl(0, F_GETFL) | O_NONBLOCK);
#endif

console_init_cmd();

// Print the header
Expand Down Expand Up @@ -333,7 +344,23 @@ void console_render(void) {
}
}

void console_tick(void) {
static size_t get_stdin_line(char *line, size_t size) {
#if !defined(WIN32) && !defined(_WIN32)
ssize_t n = read(0, line, size);
if(n > 0) {
line[n - 1] = '\0';
return (size_t)(n - 1);
}
#endif
return 0;
}

void console_tick(game_state *gs) {
if(get_stdin_line(con->input, sizeof(con->input)) > 0) {
DEBUG("Console line from stdin: %s", con->input, strlen(con->input));
console_handle_line(gs);
con->input[0] = '\0';
}
if(con->is_open && con->y_pos < 100) {
con->y_pos += 4;
if(settings_get()->video.instant_console) {
Expand Down
2 changes: 1 addition & 1 deletion src/console/console.h
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ bool console_init(void);
void console_close(void);
void console_event(game_state *scene, SDL_Event *event);
void console_render(void);
void console_tick(void);
void console_tick(game_state *gs);
void console_add_cmd(const char *name, command_func func, const char *doc);
void console_remove_cmd(const char *name);

Expand Down
2 changes: 1 addition & 1 deletion src/engine.c
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ void engine_run(engine_init_flags *init_flags) {
has_static = static_wait > STATIC_TICKS;
if(has_static) {
game_state_static_tick(gs, false);
console_tick();
console_tick(gs);
static_wait -= STATIC_TICKS;
}

Expand Down

0 comments on commit 2d5cead

Please sign in to comment.