Files
tcp-chat/src/term.c
2025-08-10 21:39:51 +03:00

96 lines
2.3 KiB
C

#include "term.h"
#include <unistd.h>
#include IFWIN("windows.h", "sys/ioctl.h")
bool term_init(){
#if defined(_WIN64) || defined(_WIN32)
DWORD mode=0;
HANDLE h;
// configure stdout
h = GetStdHandle(STD_OUTPUT_HANDLE);
if(h == INVALID_HANDLE_VALUE)
return false;
GetConsoleMode(h, &mode);
mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
mode |= ENABLE_PROCESSED_OUTPUT;
SetConsoleMode(h, mode);
// configure stdin
h = GetStdHandle(STD_INPUT_HANDLE);
if(h == INVALID_HANDLE_VALUE)
return false;
GetConsoleMode(h, &mode);
mode |= ENABLE_VIRTUAL_TERMINAL_INPUT;
mode |= ENABLE_PROCESSED_INPUT;
SetConsoleMode(h, mode);
#endif
return true;
}
int getenv_int(const char* var_name){
char* str=getenv(var_name);
if(str==NULL)
return -1;
return strtol(str, NULL, 0);
}
bool term_getSize(TerminalSize* out) {
#if defined(_WIN64) || defined(_WIN32)
// helps when STD_OUT is redirected to a file
HANDLE hConsoleErr = GetStdHandle(STD_ERROR_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO consoleInfo;
if(!GetConsoleScreenBufferInfo(hConsoleErr, &consoleInfo))
return false;
out->cols = consoleInfo.srWindow.Right - consoleInfo.srWindow.Left + 1;
out->rows = consoleInfo.srWindow.Bottom - consoleInfo.srWindow.Top + 1;
#else
struct winsize ws = {0};
// try to get terminal size from stdin, stdout, stderr
if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws)==0 ||
ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws)==0 ||
ioctl(STDERR_FILENO, TIOCGWINSZ, &ws)==0 ){
out->cols=ws.ws_col;
out->rows=ws.ws_row;
}
// try to get size from environtent variables
else {
out->cols=getenv_int("COLUMNS");
out->rows=getenv_int("LINES");
}
#endif
return out->cols > 0 && out->rows > 0;
}
/*
Most of escape sequences can be found there
https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797
*/
void term_resetCursor() {
printf("\e[H");
}
void term_resetColors() {
printf("\e[0m");
}
void term_clear() {
printf("\e[0m\e[H\e[2J");
}
void term_cursorMove(u16 row, u16 column) {
printf("\e[%u;%uH",row,column);
}
void term_cursorHide() {
printf("\e[?25l");
}
void term_cursorShow() {
printf("\e[?25h");
}