xref: /plan9/sys/src/libdraw/unloadimage.c (revision 7dd7cddf99dd7472612f1413b4da293630e6b1bc)
1 #include <u.h>
2 #include <libc.h>
3 #include <draw.h>
4 
5 int
unloadimage(Image * i,Rectangle r,uchar * data,int ndata)6 unloadimage(Image *i, Rectangle r, uchar *data, int ndata)
7 {
8 	int bpl, n, ntot, dy;
9 	uchar *a;
10 	Display *d;
11 
12 	if(!rectinrect(r, i->r)){
13 		werrstr("unloadimage: bad rectangle");
14 		return -1;
15 	}
16 	bpl = bytesperline(r, i->depth);
17 	if(ndata < bpl*Dy(r)){
18 		werrstr("unloadimage: buffer too small");
19 		return -1;
20 	}
21 
22 	d = i->display;
23 	flushimage(d, 0);	/* make sure subsequent flush is for us only */
24 	ntot = 0;
25 	while(r.min.y < r.max.y){
26 		a = bufimage(d, 1+4+4*4);
27 		if(a == 0){
28 			werrstr("unloadimage: %r");
29 			return -1;
30 		}
31 		dy = 8000/bpl;
32 		if(dy <= 0){
33 			werrstr("unloadimage: image too wide");
34 			return -1;
35 		}
36 		if(dy > Dy(r))
37 			dy = Dy(r);
38 		a[0] = 'r';
39 		BPLONG(a+1, i->id);
40 		BPLONG(a+5, r.min.x);
41 		BPLONG(a+9, r.min.y);
42 		BPLONG(a+13, r.max.x);
43 		BPLONG(a+17, r.min.y+dy);
44 		if(flushimage(d, 0) < 0)
45 			return -1;
46 		n = read(d->fd, data+ntot, ndata-ntot);
47 		if(n < 0)
48 			return n;
49 		ntot += n;
50 		r.min.y += dy;
51 	}
52 	return ntot;
53 }
54