Get window size
This commit is contained in:
parent
2ded534ff7
commit
9d5d4ea8c5
1 changed files with 37 additions and 12 deletions
47
kilo.c
47
kilo.c
|
@ -1,30 +1,34 @@
|
|||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <termios.h>
|
||||
#include <unistd.h>
|
||||
|
||||
void enable_raw_mode();
|
||||
void disable_raw_mode();
|
||||
int get_window_size(int *, int *);
|
||||
|
||||
void editor_init();
|
||||
void editor_redraw_screen();
|
||||
void editor_clear_screen();
|
||||
void editor_draw_rows();
|
||||
void editor_process_key();
|
||||
|
||||
void die(const char *s);
|
||||
void die(const char *);
|
||||
|
||||
#define CTRL_KEY(key) ((key) & 0x1f)
|
||||
|
||||
struct {
|
||||
struct termios orig_termios;
|
||||
int rows;
|
||||
int cols;
|
||||
} E;
|
||||
|
||||
int main() {
|
||||
if (!isatty(STDIN_FILENO)) {
|
||||
printf("kilo only supports a terminal at standard in. Exiting.");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
editor_init();
|
||||
enable_raw_mode();
|
||||
|
||||
while (1) {
|
||||
editor_redraw_screen();
|
||||
editor_process_key();
|
||||
|
@ -34,20 +38,42 @@ int main() {
|
|||
}
|
||||
|
||||
void enable_raw_mode() {
|
||||
if (tcgetattr(STDIN_FILENO, &orig_termios) == -1) die("tcgetattr");
|
||||
if (tcgetattr(STDIN_FILENO, &E.orig_termios) == -1) die("tcgetattr");
|
||||
atexit(disable_raw_mode);
|
||||
|
||||
struct termios raw = orig_termios;
|
||||
struct termios raw = E.orig_termios;
|
||||
cfmakeraw(&raw);
|
||||
|
||||
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr");
|
||||
}
|
||||
|
||||
void disable_raw_mode() {
|
||||
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios) == -1)
|
||||
if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.orig_termios) == -1)
|
||||
die("tcsetattr");
|
||||
}
|
||||
|
||||
int get_window_size(int *rows, int *cols) {
|
||||
struct winsize ws;
|
||||
|
||||
if (ioctl(STDIN_FILENO, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0) {
|
||||
*rows = ws.ws_row;
|
||||
*cols = ws.ws_col;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
void editor_init() {
|
||||
if (!isatty(STDIN_FILENO)) {
|
||||
printf("kilo only supports a terminal at standard in. Exiting.");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (get_window_size(&E.rows, &E.cols) == -1) die("get_window_size");
|
||||
}
|
||||
|
||||
void editor_redraw_screen() {
|
||||
editor_clear_screen();
|
||||
|
||||
|
@ -62,8 +88,7 @@ void editor_clear_screen() {
|
|||
}
|
||||
|
||||
void editor_draw_rows() {
|
||||
int rows = 24;
|
||||
for (int y = 0; y < rows - 1; y++)
|
||||
for (int y = 0; y < E.rows - 1; y++)
|
||||
write(STDIN_FILENO, "~\r\n", 3);
|
||||
write(STDIN_FILENO, "~", 1);
|
||||
}
|
||||
|
|
Reference in a new issue