Blob


1 #include <u.h>
2 #include <libc.h>
3 #include <draw.h>
5 Image *
6 creadimage(Display *d, int fd, int dolock)
7 {
8 char hdr[5*12+1];
9 Rectangle r;
10 int m, nb, miny, maxy, new, ldepth, ncblock;
11 uchar *buf, *a;
12 Image *i;
13 u32int chan;
15 if(readn(fd, hdr, 5*12) != 5*12)
16 return nil;
18 /*
19 * distinguish new channel descriptor from old ldepth.
20 * channel descriptors have letters as well as numbers,
21 * while ldepths are a single digit formatted as %-11d.
22 */
23 new = 0;
24 for(m=0; m<10; m++){
25 if(hdr[m] != ' '){
26 new = 1;
27 break;
28 }
29 }
30 if(hdr[11] != ' '){
31 werrstr("creadimage: bad format");
32 return nil;
33 }
34 if(new){
35 hdr[11] = '\0';
36 if((chan = strtochan(hdr)) == 0){
37 werrstr("creadimage: bad channel string %s", hdr);
38 return nil;
39 }
40 }else{
41 ldepth = ((int)hdr[10])-'0';
42 if(ldepth<0 || ldepth>3){
43 werrstr("creadimage: bad ldepth %d", ldepth);
44 return nil;
45 }
46 chan = drawld2chan[ldepth];
47 }
48 r.min.x=atoi(hdr+1*12);
49 r.min.y=atoi(hdr+2*12);
50 r.max.x=atoi(hdr+3*12);
51 r.max.y=atoi(hdr+4*12);
52 if(r.min.x>r.max.x || r.min.y>r.max.y){
53 werrstr("creadimage: bad rectangle");
54 return nil;
55 }
57 if(dolock)
58 lockdisplay(d);
59 i = allocimage(d, r, chan, 0, 0);
60 if(dolock)
61 unlockdisplay(d);
62 if(i == nil)
63 return nil;
64 ncblock = _compblocksize(r, i->depth);
65 buf = malloc(ncblock);
66 if(buf == nil)
67 goto Errout;
68 miny = r.min.y;
69 while(miny != r.max.y){
70 if(readn(fd, hdr, 2*12) != 2*12){
71 Errout:
72 if(dolock)
73 lockdisplay(d);
74 Erroutlock:
75 freeimage(i);
76 if(dolock)
77 unlockdisplay(d);
78 free(buf);
79 return nil;
80 }
81 maxy = atoi(hdr+0*12);
82 nb = atoi(hdr+1*12);
83 if(maxy<=miny || r.max.y<maxy){
84 werrstr("creadimage: bad maxy %d", maxy);
85 goto Errout;
86 }
87 if(nb<=0 || ncblock<nb){
88 werrstr("creadimage: bad count %d", nb);
89 goto Errout;
90 }
91 if(readn(fd, buf, nb)!=nb)
92 goto Errout;
93 if(dolock)
94 lockdisplay(d);
95 a = bufimage(i->display, 21+nb);
96 if(a == nil)
97 goto Erroutlock;
98 a[0] = 'Y';
99 BPLONG(a+1, i->id);
100 BPLONG(a+5, r.min.x);
101 BPLONG(a+9, miny);
102 BPLONG(a+13, r.max.x);
103 BPLONG(a+17, maxy);
104 if(!new) /* old image: flip the data bits */
105 _twiddlecompressed(buf, nb);
106 memmove(a+21, buf, nb);
107 if(dolock)
108 unlockdisplay(d);
109 miny = maxy;
111 free(buf);
112 return i;