Skip to content

Commit

Permalink
https://viewsourcecode.org/snaptoken/kilo/03.rawInputAndOutput.html#w…
Browse files Browse the repository at this point in the history
…indow-size-the-hard-way
  • Loading branch information
Gurrium committed Dec 19, 2022
1 parent 216b75e commit 22d1df4
Showing 1 changed file with 30 additions and 5 deletions.
35 changes: 30 additions & 5 deletions kilo.c
Expand Up @@ -4,6 +4,7 @@
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>

Expand All @@ -13,7 +14,13 @@

/*** data ***/

struct termios orig_termios;
struct editorConfig {
int screenrows;
int screencols;
struct termios orig_termios;
};

struct editorConfig E;

/*** terminal ***/

Expand All @@ -26,14 +33,15 @@ void die(const char *s) {
}

void disableRawMode() {
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios) == -1) die("tcsetattr");
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.orig_termios) == -1)
die("tcsetattr");
}

void enableRawMode() {
if (tcgetattr(STDERR_FILENO, &orig_termios) == -1) die("tcgetattr");
if (tcgetattr(STDERR_FILENO, &E.orig_termios) == -1) die("tcgetattr");
atexit(disableRawMode);

struct termios raw = orig_termios;
struct termios raw = E.orig_termios;
raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
raw.c_oflag &= ~(OPOST);
raw.c_cflag |= ~(CS8);
Expand All @@ -53,6 +61,18 @@ char editorReadKey() {
return c;
}

int getWindowSize(int *rows, int *cols) {
struct winsize ws;

if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) {
return -1;
} else {
*cols = ws.ws_col;
*rows = ws.ws_row;
return 0;
}
}

/*** input ***/
void editorProcessKeyPress() {
char c = editorReadKey();
Expand All @@ -71,7 +91,7 @@ void editorProcessKeyPress() {

void editorDrawRows() {
int y;
for (y = 0; y < 24; y++) {
for (y = 0; y < E.screenrows; y++) {
write(STDOUT_FILENO, "~\r\n", 3);
}
}
Expand All @@ -87,8 +107,13 @@ void editorRefreshScreen() {

/*** init ***/

void initEditor() {
if (getWindowSize(&E.screenrows, &E.screencols) == -1) die("getWindowSize");
}

int main() {
enableRawMode();
initEditor();

while (1) {
editorRefreshScreen();
Expand Down

0 comments on commit 22d1df4

Please sign in to comment.