shithub: fontsel

Download patch

ref: 3f4f25323d5c8a10d595c8c9dc483479fe42d61f
parent: e8191594a857420fec9ea9585b3d4822a2dc4676
author: Sigrid Haflínudóttir <[email protected]>
date: Fri May 29 13:37:08 EDT 2020

add custom text loading

--- a/README.md
+++ b/README.md
@@ -19,6 +19,5 @@
 `-` and `+` cycle through fonts of a specific font dir, or change the
 size of the font if it's a TTF one.
 
-## TODO
-
- * Custom font paths
+Displayed text can be loaded from a file: `fontsel FILE`, where `FILE`
+can be `-` to read from stdin.
--- a/fontsel.c
+++ b/fontsel.c
@@ -2,6 +2,7 @@
 #include <libc.h>
 #include <thread.h>
 #include <draw.h>
+#include <bio.h>
 #include <keyboard.h>
 #include <mouse.h>
 
@@ -32,7 +33,7 @@
 	Ttfdefsz = 16,
 };
 
-static char *text[] = {
+static char *textdef[] = {
 	"Cwm fjord bank glyphs vext quiz!",
 	"Gud hjälpe Zorns mö qvickt få byxa?",
 	"Разъярённый чтец эгоистично бьёт пятью",
@@ -46,8 +47,11 @@
 	"    fprint(2, \"# %c\\n\", t[0]);",
 	"    return dostuff(s) || dot(t, n);",
 	"}",
+	nil
 };
 
+static char **text = textdef;
+
 static char *prefixes[] = {
 	"/lib/font/bit",
 	"/lib/font/ttf",
@@ -75,14 +79,14 @@
 		string(screen, p, display->black, ZP, font, lasterr);
 	}else{
 		maxw = 0;
-		for(i = 0; i < nelem(text); i++){
+		for(i = 0; text[i] != nil; i++){
 			if((w = stringwidth(f, text[i])) > maxw)
 				maxw = w;
 		}
 		p.x += Dx(screen->r)/2 - maxw/2;
-		p.y += Dy(screen->r)/2 - nelem(text)*f->height/2;
+		p.y += Dy(screen->r)/2 - i*f->height/2;
 
-		for(i = 0; i < nelem(text); i++){
+		for(i = 0; text[i] != nil; i++){
 			string(screen, p, display->black, ZP, f, text[i]);
 			p.y += f->height;
 		}
@@ -170,6 +174,7 @@
 	}
 	if((n = dirreadall(f, &d)) < 1){
 		fprint(2, "%s: no fonts\n", t);
+		close(f);
 		return;
 	}
 	for(i = 0; i < n; i++){
@@ -219,6 +224,33 @@
 	return i < cdir->nfonts ? cdir->fonts[i] : nil;
 }
 
+static void
+usage(void)
+{
+	print("usage: %s [FILE]\n", argv0);
+	threadexitsall("usage");
+}
+
+static void
+loadtext(int f)
+{
+	Biobuf b;
+	int i;
+
+	if(f < 0 || Binit(&b, f, OREAD) != 0)
+		sysfatal("loadtext: %r");
+
+	text = nil;
+	for(i = 0; i < 256; i++){
+		if((text = realloc(text, (i+1)*sizeof(char*))) == nil)
+			sysfatal("memory");
+		if((text[i] = Brdstr(&b, '\n', 1)) == nil)
+			break;
+	}
+
+	close(f);
+}
+
 void
 threadmain(int argc, char **argv)
 {
@@ -235,7 +267,16 @@
 	};
 	int n;
 
-	USED(argc); USED(argv);
+	ARGBEGIN{
+	default:
+		usage();
+		break;
+	}ARGEND;
+
+	if(argc > 1)
+		usage();
+	else if(argc == 1)
+		loadtext(strcmp(argv[0], "-") == 0 ? 0 : open(argv[1], OREAD));
 
 	for(n = 0; n < nelem(prefixes); n++)
 		findfonts(prefixes[n]);