chiark / gitweb /
Much better error handling.
[ypp-sc-tools.db-test.git] / pctb / structure.c
1 /*
2   */
3
4 #include "structure.h"
5
6 static CanonImage *cim;
7
8 static inline char get(int x, int y) { return cim->d[y * cim->w + x]; }
9 static inline char get_p(Point p) { return get(p.x,p.y); }
10
11 #define START_MAIN {200,200}
12 #define MIN_COLUMNS         6
13 #define INTERESTING_COLUMNS 7
14 #define TEXT_COLUMNS        2
15 #define MAX_COLUMNS         7
16
17 static Rect mainr = { START_MAIN,START_MAIN };
18 static int commbasey, comminty;
19 static int colrightx[INTERESTING_COLUMNS];
20 static int text_h=-1, columns=-1;
21 static OcrReader *rd;
22
23 const CanonColourInfo canoncolourinfos[]= {
24   { 0x475A5E, '*' }, /* edge */
25   { 0x2C5F7A, '*' }, /* edge just under box heading shadow */
26   { 0x7D9094, '+' }, /* interbox */
27
28   { 0xBDC5BF, ' ' }, /* background - pale  Sugar cane, etc. */
29   { 0xADB5AF, ' ' }, /* background - dark                   */
30   { 0xC7E1C3, ' ' }, /* background - pale  Swill, etc.      */
31   { 0xB5CFB1, ' ' }, /* background - dark                   */
32   { 0xD6CEB0, ' ' }, /* background - pale  Madder, etc.     */
33   { 0xC8C0A2, ' ' }, /* background - dark                   */
34   { 0xE0E1D3, ' ' }, /* background - pale  Lorandite, etc.  */
35   { 0xD0D1C3, ' ' }, /* background - dark                   */
36   { 0xE5E6C1, ' ' }, /* background - pale  Cloth            */
37   { 0xD7D8B3, ' ' }, /* background - dark                   */
38   { 0xEDDED9, ' ' }, /* background - pale  Dye              */
39   { 0xDACBC6, ' ' }, /* background - dark                   */
40   { 0xD3DEDF, ' ' }, /* background - pale  Paint            */
41   { 0xC5D0D1, ' ' }, /* background - dark                   */
42   { 0xDCD1CF, ' ' }, /* background - pale  Enamel           */
43   { 0xCEC3C1, ' ' }, /* background - dark                   */
44   { 0xF3F6F5, ' ' }, /* background - pale  fruit            */
45   { 0xE2E7E5, ' ' }, /* background - dark                   */
46
47   { 0x000000, 'o' }, /* foreground */
48   { 0xD4B356, ' ' }, /* background (cursor) */
49   { 0xFFFFFF, 'o' }, /* foreground (cursor) */
50
51   { 0x5B93BF, '_' }, /* selector dropdown background */
52   { 0xD7C94F, 'X' }, /* selector dropdown foreground */
53   { 0,0 }
54 };
55
56
57 static void mustfail1(const char *file, int line, const char *what) {
58   fprintf(stderr,
59           "\n\n"
60           "Unable to figure out contents YPP client display.\n"
61           " Check that your client is logged in has the correct display.\n"
62           " If that isn't the problem, please report this as a fault.\n\n"
63           "Technical details:"
64           " %s:%d: requirement failed: %s\n",
65           file, line, what);
66 }
67 static void mustfail2(void) NORET;
68 static void mustfail2(void) {
69   fprintf(stderr, "\n\nGiving up.\n");
70   exit(8);
71 }
72
73 #define MUST(x, ifnot) do{                      \
74     if (!(x)) {                                 \
75       mustfail1(__FILE__,__LINE__,#x);          \
76       ifnot;                                    \
77       mustfail2();                              \
78     }                                           \
79   }while(0)
80
81 #define MP(v) fprintf(stderr," %s=%d,%d",#v,(v).x,(v).y)
82 #define MI(v) fprintf(stderr," %s=%d",   #v,(v))
83 #define MC(v) fprintf(stderr," %s='%c'", #v,(v))
84 #define MS(v) fprintf(stderr," %s=\"%s\"", #v,(v))
85 #define MSB(v) fprintf(stderr," %s", (v))
86 #define MR(v) fprintf(stderr," %s=%d,%d..%d,%d",\
87                       #v,(v).tl.x,(v).tl.y,(v).br.x,(v).br.y)
88
89
90 static void require_rectangle(int tlx, int tly, int brx, int bry,
91                               const char *ok) {
92   Point p;
93   for (p.x=tlx; p.x<=brx; p.x++)
94     for (p.y=tly; p.y<=bry; p.y++) {
95       int c= get_p(p);
96       MUST( strchr(ok,c), ({
97              Rect rm={{tlx,tly},{brx,bry}};
98              MR(rm);MP(p);MS(ok);
99       }));
100     }
101 }
102 static void require_rectangle_r(Rect rr, const char *ok) {
103   require_rectangle(rr.tl.x,rr.tl.y, rr.br.x,rr.br.y, ok);
104 }
105
106 static void debug_rect(const char *what, int whati, Rect rr) {
107   if (!DEBUGP(rect)) return;
108   int y,w;
109   fprintf(debug, "%s %d: %d,%d..%d,%d:\n", what, whati,
110           rr.tl.x,rr.tl.y, rr.br.x,rr.br.y);
111   w= rr.br.x - rr.tl.x + 1;
112   for (y=rr.tl.y; y<=rr.br.y; y++) {
113     fprintf(debug, "%4d%*s|", y, rr.tl.x,"");
114     fwrite(cim->d + y*cim->w + rr.tl.x, 1, w, debug);
115     fputc('|',debug);
116     fputc('\n',debug);
117   }
118   debug_flush();
119 }
120
121 #define WALK_UNTIL(point,coord,increm,last,edge)                        \
122   for (;;) {                                                            \
123     if ((point).coord == (last)+(increm)) break;                        \
124     if (get_p((point)) == (edge)) { (point).coord -= (increm); break; } \
125     (point).coord += (increm);                                          \
126   }
127
128 #define WALK_UNTIL_MUST(point,coord,increm,last,edge)   \
129   do {                                                  \
130     WALK_UNTIL(point,coord,increm,last,edge);           \
131     MUST( (point).coord != (last)+(increm),             \
132           MP(point); MI(increm); MI(last); MC(edge);    \
133           );                                            \
134   }while(0)
135
136 void find_structure(CanonImage *im) {
137   cim= im;
138   
139   Rect whole = { {0,0}, {cim->w-1,cim->h-1} };
140
141   WALK_UNTIL_MUST(mainr.tl, x,-1, whole.tl.x, '*');
142   WALK_UNTIL_MUST(mainr.tl, y,-1, whole.tl.y, '*');
143   WALK_UNTIL_MUST(mainr.br, x,+1, whole.br.x, '*');
144   WALK_UNTIL_MUST(mainr.br, y,+1, whole.br.y, '*');
145
146   require_rectangle(mainr.tl.x-1, mainr.tl.y, mainr.tl.x-1, mainr.br.y, "*");
147   require_rectangle(mainr.br.x+1, mainr.tl.y, mainr.br.x+1, mainr.br.y, "*");
148   require_rectangle(mainr.tl.x, mainr.tl.y-1, mainr.br.x, mainr.tl.y-1, "*");
149   require_rectangle(mainr.tl.x, mainr.br.y+1, mainr.br.x, mainr.br.y+1, "*");
150
151 #define CHECK_STRIP_BORDER(tlbr,xy,increm)      \
152   do {                                          \
153     Point csb_p;                                \
154     Rect csb_r;                                 \
155     csb_p= mainr.tl;                            \
156     csb_p.xy= mainr.tlbr.xy;                    \
157     if (get_p(csb_p)=='+') {                    \
158       csb_r= mainr;                             \
159       csb_r.tl.xy= csb_p.xy;                    \
160       csb_r.br.xy= csb_p.xy;                    \
161       require_rectangle_r(csb_r, "+");          \
162       mainr.tlbr.xy += increm;                  \
163     }                                           \
164   } while(0)
165
166   debug_rect("mainr",0, mainr);
167
168   CHECK_STRIP_BORDER(tl,x,+1);
169   CHECK_STRIP_BORDER(tl,y,+1);
170   CHECK_STRIP_BORDER(br,x,-1);
171   CHECK_STRIP_BORDER(br,y,-1);
172
173   debug_rect("mainr",1, mainr);
174
175   Point up = START_MAIN;
176   WALK_UNTIL_MUST(up, y,-1, mainr.tl.y, '+');
177
178   Point down = START_MAIN;
179   down.y++;
180   WALK_UNTIL_MUST(down, y,+1, mainr.br.y, '+');
181
182   if (DEBUGP(rect)) {
183     int xscaleunit, y,x;
184     for (y=0, xscaleunit=1; y<4; y++, xscaleunit*=10) {
185       fprintf(debug,"     ");
186       for (x=0; x<=cim->w; x++) {
187         if (x % xscaleunit) fputc(' ',debug);
188         else fprintf(debug,"%d",(x / xscaleunit)%10);
189       }
190       fputc('\n',debug);
191     }
192   }
193
194   commbasey= up.y;
195   comminty= down.y - up.y + 2;
196
197   Point across= { mainr.tl.x, commbasey };
198   int colno=0;
199   for (;;) {
200     MUST( get_p(across) != '+', MI(colno);MP(across);MR(mainr);MI(commbasey) );
201     WALK_UNTIL(across, x,+1, mainr.br.x, '+');
202     MUST( colno < MAX_COLUMNS, MP(across);MR(mainr);MI(commbasey); );
203     int colrx= across.x;
204     if (colrx > mainr.br.x) colrx= mainr.br.x;
205     if (colno < INTERESTING_COLUMNS)
206       colrightx[colno]= colrx;
207       
208     colno++;
209     
210     if (across.x >= mainr.br.x-1)
211       break;
212
213     across.x++;
214     require_rectangle(across.x,mainr.tl.y, across.x,mainr.br.y, "+");
215     across.x++;
216   }
217   MUST( colno >= MIN_COLUMNS, MI(colno);MR(mainr);MP(across); );
218
219 #define SET_ONCE(var,val) do{                                           \
220     int v= (val);                                                       \
221     if ((var)==-1) (var)= v;                                            \
222     else MUST( (var) == v, MSB(#var);MI((var));MI(v);MR(mainr); );      \
223   }while(0)
224
225   SET_ONCE(columns, colno);
226   SET_ONCE(text_h, comminty - 1);
227 }                   
228
229 CanonImage *alloc_canon_image(int w, int h) {
230   CanonImage *im= mmalloc(sizeof(CanonImage) + w*h);
231   im->w= w;
232   im->h= h;
233   memset(im->d,'?',w*h);
234   return im;
235 }
236
237 static void file_read_image_ppm(FILE *f) {
238   struct pam inpam;
239   unsigned char rgb_buf[3];
240   CanonImage *im;
241
242   pnm_readpaminit(f, &inpam, sizeof(inpam));
243   if (!(inpam.maxval == 255 &&
244         inpam.bytes_per_sample == 1 &&
245         inpam.format == RPPM_FORMAT))
246     fatal("PNM screenshot(s) file must be 8bpp 1 byte per sample RGB");
247
248   CANONICALISE_IMAGE(im, inpam.width, inpam.height, {
249     int r= fread(&rgb_buf,1,3,f);
250     sysassert(!ferror(f));
251     if (r!=3) fatal("PNM screenshot(s) file ends unexpectedly");
252
253     rgb=
254         ((unsigned long)rgb_buf[0]<<16) |
255         ((unsigned long)rgb_buf[1]<<8) |
256                        (rgb_buf[2]);
257   });
258
259   sysassert(!ferror(screenshots_file));
260
261   if (!(npages < MAX_PAGES))
262     fatal("Too many images in screenshots file; max is %d.\n", MAX_PAGES);
263
264   page_images[npages++]= im;
265 }
266
267 void read_one_screenshot(void) {
268   progress("reading screenshot...");
269   file_read_image_ppm(screenshots_file);
270   progress_log("read screenshot.");
271 }
272
273 void read_screenshots(void) {
274   struct stat stab;
275   
276   sysassert(! fstat(fileno(screenshots_file), &stab) );
277   
278   for (;;) {
279     if (S_ISREG(stab.st_mode)) {
280       long pos= ftell(screenshots_file);
281       if (pos == stab.st_size) break;
282     } else {
283       int c= fgetc(screenshots_file);
284       if (c==EOF) break;
285       ungetc(c, screenshots_file);
286     }
287     progress("reading screenshot %d...",npages);
288     file_read_image_ppm(screenshots_file);
289   }
290   sysassert(!ferror(screenshots_file));
291   progress_log("read %d screenshots.",npages);
292 }
293
294 static void find_commodity(int offset, Rect *rr) {
295   /* rr->tl.x==-1 if offset out of range */
296   rr->tl.y= commbasey - offset*comminty;
297   rr->br.y= rr->tl.y + comminty-2;
298   if (rr->tl.y < mainr.tl.y || rr->br.y > mainr.br.y) { rr->tl.x=-1; return; }
299   
300   rr->tl.x= mainr.tl.x;
301   rr->br.x= mainr.br.x;
302
303   if (rr->tl.y > mainr.tl.y)
304     require_rectangle(rr->tl.x,rr->tl.y-1, rr->br.x,rr->tl.y-1, "+");
305   if (rr->br.y < mainr.tl.y)
306     require_rectangle(rr->tl.x,rr->br.y+1, rr->br.x,rr->br.y+1, "+");
307 }
308
309 static void find_table_entry(Rect commod, int colno, Rect *cellr) {
310   cellr->tl.y= commod.tl.y;
311   cellr->br.y= commod.br.y;
312   cellr->tl.x= !colno ? commod.tl.x : colrightx[colno-1]+2;
313   cellr->br.x=                        colrightx[colno];
314   debug_rect("cell", colno, *cellr);
315   require_rectangle_r(*cellr, " o");
316 }
317
318 static void ocr_rectangle(Rect r, const OcrCellType ct) {
319   OcrResultGlyph *results, *res;
320
321   int w= r.br.x - r.tl.x + 1;
322   Pixcol cols[w+1];
323   int x,y;
324   for (x=0; x<w; x++) {
325     Pixcol cx, rv;
326     for (y=0, cx=0, rv=1; y<text_h; y++, rv<<=1) {
327       Point here= { x+r.tl.x, y+r.tl.y };
328       int pixel= get_p(here);
329       switch (pixel) {
330       case ' ':           break;
331       case 'o': cx |= rv; break;
332       default:
333         MUST(!"wrong pixel",
334              MC(pixel);MP(here);MSB(ocr_celltype_name(ct));MR(r); );
335       }
336     }
337     cols[x]= cx;
338   }
339   cols[w]= 0;
340
341   results= ocr(rd,ct,w,cols);
342   for (res=results; res->s; res++)
343     printf("%s",res->s);
344 }
345
346 void analyse(void) {
347   Rect thisr, entryr;
348   int page, tryrect, colno;
349
350   for (page=0; page<npages; page++) {
351     find_structure(page_images[page]);
352
353     if (!rd)
354       rd= ocr_init(text_h);
355
356     for (tryrect= +cim->h; tryrect >= -cim->h; tryrect--) {
357       find_commodity(tryrect, &thisr);
358       if (thisr.tl.x < 0)
359         continue;
360       debug_rect("commod",tryrect, thisr);
361
362       const char *tab= "";
363       for (colno=0; colno<columns; colno++) {
364         find_table_entry(thisr,colno,&entryr);
365         fputs(tab, stdout);
366         ocr_rectangle(entryr,
367                       colno<TEXT_COLUMNS
368                       ? &ocr_celltype_text
369                       : &ocr_celltype_number);
370         tab= "\t";
371       }
372       fputs("\n", stdout);
373       sysassert(!ferror(stdout));
374       sysassert(!fflush(stdout));
375     }
376   }
377 }