shithub: olednews

ref: 8592776712b7d54043d044bda06380a58fb515cd
dir: /textimg.c/

View raw version
#include <u.h>
#include <libc.h>
#include <draw.h>
#include <memdraw.h>
#include <bio.h>

void
usage(void)
{
	sysfatal("usage: %s [ -f subfont ] text", argv0);
}

void
writeuncompressed(int fd, Memimage *m)
{
	char chanstr[32];
	int bpl, y, j;
	uchar *buf;

	if(chantostr(chanstr, m->chan) == nil)
		sysfatal("can't convert channel descriptor: %r");
	fprint(fd, "%11s %11d %11d %11d %11d ",
		chanstr, m->r.min.x, m->r.min.y, m->r.max.x, m->r.max.y);

	bpl = bytesperline(m->r, m->depth);
	buf = malloc(bpl+1);
	if(buf == nil)
		sysfatal("malloc failed: %r");
	for(y=m->r.min.y; y<m->r.max.y; y++){
		j = unloadmemimage(m, Rect(m->r.min.x, y, m->r.max.x, y+1), buf, bpl);
		if(j != bpl)
			sysfatal("image unload failed: %r");
		if(write(fd, buf, bpl) != bpl)
			sysfatal("write failed: %r");
	}
	free(buf);
}


void
main(int argc, char **argv)
{
	char *s;
	Memsubfont *f;
	Point p;
	char *path;
	int fd;
	Biobufhdr *in;

	s = "/lib/font/bit/vga/vga.0000-007F";
	f = nil;
	path = "/mnt/reform/kbdoled";
	in = Bfdopen(0, OREAD);

	ARGBEGIN{
	case 'f':
		s = EARGF(usage());
		break;
	case 'p':
		path = EARGF(usage());
		break;
	}ARGEND;

	if (memimageinit())
		sysfatal("memimageinit failed: %r");
	
	if (s)
		f = openmemsubfont(s);
	if (!f){
		fprint(2, "cannot load subfont. Falling back to default.\n");
		f = getmemdefont();
	}

	// Read text in - one OLED line width at a time
	//	2 lines on the OLED display
	// p.x = width of one char in pixels
	// 126 x 32 oled
	p = memsubfontwidth(f, "Q");
	if (p.x == 0)
		sysfatal("no length");

	int ncharspline;//, nlines;
	int h = 32;
	int w = 126;
	int y = 0;
	int i;
	int ms = 100;
	long n;
	ncharspline = w / p.x;
	//nlines = 2;	// i guess?
	char *buf;
	buf = calloc(ncharspline, sizeof (char));
	fprint(2, "ncharspline: %d\n", ncharspline);
	n = Bread(in, buf, ncharspline-1);
	if(n <= 0)
		sysfatal("no bread in the bread box");
	buf[n] = '\0';
	for(i = 0; i < n; i++)
		if(buf[i] == '\n' || buf[i] == '\r')
			buf[i] = ' ';

	for(;;){
		Memimage *img;
		//fprint(2, "buf str: %s\n", buf);

		fd = open(path, OWRITE);
		if(fd < 0){
			sysfatal("could not open kbdoled file → %r");
		}
		
		//img = allocmemimage(Rect(0, 0, p.x, f->height), RGB24);
		img = allocmemimage(Rect(0, 0, p.x*ncharspline, f->height), GREY1);
		if (!img)
			sysfatal("cannot allocate memimage: %r");
		memfillcolor(img, DWhite);
		
		memimagestring(img, Pt(0, 0), memblack, ZP, f, buf);
		writeuncompressed(fd, img);
	
		close(fd);
		//free(buf);
		if(y == 0)
			y = h/2;
		else
			y = 0;

		char c;
		c = Bgetc(in);
		if(c <= 0)
			break;
		if(c == '\n' || c == '\r')
			c = ' ';

		for(i = 0; i < n-1; i++)
			buf[i] = buf[i+1];
		buf[n-1] = c;
		//freememimage(img);

		sleep(ms);
	}
	free(buf);
}