chiark / gitweb /
progress printing and bugfixing and build system improvements
[ypp-sc-tools.db-live.git] / pctb / pages.c
1 /*
2   */
3
4 #include "structure.h"
5
6 #include <X11/Xlib.h>
7 #include <X11/extensions/XTest.h>
8 #include <X11/keysym.h>
9 #include <X11/Xutil.h>
10
11 CanonImage *page_images[MAX_PAGES];
12 int npages;
13
14 char *ocean, *pirate;
15
16 static XWindowAttributes attr;
17 static Window id;
18 static Display *disp;
19 static struct timeval tv_startup;
20 static unsigned wwidth, wheight;
21
22 DEBUG_DEFINE_DEBUGF(pages)
23
24 static KeyCode keycode(KeySym sym) {
25   return XKeysymToKeycode(disp,sym);
26 }
27
28 void screenshot_startup(void) {
29   int r;
30   progress("starting...");
31   disp= XOpenDisplay(0);  eassert(disp);
32   r= gettimeofday(&tv_startup,0);  eassert(!r);
33 }
34
35 /*---------- pager ----------*/
36
37 typedef XImage Snapshot;
38
39 static double last_input;
40 static const double min_update_allowance= 0.25;
41
42 static double timestamp(void) {
43   struct timeval tv;
44   int r;
45   
46   r= gettimeofday(&tv,0);  eassert(!r);
47   double t= (tv.tv_sec - tv_startup.tv_sec) +
48             (tv.tv_usec - tv_startup.tv_usec) * 1e-6;
49   debugf("PAGING %f\n",t);
50   return t;
51 }
52 static void delay(double need_sleep) {
53   int r;
54   debugf("PAGING     delay %f\n",need_sleep);
55   r= usleep(need_sleep * 1e6);  eassert(!r);
56 }
57
58 static void sync_after_input(void) {
59   int r;
60   r= XSync(disp, False);  eassert(r);
61   last_input= timestamp();
62 }
63
64 static void translate_coords_toroot(int wx, int wy, int *rx, int *ry) {
65   int r;
66   Window dummy;
67   r= XTranslateCoordinates(disp, id,attr.root, wx,wy, rx,ry, &dummy);
68   eassert(r);
69 }
70
71 static void check_client_window_all_on_screen(void) {
72   int r;
73   int rxpos, rypos;
74   unsigned rwidth, rheight;
75   Window dummy;
76   unsigned bd, depth;
77
78   r= XGetGeometry(disp,attr.root, &dummy, &rxpos,&rypos,
79                   &rwidth, &rheight,
80                   &bd,&depth);
81   
82   translate_coords_toroot(0,0, &rxpos,&rypos);
83   eassert(rxpos>=0 && rypos>=0);
84
85   translate_coords_toroot(wwidth-1,wheight-1, &rxpos,&rypos);
86   eassert(rxpos<rwidth && rypos<rheight);
87 }
88
89 static void check_not_disturbed(void) {
90   XEvent ev;
91   int r;
92   
93   for (;;) {
94     r= XCheckMaskEvent(disp, ~0, &ev);
95     if (r==False) return;
96
97     switch (ev.type) {
98     case VisibilityNotify:
99       eassert(ev.xvisibility.state == VisibilityUnobscured);
100       break;
101     case ConfigureNotify:
102       check_client_window_all_on_screen();
103       break;
104     case FocusOut:
105       eassert(!"focus left YPP client window");
106       break;
107     case FocusIn:
108       warning("focus entered YPP client window ?!");
109       break;
110     default:
111       eassert(!"unexpected X11 event");
112     }
113   }
114 }      
115
116 static void send_key(KeySym sym) {
117   XTestFakeKeyEvent(disp, keycode(sym),1, 10);
118   XTestFakeKeyEvent(disp, keycode(sym),0, 10);
119 }
120
121 static void send_pgup_many(void) {
122   int i;
123   for (i=0; i<25; i++)
124     send_key(XK_Prior);
125   debugf("PAGING   PageUp x %d\n",i);
126   sync_after_input();
127 }
128 static void send_pgdown(void) {
129   send_key(XK_Next);
130   debugf("PAGING   PageDown\n");
131   sync_after_input();
132 }
133
134 static void free_snapshot(Snapshot **io) {
135   if (*io) XDestroyImage(*io);
136   *io= 0;
137 }
138
139 static void snapshot(Snapshot **output) {
140   free_snapshot(output);
141
142   debugf("PAGING   snapshot\n");
143
144   timestamp();
145   *output= XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap);
146   timestamp();
147
148   check_not_disturbed();
149
150   debugf("PAGING   snapshot done.\n");
151 }
152
153 static int identical(const Snapshot *a, const Snapshot *b) {
154   if (!(a->width == b->width &&
155         a->height == b->height &&
156         a->bytes_per_line == b->bytes_per_line &&
157         a->format == b->format))
158     return 0;
159   return !memcmp(a->data, b->data, a->bytes_per_line * a->height);
160 }
161
162 static void wait_for_stability(Snapshot **output,
163                                const Snapshot *previously,
164                                void (*with_keypress)(void),
165                                const char *fmt, ...)
166      FMT(4,5);
167
168 static void wait_for_stability(Snapshot **output,
169                                const Snapshot *previously,
170                                void (*with_keypress)(void),
171                                const char *fmt, ...) {
172   va_list al;
173   va_start(al,fmt);
174
175   Snapshot *last=0;
176   int r;
177   /* waits longer if we're going to return an image identical to previously
178    * if previously==0, all images are considered identical to it */
179
180   debugf("PAGING  wait_for_stability"
181           "  last_input=%f previously=%p\n",
182           last_input, previously);
183
184   char *doing;
185   r= vasprintf(&doing,fmt,al);  eassert(r>=0);
186
187   progress("%s",doing);
188
189   for (;;) {
190     double at_snapshot= timestamp();
191     double need_sleep= min_update_allowance - (at_snapshot - last_input);
192     if (need_sleep > 0) { delay(need_sleep); continue; }
193
194     snapshot(output);
195
196     if (!with_keypress &&
197         !(previously && identical(*output,previously))) {
198       debugf("PAGING  wait_for_stability  simple\n");
199       break;
200     }
201
202     if (last && identical(*output,last)) {
203       debugf("PAGING  wait_for_stability  stabilised\n");
204       break;
205     }
206     
207     progress_spinner("%s",doing);
208
209     debugf("PAGING  wait_for_stability  retry\n");
210
211     free_snapshot(&last); last=*output; *output=0;
212
213     if (with_keypress)
214       with_keypress();
215
216     delay(0.5);
217   }
218
219   free_snapshot(&last);
220   free(doing);
221   debugf("PAGING  wait_for_stability done.\n");
222   va_end(al);
223 }
224
225 static void raise_and_get_details(void) {
226   int r;
227   int evbase,errbase,majver,minver;
228   int wxpos, wypos;
229   unsigned bd,depth;
230
231   progress("raising and checking YPP client window...");
232
233   debugf("PAGING raise_and_get_details\n");
234
235   r= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
236   eassert(r==True);
237
238   r= XRaiseWindow(disp, id);  eassert(r);
239   /* in case VisibilityNotify triggers right away before we have had a
240    * change to raise; to avoid falsely detecting lowering in that case */
241   
242   r= XSelectInput(disp, id,
243                   StructureNotifyMask|
244                   VisibilityChangeMask
245                   );  eassert(r);
246
247   r= XRaiseWindow(disp, id);  eassert(r);
248   /* in case the window was lowered between our Raise and our SelectInput;
249    * to avoid failing to detect that lowering */
250
251   r= XGetWindowAttributes(disp, id, &attr);  eassert(r);
252   r= XGetGeometry(disp,id, &attr.root,
253                   &wxpos,&wypos, &wwidth,&wheight,
254                   &bd,&depth);
255
256   eassert(wwidth >= 320 && wheight >= 320);
257
258   check_client_window_all_on_screen();
259 }
260
261 static void set_focus(void) {
262   int r;
263   int screen= XScreenNumberOfScreen(attr.screen);
264
265   progress("taking control of YPP client window...");
266
267   debugf("PAGING set_focus\n");
268
269   int xpos, ypos;
270   translate_coords_toroot(160,160, &xpos,&ypos);
271   XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
272
273   XTestFakeButtonEvent(disp,1,1, 50);
274   XTestFakeButtonEvent(disp,1,0, 50);
275
276   sync_after_input();
277
278   delay(0.5);
279   r= XSelectInput(disp, id,
280                   StructureNotifyMask|
281                   VisibilityChangeMask|
282                   FocusChangeMask
283                   );  eassert(r);
284
285   translate_coords_toroot(10,10, &xpos,&ypos);
286   XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
287
288   sync_after_input();
289
290   debugf("PAGING raise_and_set_focus done.\n");
291 }
292
293 #define SAMPLEMASK 0xfful
294
295 typedef struct {
296   int lshift, rshift;
297 } ShMask;
298
299 static void compute_shift_mask(ShMask *sm, unsigned long ximage_mask) {
300   sm->lshift= 0;
301   sm->rshift= 0;
302   
303   for (;;) {
304     if (ximage_mask <= (SAMPLEMASK>>1)) {
305       sm->lshift++;  ximage_mask <<= 1;
306     } else if (ximage_mask > SAMPLEMASK) {
307       sm->rshift++;  ximage_mask >>= 1;
308     } else {
309       break;
310     }
311     assert(!(sm->lshift && sm->rshift));
312   }
313   assert(sm->lshift < LONG_BIT);
314   assert(sm->rshift < LONG_BIT);
315 }
316
317 static CanonImage *convert_page(Snapshot *sn) {
318   ShMask shiftmasks[3];
319   CanonImage *im;
320
321   fprintf(screenshots_file,
322           "P6\n"
323           "%d %d\n"
324           "255\n", sn->width, sn->height);
325
326 #define COMPUTE_SHIFT_MASK(ix, rgb) \
327   compute_shift_mask(&shiftmasks[ix], sn->rgb##_mask)
328   COMPUTE_SHIFT_MASK(0, red);
329   COMPUTE_SHIFT_MASK(1, green);
330   COMPUTE_SHIFT_MASK(2, blue);
331
332   CANONICALISE_IMAGE(im, sn->width, sn->height, {
333     long xrgb= XGetPixel(sn, x, y);
334     int i;
335     rgb= 0;
336     for (i=0; i<3; i++) {
337       rgb <<= 8;
338       unsigned long sample=
339         ((xrgb << shiftmasks[i].lshift)
340               >> shiftmasks[i].rshift) & SAMPLEMASK;
341       rgb |= sample;
342       fputc(sample, screenshots_file);
343     }
344   });
345
346   eassert(!fflush(screenshots_file));
347
348   return im;
349 }
350
351 void take_screenshots(void) {
352   Snapshot *current=0, *last=0;
353   CanonImage *test;
354
355   /* find the window and check it's on the right kind of screen */
356   raise_and_get_details();
357   wait_for_stability(&current,0,0, "checking current YPP client screen...");
358   test= convert_page(current);
359   find_structure(test);
360   free(test);
361
362   /* page to the top - keep pressing page up until the image stops changing */
363   set_focus();
364   wait_for_stability(&current,0, send_pgup_many,
365                      "paging up to top of commodity list...");
366
367   /* now to actually page down */
368   for (;;) {
369     debugf("paging page %d\n",npages);
370
371     eassert(npages < MAX_PAGES);
372     page_images[npages]= convert_page(current);
373     free_snapshot(&last); last=current; current=0;
374
375     debugf("PAGING page %d converted\n",npages);
376
377     wait_for_stability(&current,last, 0,
378                        "collecting screenshot of page %d...",
379                        npages+1);
380
381     if (npages &&  /* first pagedown doesn't do much */
382         identical(current,last)) {
383       free_snapshot(&current);
384       break;
385     }
386
387     send_pgdown();
388     npages++;
389   }
390   debugf("PAGING all done.\n");
391   progress_log("collected %d screenshots.",npages);
392 }    
393
394 void take_one_screenshot(void) {
395   Snapshot *current=0;
396   
397   raise_and_get_details();
398   sync_after_input();
399   wait_for_stability(&current,0,0, "taking screenshot...");
400   page_images[0]= convert_page(current);
401   npages= 1;
402   progress_log("collected single screenshot.");
403 }
404
405 void set_yppclient_window(unsigned long wul) {
406   id= wul;
407 }
408
409 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
410
411 void find_yppclient_window(void) {
412   Window root, gotroot, gotparent;
413   int screen, r;
414   int nfound=0;
415   
416   if (id) return;
417   
418   progress("looking for YPP client window...");
419
420   static const char prefix[]= "Puzzle Pirates - ";
421   static const char onthe[]= " on the ";
422   static const char suffix[]= " ocean";
423 #define S(x) (sizeof((x))-1)
424
425   Atom wm_name= XInternAtom(disp,"WM_NAME",True);
426   eassert(wm_name != None);
427
428   for (screen=0; screen<ScreenCount(disp); screen++) {
429     debugfind("FINDYPP screen %d\n", screen);
430     root= RootWindow(disp,screen);
431     unsigned int nchildren1;
432     Window *children1=0;
433
434     r= XQueryTree(disp,root,
435                   &gotroot,&gotparent,
436                   &children1,&nchildren1);
437     eassert(r);
438     debugfind("FINDYPP screen %d nchildren1=%d\n", screen, nchildren1);
439
440     int i;
441     for (i=0; i<nchildren1; i++) {
442       Window w1= children1[i];
443       unsigned int nchildren2;
444       Window *children2=0;
445
446       r= XQueryTree(disp,w1,
447                     &gotroot,&gotparent,
448                     &children2,&nchildren2);
449       eassert(r);
450       debugfind("FINDYPP screen %d c1[%2d]=0x%08lx nchildren2=%d\n",
451                 screen, i, (unsigned long)w1, nchildren2);
452
453       int j;
454       for (j=-1; j<(int)nchildren2; j++) {
455         Window w2= j<0 ? w1 : children2[j];
456         debugfind("FINDYPP screen %d c1[%2d]=0x%08lx c2[%2d]=0x%08lx",
457                   screen, i, (unsigned long)w1, j, (unsigned long)w2);
458
459         int gotfmt;
460         Atom gottype;
461         unsigned long len, gotbytesafter;
462         char *title;
463         unsigned char *gottitle=0;
464         r= XGetWindowProperty(disp,w2, wm_name,0,512, False,
465                               AnyPropertyType,&gottype, &gotfmt, &len,
466                               &gotbytesafter, &gottitle);
467         eassert(!r);
468         title= (char*)gottitle;
469
470         if (DEBUGP(findypp)) {
471           debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
472           char *p;
473           for (p=title; p < title+len; p++) {
474             char c= *p;
475             if (c>=' ' && c<=126) fputc(c,debug);
476             else fprintf(debug,"\\x%02x",c & 0xff);
477           }
478           fputs("\": ",debug);
479         }
480
481 #define REQUIRE(pred)                                                      \
482         if (!(pred)) { debugfind(" failed test  %s\n", #pred); continue; } \
483         else
484
485         REQUIRE( gottype!=None );
486         REQUIRE( len );
487         REQUIRE( gotfmt==8 );
488
489         REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
490
491         char *spc1= strchr(  title        + S(prefix), ' ');  REQUIRE(spc1);
492         char *spc2= strrchr((title + len) - S(suffix), ' ');  REQUIRE(spc2);
493
494         REQUIRE( (title + len) - spc1  >= S(onthe)  + S(suffix) );
495         REQUIRE(  spc2         - title >= S(prefix) + S(onthe) );
496
497         REQUIRE( !memcmp(title,                   prefix, S(prefix)) );
498         REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix))  );
499         REQUIRE( !memcmp(spc1,                    onthe,  S(onthe))  );
500
501 #define ASSIGN(what, start, end) do {                                   \
502         r= asprintf(&what, "%.*s", end - start, start);  eassert(r>0);  \
503      }while(0)
504         ASSIGN(ocean,  title + S(prefix),  spc1);
505         ASSIGN(pirate, spc1 + S(onthe),   (title + len) - S(suffix));
506
507         debugfind(" YES!\n");
508         id= w2;
509         nfound++;
510         progress_log("found YPP client window (0x%lx): %s on the %s ocean.",
511                      (unsigned long)id, pirate, ocean);
512       }
513       if (children2) XFree(children2);
514     }
515     if (children1) XFree(children1);
516   }
517   eassert(nfound==1);
518 }