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