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