git.y1.nz

lwl

Less with links.
download: http://git.y1.nz/archives/lwl.tar.gz
README | Files | Log | Refs

term.c

      1 
      2 #include <stdio.h>
      3 #include <termios.h>
      4 #include <unistd.h>
      5 #include <ctype.h>
      6 #include <stdlib.h> /* exit */
      7 
      8 #define RESPONSE_SIZE  10
      9 
     10 int
     11 query_cursor_position(FILE *tin, FILE *tout, int *x, int *y)
     12 {
     13 	int ch = 0;
     14 	int result;
     15 	struct termios original, changed;
     16 	char response[RESPONSE_SIZE] = "";
     17 	int index = 0;
     18 
     19 	/* set termios to avoid hanging for response */
     20 	result = tcgetattr(fileno(tin), &original);
     21 	if (result < 0) {
     22 		printf("Error getting termios" "\n");
     23 		exit(1);
     24 	}
     25 	changed = original;
     26 	changed.c_lflag &= ~(ICANON | ECHO);
     27 	changed.c_cc[VMIN] = 1;
     28 	changed.c_cc[VTIME] = 0;
     29 	result = tcsetattr(fileno(tin), TCSANOW, &changed);
     30 	if (result < 0) {
     31 		printf("Error getting termios" "\n");
     32 		exit(1);
     33 	}
     34 
     35 	/* query cursor position */
     36 	fprintf(tout, "\033[6n");
     37 	fflush(tout);
     38 
     39 	for (;;) {
     40 		ch = fgetc(tin);
     41 		if (ch == 'R' || ch == EOF || index >= RESPONSE_SIZE) break;
     42 		if (!isprint(ch)) continue;
     43 		response[index++] = ch;
     44 	}
     45 	response[index] = '\0';
     46 
     47 	/* no R at the end of the format */
     48 	result = sscanf(response, "[%d;%d", y, x);
     49 
     50 	result = tcsetattr(fileno(tin), TCSANOW, &original);
     51 	if (result < 0) {
     52 		printf("Error reset termios" "\n");
     53 		exit(1);
     54 	}
     55 	return 1; // result == 2;
     56 }
     57 
     58 int
     59 get_root_size(FILE *tin, FILE *tout, int *x, int *y)
     60 {
     61 	int x0, y0;
     62 	int result;
     63 	result = query_cursor_position(tin, tout, &x0, &y0);
     64 	if (!result) {
     65 		fprintf(stderr, "FAILURE!!" "\n");
     66 		return 0;
     67 	}
     68 
     69 	/* move down/right until end of screen */
     70 	fprintf(tout, "\033[9999B" "\033[9999C");
     71 	fflush(tout);
     72 	result = query_cursor_position(tin, tout, x, y);
     73 
     74 	/* move cursor back to original position */
     75 	fprintf(tout, "\033[%d;%dH", y0, x0);
     76 	fflush(tout);
     77 
     78 	return result;
     79 }

This webpage is intended to be an accessible preview of this repository. To get a fuller picture, clone it and use the git CLI.