changeset 419:af0cca0aba9d

Quick and dirty terminal_size() and yesno() functions, both of which need to be improved.
author Rob Landley <rob@landley.net>
date Thu, 02 Feb 2012 07:27:35 -0600
parents 9be513853e6b
children eda61bcf575a
files lib/lib.c lib/lib.h
diffstat 2 files changed, 53 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/lib/lib.c	Thu Feb 02 07:27:05 2012 -0600
+++ b/lib/lib.c	Thu Feb 02 07:27:35 2012 -0600
@@ -174,7 +174,8 @@
 {
 	toy_exec(argv);
 	execvp(argv[0], argv);
-	error_exit("No %s", argv[0]);
+
+	perror_exit("exec %s", argv[0]);
 }
 
 void xaccess(char *path, int flags)
@@ -756,3 +757,51 @@
 		crc_table[i] = c;
 	}
 }
+
+// Quick and dirty query size of terminal, doesn't do ANSI probe fallback.
+// set *x=0 and *y=0 before calling to detect failure to set either, or
+// x=80 y=25 to provide defaults
+
+void terminal_size(unsigned *x, unsigned *y)
+{
+	struct winsize ws;
+	int i;
+
+	//memset(&ws, 0, sizeof(ws));
+	for (i=0; i<3; i++) {
+		if (ioctl(i, TIOCGWINSZ, &ws)) continue;
+		if (x) *x = ws.ws_col;
+		if (y) *y = ws.ws_row;
+	}
+	if (x) {
+		char *s = getenv("COLUMNS");
+
+		i = s ? atoi(s) : 0;
+		if (i>0) *x = i;
+	}
+	if (y) {
+		char *s = getenv("ROWS");
+
+		i = s ? atoi(s) : 0;
+		if (i>0) *y = i;
+	}
+}
+
+// This should use a raw tty, fixit later.
+int yesno(int def)
+{
+	char buf[16];
+	int i;
+
+	for (i=0; i<3 && !isatty(i); i++);
+	if (i == 3) return 1;
+
+	sprintf(buf, "(%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
+	write(i, buf, 6);
+	while (read(i, buf, 1)) {
+		if (isspace(*buf)) break;
+		if (tolower(*buf) == 'y') return 1;
+		if (tolower(*buf) == 'n') return 0;
+	}
+	return def;
+}
--- a/lib/lib.h	Thu Feb 02 07:27:05 2012 -0600
+++ b/lib/lib.h	Thu Feb 02 07:27:35 2012 -0600
@@ -108,6 +108,9 @@
 void delete_tempfile(int fdin, int fdout, char **tempname);
 void replace_tempfile(int fdin, int fdout, char **tempname);
 void crc_init(unsigned int *crc_table, int little_endian);
+void terminal_size(unsigned *x, unsigned *y);
+int yesno(int def);
+
 
 // getmountlist.c
 struct mtab_list {