Archived
1
Fork 0

Add support to handle terminal resizing

Got stuck on a bug for a while, fix was to check for errors when using
system calls. Lesson learned.
This commit is contained in:
Hadeed 2023-09-26 06:42:36 +05:00
parent b755aad0b4
commit c10f4a243b
4 changed files with 34 additions and 9 deletions

View file

@ -4,9 +4,9 @@
#include <stdbool.h>
#include <stddef.h>
#include "erow.h"
#include "utils.h"
struct erow;
struct buffer {
char *filename;

View file

@ -1,8 +1,7 @@
#ifndef CURSOR_H
#define CURSOR_H
#include "buffer.h"
struct buffer;
void cursor_move(struct buffer *buffer, int dx, int dy);
#endif // CURSOR_H

View file

@ -1,4 +1,7 @@
#define _POSIX_C_SOURCE 199309L
#include <ctype.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
@ -15,6 +18,7 @@
#include "utils.h"
void editor_init(char *filename);
void editor_resize();
struct editor_state E;
@ -39,7 +43,6 @@ void editor_init(char *filename) {
if (terminal_get_win_size(&E.screenrows, &E.screencols) == -1)
die("term_get_win_size");
E.screenrows -= 2;
E.quit_times = 3;
E.current_buf = buffer_create();
@ -48,6 +51,10 @@ void editor_init(char *filename) {
editor_set_message("Welcome to kilo! | CTRL-Q: Quit | CTRL-S: SAVE");
terminal_clear();
struct sigaction sa;
sa.sa_handler = editor_resize;
sigaction(SIGWINCH, &sa, NULL);
}
void editor_set_message(const char *fmt, ...) {
@ -112,3 +119,10 @@ success:
editor_set_message("");
return buf;
}
void editor_resize() {
if (terminal_get_win_size(&E.screenrows, &E.screencols) == -1)
die("term_get_win_size");
ui_draw_screen();
}

View file

@ -48,7 +48,7 @@ ERRCODE terminal_get_win_size(int *row, int *col) {
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 && ws.ws_col != 0) {
*row = ws.ws_row;
*row = ws.ws_row - 2;
*col = ws.ws_col;
return 0;
@ -56,7 +56,14 @@ ERRCODE terminal_get_win_size(int *row, int *col) {
// Fallback implementation
if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12) return -1;
return terminal_get_cursor_pos(row, col);
int _row, _col;
ERRCODE get_err = terminal_get_cursor_pos(&_row, &_col);
if (get_err == 0) {
*row = _row - 2;
*col = _col;
}
return get_err;
}
}
@ -90,8 +97,13 @@ ERRCODE terminal_set_cursor_pos(int row, int col) {
KEY terminal_read_key(void) {
char c;
int n;
while (read(STDIN_FILENO, &c, 1) == 0);
ssize_t read_return = 0;
while (read_return == 0)
read_return = read(STDIN_FILENO, &c, 1);
if (read_return == -1)
return NOP;
if (c == '\x1b') {
char buf[8] = { '\0' };
@ -105,7 +117,7 @@ KEY terminal_read_key(void) {
char escape_char;
int escape_int;
n = 0;
int n = 0;
sscanf(buf, "[%c%n", &escape_char, &n);
if (n > 0) {
switch (escape_char) {