#include #include #include #include #include "environment.hpp" #ifndef STDOUT_FILENO #define STDOUT_FILENO 1 #endif #ifndef STDIN_FILENO #define STDIN_FILENO 0 #endif int getWindowSize(int *rows, int *cols) { struct winsize ws; // Getting window size thanks to ioctl into the given // winsize struct. if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { return -1; } else { *cols = ws.ws_col; *rows = ws.ws_row; return 0; } } static struct termios orig_termios; static void disableRawMode() { tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios); } int enableRawMode(void) { // Save original terminal state into orig_termios. if (tcgetattr(STDIN_FILENO, &orig_termios) == -1) return 1; // At exit, restore the original state. atexit(disableRawMode); // Modify the original state to enter in raw mode. struct termios raw = orig_termios; // This disables Ctrl-M, Ctrl-S and Ctrl-Q commands. // (BRKINT, INPCK and ISTRIP are not estrictly mandatory, // but it is recommended to turn them off in case any // system needs it). raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); // Turning off all output processing (\r\n). raw.c_oflag &= ~(OPOST); // Setting character size to 8 bits per byte (it should be // like that on most systems, but whatever). raw.c_cflag |= (CS8); // Using NOT operator on ECHO | ICANON | IEXTEN | ISIG and // then bitwise-AND them with flags field in order to // force c_lflag 4th bit to become 0. This disables // chars being printed (ECHO) and let us turn off // canonical mode in order to read input byte-by-byte // instead of line-by-line (ICANON), ISIG disables // Ctrl-C command and IEXTEN the Ctrl-V one. raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); // read() function now returns as soon as there is any // input to be read. raw.c_cc[VMIN] = 0; // Forcing read() function to return every 1/10 of a // second if there is nothing to read. raw.c_cc[VTIME] = 1; // consoleBufferOpen(); if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) return 1; return 0; } int writeTerm(const char *buf, int length) { return write(STDOUT_FILENO, buf, length); } int readTerm(char *buf, int length) { return read(STDIN_FILENO, buf, length); }