chiark / gitweb /
99f4af2adb562be8e340981f78f5b0416b0e17b3
[ypp-sc-tools.db-test.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 send_key(KeySym sym) {
65   XTestFakeKeyEvent(disp, keycode(sym),1, 10);
66   XTestFakeKeyEvent(disp, keycode(sym),0, 10);
67 }
68
69 static void send_pgup_many(void) {
70   int i;
71   for (i=0; i<25; i++)
72     send_key(XK_Prior);
73   debugf("PAGING   PageUp x %d\n",i);
74   sync_after_input();
75 }
76 static void send_pgdown(void) {
77   send_key(XK_Next);
78   debugf("PAGING   PageDown\n");
79   sync_after_input();
80 }
81
82 static void free_snapshot(Snapshot **io) {
83   if (*io) XDestroyImage(*io);
84   *io= 0;
85 }
86
87 static void snapshot(Snapshot **output) {
88 //  char *cmd;
89 //  int r;
90 //  XImage *xim;
91   
92   free_snapshot(output);
93
94   debugf("PAGING   snapshot\n");
95
96   timestamp();
97   *output= XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap);
98   timestamp();
99   
100   debugf("PAGING   snapshot done.\n");
101 }
102
103 static int identical(const Snapshot *a, const Snapshot *b) {
104   if (!(a->width == b->width &&
105         a->height == b->height &&
106         a->bytes_per_line == b->bytes_per_line &&
107         a->format == b->format))
108     return 0;
109   return !memcmp(a->data, b->data, a->bytes_per_line * a->height);
110 }
111
112 static void wait_for_stability(Snapshot **output,
113                                const Snapshot *previously,
114                                void (*with_keypress)(void)) {
115   Snapshot *last=0;
116   /* waits longer if we're going to return an image identical to previously
117    * if previously==0, all images are considered identical to it */
118
119   debugf("PAGING  wait_for_stability"
120           "  last_input=%f previously=%p\n",
121           last_input, previously);
122
123   for (;;) {
124     double at_snapshot= timestamp();
125     double need_sleep= min_update_allowance - (at_snapshot - last_input);
126     if (need_sleep > 0) { delay(need_sleep); continue; }
127
128     snapshot(output);
129
130     if (!with_keypress &&
131         !(previously && identical(*output,previously))) {
132       debugf("PAGING  wait_for_stability  simple\n");
133       break;
134     }
135
136     if (last && identical(*output,last)) {
137       debugf("PAGING  wait_for_stability  stabilised\n");
138       break;
139     }
140     
141     debugf("PAGING  wait_for_stability  retry\n");
142
143     free_snapshot(&last); last=*output; *output=0;
144
145     if (with_keypress)
146       with_keypress();
147
148     delay(0.5);
149   }
150
151   free_snapshot(&last);
152   debugf("PAGING  wait_for_stability done.\n");
153 }
154
155 static void translate_coords_toroot(int wx, int wy, int *rx, int *ry) {
156   int r;
157   Window dummy;
158   r= XTranslateCoordinates(disp, id,attr.root, wx,wy, rx,ry, &dummy);
159   eassert(r);
160 }
161
162 static void raise_and_get_details(void) {
163   int r;
164   int evbase,errbase,majver,minver;
165   int wxpos, wypos;
166   unsigned bd,depth;
167   Window dummy;
168
169   progress("raising and checking YPP client window ...\n");
170
171   debugf("PAGING raise_and_get_details\n");
172
173   r= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
174   eassert(r==True);
175
176   r= XRaiseWindow(disp, id);  eassert(r);
177   /* in case VisibilityNotify triggers right away before we have had a
178    * change to raise; to avoid falsely detecting lowering in that case */
179   
180   r= XSelectInput(disp, id,
181                   StructureNotifyMask|
182                   VisibilityChangeMask
183                   );  eassert(r);
184
185   r= XRaiseWindow(disp, id);  eassert(r);
186   /* in case the window was lowered between our Raise and our SelectInput;
187    * to avoid failing to detect that lowering */
188
189   r= XGetWindowAttributes(disp, id, &attr);  eassert(r);
190   r= XGetGeometry(disp,id, &attr.root,
191                   &wxpos,&wypos, &wwidth,&wheight,
192                   &bd,&depth);
193
194   eassert(wwidth >= 320 && wheight >= 320);
195
196   int rxpos, rypos;
197   unsigned rwidth, rheight;
198   r= XGetGeometry(disp,attr.root, &dummy, &rxpos,&rypos,
199                   &rwidth, &rheight,
200                   &bd,&depth);
201   
202   translate_coords_toroot(0,0, &rxpos,&rypos);
203   eassert(rxpos>=0 && rypos>=0);
204
205   translate_coords_toroot(wwidth-1,wheight-1, &rxpos,&rypos);
206   eassert(rxpos<rwidth && rypos<rheight);
207 }
208
209 static void set_focus(void) {
210   int screen= XScreenNumberOfScreen(attr.screen);
211
212   progress("taking control of YPP client window ...\n");
213
214   debugf("PAGING set_focus\n");
215
216   int xpos, ypos;
217   translate_coords_toroot(160,160, &xpos,&ypos);
218   XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
219
220   XTestFakeButtonEvent(disp,1,1, 50);
221   XTestFakeButtonEvent(disp,1,0, 50);
222
223   sync_after_input();
224
225   translate_coords_toroot(10,10, &xpos,&ypos);
226   XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
227
228   sync_after_input();
229
230   debugf("PAGING raise_and_set_focus done.\n");
231 }
232
233 #define SAMPLEMASK 0xfful
234
235 typedef struct {
236   int lshift, rshift;
237 } ShMask;
238
239 static void compute_shift_mask(ShMask *sm, unsigned long ximage_mask) {
240   sm->lshift= 0;
241   sm->rshift= 0;
242   
243   for (;;) {
244     if (ximage_mask <= (SAMPLEMASK>>1)) {
245       sm->lshift++;  ximage_mask <<= 1;
246     } else if (ximage_mask > SAMPLEMASK) {
247       sm->rshift++;  ximage_mask >>= 1;
248     } else {
249       break;
250     }
251     assert(!(sm->lshift && sm->rshift));
252   }
253   assert(sm->lshift < LONG_BIT);
254   assert(sm->rshift < LONG_BIT);
255 }
256
257 static CanonImage *convert_page(Snapshot *sn) {
258   ShMask shiftmasks[3];
259   CanonImage *im;
260
261   fprintf(screenshots_file,
262           "P6\n"
263           "%d %d\n"
264           "255\n", sn->width, sn->height);
265
266 #define COMPUTE_SHIFT_MASK(ix, rgb) \
267   compute_shift_mask(&shiftmasks[ix], sn->rgb##_mask)
268   COMPUTE_SHIFT_MASK(0, red);
269   COMPUTE_SHIFT_MASK(1, green);
270   COMPUTE_SHIFT_MASK(2, blue);
271
272   CANONICALISE_IMAGE(im, sn->width, sn->height, {
273     long xrgb= XGetPixel(sn, x, y);
274     int i;
275     rgb= 0;
276     for (i=0; i<3; i++) {
277       rgb <<= 8;
278       unsigned long sample=
279         ((xrgb << shiftmasks[i].lshift)
280               >> shiftmasks[i].rshift) & SAMPLEMASK;
281       rgb |= sample;
282       fputc(sample, screenshots_file);
283     }
284   });
285
286   eassert(!fflush(screenshots_file));
287
288   return im;
289 }
290
291 void take_screenshots(void) {
292   Snapshot *current=0, *last=0;
293   CanonImage *test;
294
295   /* find the window and check it's on the right kind of screen */
296   raise_and_get_details();
297   wait_for_stability(&current,0,0);
298   test= convert_page(current);
299   find_structure(test);
300   free(test);
301
302   /* page to the top - keep pressing page up until the image stops changing */
303   set_focus();
304   wait_for_stability(&current,0, send_pgup_many);
305
306   /* now to actually page down */
307   for (;;) {
308     debugf("paging page %d\n",npages);
309
310     eassert(npages < MAX_PAGES);
311     page_images[npages]= convert_page(current);
312     free_snapshot(&last); last=current; current=0;
313
314     debugf("PAGING page %d converted\n",npages);
315
316     wait_for_stability(&current,last, 0);
317     if (npages &&  /* first pagedown doesn't do much */
318         identical(current,last)) {
319       free_snapshot(&current);
320       break;
321     }
322
323     send_pgdown();
324     npages++;
325   }
326   debugf("PAGING all done.\n");
327 }    
328
329 void take_one_screenshot(void) {
330   Snapshot *current=0;
331   
332   raise_and_get_details();
333   sync_after_input();
334   wait_for_stability(&current,0,0);
335   page_images[0]= convert_page(current);
336   npages= 1;
337 }
338
339 void set_yppclient_window(unsigned long wul) {
340   id= wul;
341 }
342
343 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
344
345 void find_yppclient_window(void) {
346   Window root, gotroot, gotparent;
347   int screen, r;
348   int nfound=0;
349   
350   if (id) return;
351   
352   static const char prefix[]= "Puzzle Pirates - ";
353   static const char onthe[]= " on the ";
354   static const char suffix[]= " ocean";
355 #define S(x) (sizeof((x))-1)
356
357   Atom wm_name= XInternAtom(disp,"WM_NAME",True);
358   eassert(wm_name != None);
359
360   for (screen=0; screen<ScreenCount(disp); screen++) {
361     debugfind("FINDYPP screen %d\n", screen);
362     root= RootWindow(disp,screen);
363     unsigned int nchildren1;
364     Window *children1=0;
365
366     r= XQueryTree(disp,root,
367                   &gotroot,&gotparent,
368                   &children1,&nchildren1);
369     eassert(r);
370     debugfind("FINDYPP screen %d nchildren1=%d\n", screen, nchildren1);
371
372     int i;
373     for (i=0; i<nchildren1; i++) {
374       Window w1= children1[i];
375       unsigned int nchildren2;
376       Window *children2=0;
377
378       r= XQueryTree(disp,w1,
379                     &gotroot,&gotparent,
380                     &children2,&nchildren2);
381       eassert(r);
382       debugfind("FINDYPP screen %d c1[%2d]=0x%08lx nchildren2=%d\n",
383                 screen, i, (unsigned long)w1, nchildren2);
384
385       int j;
386       for (j=-1; j<(int)nchildren2; j++) {
387         Window w2= j<0 ? w1 : children2[j];
388         debugfind("FINDYPP screen %d c1[%2d]=0x%08lx c2[%2d]=0x%08lx",
389                   screen, i, (unsigned long)w1, j, (unsigned long)w2);
390
391         int gotfmt;
392         Atom gottype;
393         unsigned long len, gotbytesafter;
394         char *title;
395         unsigned char *gottitle=0;
396         r= XGetWindowProperty(disp,w2, wm_name,0,512, False,
397                               AnyPropertyType,&gottype, &gotfmt, &len,
398                               &gotbytesafter, &gottitle);
399         eassert(!r);
400         title= (char*)gottitle;
401
402         if (DEBUGP(findypp)) {
403           debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
404           char *p;
405           for (p=title; p < title+len; p++) {
406             char c= *p;
407             if (c>=' ' && c<=126) fputc(c,debug);
408             else fprintf(debug,"\\x%02x",c & 0xff);
409           }
410           fputs("\": ",debug);
411         }
412
413 #define REQUIRE(pred)                                                      \
414         if (!(pred)) { debugfind(" failed test  %s\n", #pred); continue; } \
415         else
416
417         REQUIRE( gottype!=None );
418         REQUIRE( len );
419         REQUIRE( gotfmt==8 );
420
421         REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
422
423         char *spc1= strchr(  title        + S(prefix), ' ');  REQUIRE(spc1);
424         char *spc2= strrchr((title + len) - S(suffix), ' ');  REQUIRE(spc2);
425
426         REQUIRE( (title + len) - spc1  >= S(onthe)  + S(suffix) );
427         REQUIRE(  spc2         - title >= S(prefix) + S(onthe) );
428
429         REQUIRE( !memcmp(title,                   prefix, S(prefix)) );
430         REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix))  );
431         REQUIRE( !memcmp(spc1,                    onthe,  S(onthe))  );
432
433 #define ASSIGN(what, start, end) do {                                   \
434         r= asprintf(&what, "%.*s", end - start, start);  eassert(r>0);  \
435      }while(0)
436         ASSIGN(ocean,  title + S(prefix),  spc1);
437         ASSIGN(pirate, spc1 + S(onthe),   (title + len) - S(suffix));
438
439         debugfind(" YES!\n");
440         id= w2;
441         nfound++;
442         progress_log("found YPP client window 0x%lx: %s on the %s ocean\n",
443                      (unsigned long)id, pirate, ocean);
444       }
445       if (children2) XFree(children2);
446     }
447     if (children1) XFree(children1);
448   }
449   eassert(nfound==1);
450 }