chiark / gitweb /
WIP island determination; pixoptions can list islands
[ypp-sc-tools.db-test.git] / pctb / pages.c
1 /*
2  * Interaction with the YPP client via X11
3  */
4 /*
5  *  This is part of ypp-sc-tools, a set of third-party tools for assisting
6  *  players of Yohoho Puzzle Pirates.
7  * 
8  *  Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9  * 
10  *  This program is free software: you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation, either version 3 of the License, or
13  *  (at your option) any later version.
14  * 
15  *  This program is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  * 
20  *  You should have received a copy of the GNU General Public License
21  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  * 
23  *  Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
24  *  are used without permission.  This program is not endorsed or
25  *  sponsored by Three Rings.
26  */
27
28 /*
29  * Only this file #includes the X11 headers, as they're quite
30  * pollutant of the namespace.
31  */
32
33 #include "structure.h"
34
35 #include <X11/Xlib.h>
36 #include <X11/extensions/XTest.h>
37 #include <X11/keysym.h>
38 #include <X11/Xutil.h>
39
40 CanonImage *page_images[MAX_PAGES];
41 int npages;
42 RgbImage *page0_rgbimage;
43
44 char *ocean, *pirate;
45
46 static XWindowAttributes attr;
47 static Window id;
48 static Display *disp;
49 static struct timeval tv_startup;
50 static unsigned wwidth, wheight;
51 static int max_relevant_y= -1;
52
53 DEBUG_DEFINE_DEBUGF(pages)
54
55 #define xassert(what)                                   \
56   ((what) ? (void)0 :                                   \
57    fatal("X11 operation unexpectedly failed."           \
58          " %s:%d: %s\n", __FILE__,__LINE__,#what))
59
60 static KeyCode keycode(KeySym sym) {
61   return XKeysymToKeycode(disp,sym);
62 }
63
64 void screenshot_startup(void) {
65   progress("starting...");
66   disp= XOpenDisplay(0);
67   if (!disp) fatal("Unable to open X11 display.");
68   sysassert(! gettimeofday(&tv_startup,0) );
69 }
70
71 /*---------- pager ----------*/
72
73 typedef XImage Snapshot;
74
75 static double last_input;
76 static const double min_update_allowance= 0.25;
77
78 static double timestamp(void) {
79   struct timeval tv;
80   
81   sysassert(! gettimeofday(&tv,0) );
82   double t= (tv.tv_sec - tv_startup.tv_sec) +
83             (tv.tv_usec - tv_startup.tv_usec) * 1e-6;
84   debugf("PAGING %f\n",t);
85   return t;
86 }
87 static void delay(double need_sleep) {
88   debugf("PAGING     delay %f\n",need_sleep);
89   sysassert(! usleep(need_sleep * 1e6) );
90 }
91
92 static void sync_after_input(void) {
93   xassert( XSync(disp, False) );
94   last_input= timestamp();
95 }
96
97 static void translate_coords_toroot(int wx, int wy, int *rx, int *ry) {
98   Window dummy;
99   xassert( XTranslateCoordinates(disp, id,attr.root, wx,wy, rx,ry, &dummy) );
100 }
101
102 static void check_client_window_all_on_screen(void) {
103   Rect onroot;
104   unsigned rwidth, rheight;
105   Window dummy;
106   unsigned bd, depth;
107   int rxpos, rypos;
108
109   xassert( XGetGeometry(disp,attr.root, &dummy, &rxpos,&rypos,
110                         &rwidth, &rheight,
111                         &bd,&depth) );
112   
113   translate_coords_toroot(0,0, &onroot.tl.x,&onroot.tl.y);
114   translate_coords_toroot(wwidth-1,wheight-1, &onroot.br.x,&onroot.br.y);
115   if (!(onroot.tl.x >= 0 &&
116         onroot.tl.y >= 0 &&
117         onroot.br.x < rwidth &&
118         onroot.br.y < rheight))
119     fatal("YPP client window is not entirely on the screen.");
120 }
121
122 static void check_not_disturbed(void) {
123   XEvent ev;
124   int r;
125   
126   for (;;) {
127     r= XCheckMaskEvent(disp, ~0, &ev);
128     if (r==False) return;
129
130     switch (ev.type) {
131     case VisibilityNotify:
132       if (ev.xvisibility.state != VisibilityUnobscured)
133         fatal("YPP client window has become obscured.");
134       break;
135     case ConfigureNotify:
136       check_client_window_all_on_screen();
137       break;
138     case FocusOut:
139       fatal("Focus left YPP client window.");
140       break;
141     case FocusIn:
142       warning("focus entered YPP client window ?!");
143       break;
144     default:
145       fatal("Received unexpected X11 event (type code %d)!", ev.type);
146     }
147   }
148 }      
149
150 static void send_key(KeySym sym) {
151   check_not_disturbed();
152   XTestFakeKeyEvent(disp, keycode(sym),1, 10);
153   XTestFakeKeyEvent(disp, keycode(sym),0, 10);
154 }
155 static void mouse_1_updown_here(void) {
156   check_not_disturbed();
157   XTestFakeButtonEvent(disp,1,1, 50);
158   XTestFakeButtonEvent(disp,1,0, 50);
159 }
160 static void mouse_1_updown(int x, int y) {
161   check_not_disturbed();
162   int screen= XScreenNumberOfScreen(attr.screen);
163   int xpos, ypos;
164   translate_coords_toroot(x,y, &xpos,&ypos);
165   XTestFakeMotionEvent(disp, screen, xpos,ypos, 0);
166   mouse_1_updown_here();
167 }
168
169 static int pgupdown;
170
171 static void send_pgup_many(void) {
172   int i;
173   for (i=0; i<25; i++) {
174     send_key(XK_Prior);
175     pgupdown--;
176   }
177   debugf("PAGING   PageUp x %d\n",i);
178   sync_after_input();
179 }
180 static void send_pgdown(void) {
181   send_key(XK_Next);
182   pgupdown++;
183   debugf("PAGING   PageDown\n");
184   sync_after_input();
185 }
186 static void send_pgdown_torestore(void) {
187   debugf("PAGING   PageDown x %d\n", -pgupdown);
188   while (pgupdown < 0) {
189     send_key(XK_Next);
190     pgupdown++;
191   }
192   sync_after_input();
193 }
194
195 static void free_snapshot(Snapshot **io) {
196   if (*io) XDestroyImage(*io);
197   *io= 0;
198 }
199
200 static void snapshot(Snapshot **output) {
201   free_snapshot(output);
202
203   debugf("PAGING   snapshot\n");
204
205   timestamp();
206   *output= XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap);
207   timestamp();
208
209   check_not_disturbed();
210
211   debugf("PAGING   snapshot done.\n");
212 }
213
214 static int identical(const Snapshot *a, const Snapshot *b) {
215   if (!(a->width == b->width &&
216         a->height == b->height &&
217         a->bytes_per_line == b->bytes_per_line &&
218         a->format == b->format))
219     return 0;
220
221   int compare_to= a->height;
222   if (max_relevant_y && compare_to > max_relevant_y)
223     compare_to= max_relevant_y;
224   
225   return !memcmp(a->data, b->data, a->bytes_per_line * compare_to);
226 }
227
228 static void wait_for_stability(Snapshot **output,
229                                const Snapshot *previously,
230                                void (*with_keypress)(void),
231                                const char *fmt, ...)
232      FMT(4,5);
233
234 static void wait_for_stability(Snapshot **output,
235                                const Snapshot *previously,
236                                void (*with_keypress)(void),
237                                const char *fmt, ...) {
238   va_list al;
239   va_start(al,fmt);
240
241   Snapshot *last=0;
242   /* waits longer if we're going to return an image identical to previously
243    * if previously==0, all images are considered identical to it */
244
245   debugf("PAGING  wait_for_stability"
246           "  last_input=%f previously=%p\n",
247           last_input, previously);
248
249   char *doing;
250   sysassert( vasprintf(&doing,fmt,al) >=0);
251
252   progress("%s",doing);
253
254   for (;;) {
255     double at_snapshot= timestamp();
256     double need_sleep= min_update_allowance - (at_snapshot - last_input);
257     if (need_sleep > 0) { delay(need_sleep); continue; }
258
259     snapshot(output);
260
261     if (!with_keypress &&
262         !(previously && identical(*output,previously))) {
263       debugf("PAGING  wait_for_stability  simple\n");
264       break;
265     }
266
267     if (last && identical(*output,last)) {
268       debugf("PAGING  wait_for_stability  stabilised\n");
269       break;
270     }
271     
272     progress_spinner("%s",doing);
273
274     debugf("PAGING  wait_for_stability  retry\n");
275
276     free_snapshot(&last); last=*output; *output=0;
277
278     if (with_keypress)
279       with_keypress();
280
281     delay(0.5);
282   }
283
284   free_snapshot(&last);
285   free(doing);
286   debugf("PAGING  wait_for_stability done.\n");
287   va_end(al);
288 }
289
290 static void raise_and_get_details(void) {
291   int evbase,errbase,majver,minver;
292   int wxpos, wypos;
293   unsigned bd,depth;
294
295   progress("raising and checking YPP client window...");
296
297   debugf("PAGING raise_and_get_details\n");
298
299   int xtest= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
300   if (!xtest) fatal("X server does not support the XTEST extension.");
301
302   xassert( XRaiseWindow(disp, id) );
303   /* in case VisibilityNotify triggers right away before we have had a
304    * change to raise; to avoid falsely detecting lowering in that case */
305   
306   xassert( XSelectInput(disp, id,
307                         StructureNotifyMask|
308                         VisibilityChangeMask
309                         ) );
310
311   xassert( XRaiseWindow(disp, id) );
312   /* in case the window was lowered between our Raise and our SelectInput;
313    * to avoid failing to detect that lowering */
314
315   xassert( XGetWindowAttributes(disp, id, &attr) );
316   xassert( XGetGeometry(disp,id, &attr.root,
317                         &wxpos,&wypos, &wwidth,&wheight,
318                         &bd,&depth) );
319
320   if (!(wwidth >= 320 && wheight >= 320))
321     fatal("YPP client window is implausibly small?");
322
323   check_client_window_all_on_screen();
324 }
325
326 static void set_focus_commodity(void) {
327   int screen= XScreenNumberOfScreen(attr.screen);
328
329   progress("taking control of YPP client window...");
330
331   debugf("PAGING set_focus\n");
332
333   mouse_1_updown(160,160);
334   sync_after_input();
335
336   delay(0.5);
337   xassert( XSelectInput(disp, id,
338                         StructureNotifyMask|
339                         VisibilityChangeMask|
340                         FocusChangeMask
341                         ) );
342
343   int xpos,ypos;
344   translate_coords_toroot(10,10, &xpos,&ypos);
345   XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
346
347   sync_after_input();
348
349   debugf("PAGING raise_and_set_focus done.\n");
350 }
351
352 #define SAMPLEMASK 0xfful
353
354 typedef struct {
355   int lshift, rshift;
356 } ShMask;
357
358 static void compute_shift_mask(ShMask *sm, unsigned long ximage_mask) {
359   sm->lshift= 0;
360   sm->rshift= 0;
361   
362   for (;;) {
363     if (ximage_mask <= (SAMPLEMASK>>1)) {
364       sm->lshift++;  ximage_mask <<= 1;
365     } else if (ximage_mask > SAMPLEMASK) {
366       sm->rshift++;  ximage_mask >>= 1;
367     } else {
368       break;
369     }
370     assert(!(sm->lshift && sm->rshift));
371   }
372   assert(sm->lshift < LONG_BIT);
373   assert(sm->rshift < LONG_BIT);
374 }
375
376 static CanonImage *convert_page(Snapshot *sn, RgbImage *ri) {
377   ShMask shiftmasks[3];
378   CanonImage *im;
379
380   fprintf(screenshot_file,
381           "P6\n"
382           "%d %d\n"
383           "255\n", sn->width, sn->height);
384
385 #define COMPUTE_SHIFT_MASK(ix, rgb) \
386   compute_shift_mask(&shiftmasks[ix], sn->rgb##_mask)
387   COMPUTE_SHIFT_MASK(0, red);
388   COMPUTE_SHIFT_MASK(1, green);
389   COMPUTE_SHIFT_MASK(2, blue);
390
391   CANONICALISE_IMAGE(im, sn->width, sn->height, {
392     long xrgb= XGetPixel(sn, x, y);
393     int i;
394     rgb= 0;
395     for (i=0; i<3; i++) {
396       rgb <<= 8;
397       unsigned long sample=
398         ((xrgb << shiftmasks[i].lshift)
399               >> shiftmasks[i].rshift) & SAMPLEMASK;
400       rgb |= sample;
401       fputc(sample, screenshot_file);
402     }
403     if (ri)
404       CANONIMG_ALSO_STORERGB(ri);
405   });
406
407   sysassert(!ferror(screenshot_file));
408   sysassert(!fflush(screenshot_file));
409
410   return im;
411 }
412
413 static void prepare_ypp_client(void) {
414   CanonImage *test;
415   Snapshot *current=0;
416   
417   /* find the window and check it's on the right kind of screen */
418   raise_and_get_details();
419   wait_for_stability(&current,0,0, "checking current YPP client screen...");
420   test= convert_page(current, 0);
421   find_structure(test, &max_relevant_y);
422   check_correct_commodities();
423   free(test);
424   free_snapshot(&current);
425
426   progress("requesting status information...");
427   mouse_1_updown(250, wheight-10);
428   mouse_1_updown_here();
429   mouse_1_updown_here();
430   XSync(disp,False);
431   check_not_disturbed();
432   send_key(XK_slash);
433   send_key(XK_w);
434   send_key(XK_Return);
435   sync_after_input();
436 }
437
438 void take_screenshots(void) {
439   Snapshot *current=0, *last=0;
440
441   prepare_ypp_client();
442   
443   /* page to the top - keep pressing page up until the image stops changing */
444   set_focus_commodity();
445   wait_for_stability(&current,0, send_pgup_many,
446                      "paging up to top of commodity list...");
447
448   /* now to actually page down */
449   for (;;) {
450     debugf("paging page %d\n",npages);
451
452     if (!(npages < MAX_PAGES))
453       fatal("Paging down seems to generate too many pages - max is %d.",
454             MAX_PAGES);
455     
456     page_images[npages]= convert_page(current, 0);
457     free_snapshot(&last); last=current; current=0;
458
459     debugf("PAGING page %d converted\n",npages);
460
461     wait_for_stability(&current,last, 0,
462                        "collecting screenshot of page %d...",
463                        npages+1);
464
465     if (npages &&  /* first pagedown doesn't do much */
466         identical(current,last)) {
467       free_snapshot(&current);
468       break;
469     }
470
471     send_pgdown();
472     npages++;
473   }
474   progress("finishing with the YPP client...");
475   send_pgdown_torestore();
476
477   debugf("PAGING all done.\n");
478   progress_log("collected %d screenshots.",npages);
479 }    
480
481 void take_one_screenshot(void) {
482   Snapshot *current=0;
483
484   prepare_ypp_client();
485   wait_for_stability(&current,0,0, "taking screenshot...");
486   page0_rgbimage= alloc_rgb_image(current->width, current->height);
487   page_images[0]= convert_page(current, 0);
488   npages= 1;
489   progress_log("collected single screenshot.");
490 }
491
492 void set_yppclient_window(unsigned long wul) {
493   id= wul;
494 }
495
496 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
497
498 void find_yppclient_window(void) {
499   Window root, gotroot, gotparent;
500   int screen;
501   int nfound=0;
502   
503   if (id) return;
504   
505   progress("looking for YPP client window...");
506
507   static const char prefix[]= "Puzzle Pirates - ";
508   static const char onthe[]= " on the ";
509   static const char suffix[]= " ocean";
510 #define S(x) (sizeof((x))-1)
511
512   Atom wm_name= XInternAtom(disp,"WM_NAME",True);
513   xassert(wm_name != None);
514
515   for (screen=0; screen<ScreenCount(disp); screen++) {
516     debugfind("FINDYPP screen %d\n", screen);
517     root= RootWindow(disp,screen);
518     unsigned int nchildren1;
519     Window *children1=0;
520
521     xassert( XQueryTree(disp,root,
522                   &gotroot,&gotparent,
523                   &children1,&nchildren1) );
524     debugfind("FINDYPP screen %d nchildren1=%d\n", screen, nchildren1);
525
526     int i;
527     for (i=0; i<nchildren1; i++) {
528       Window w1= children1[i];
529       unsigned int nchildren2;
530       Window *children2=0;
531
532       xassert( XQueryTree(disp,w1,
533                           &gotroot,&gotparent,
534                           &children2,&nchildren2) );
535       debugfind("FINDYPP screen %d c1[%2d]=0x%08lx nchildren2=%d\n",
536                 screen, i, (unsigned long)w1, nchildren2);
537
538       int j;
539       for (j=-1; j<(int)nchildren2; j++) {
540         Window w2= j<0 ? w1 : children2[j];
541         debugfind("FINDYPP screen %d c1[%2d]=0x%08lx c2[%2d]=0x%08lx",
542                   screen, i, (unsigned long)w1, j, (unsigned long)w2);
543
544         int gotfmt;
545         Atom gottype;
546         unsigned long len, gotbytesafter;
547         char *title;
548         unsigned char *gottitle=0;
549         xassert( !XGetWindowProperty(disp,w2, wm_name,0,512, False,
550                                      AnyPropertyType,&gottype, &gotfmt, &len,
551                                      &gotbytesafter, &gottitle) );
552         title= (char*)gottitle;
553
554         if (DEBUGP(findypp)) {
555           debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
556           char *p;
557           for (p=title; p < title+len; p++) {
558             char c= *p;
559             if (c>=' ' && c<=126) fputc(c,debug);
560             else fprintf(debug,"\\x%02x",c & 0xff);
561           }
562           fputs("\": ",debug);
563         }
564
565 #define REQUIRE(pred)                                                      \
566         if (!(pred)) { debugfind(" failed test  %s\n", #pred); continue; } \
567         else
568
569         REQUIRE( gottype!=None );
570         REQUIRE( len );
571         REQUIRE( gotfmt==8 );
572
573         REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
574
575         char *spc1= strchr(  title        + S(prefix), ' ');  REQUIRE(spc1);
576         char *spc2= strrchr((title + len) - S(suffix), ' ');  REQUIRE(spc2);
577
578         REQUIRE( (title + len) - spc1  >= S(onthe)  + S(suffix) );
579         REQUIRE(  spc2         - title >= S(prefix) + S(onthe) );
580
581         REQUIRE( !memcmp(title,                   prefix, S(prefix)) );
582         REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix))  );
583         REQUIRE( !memcmp(spc1,                    onthe,  S(onthe))  );
584
585 #define ASSIGN(what, start, end) do {                                   \
586         sysassert( asprintf(&what, "%.*s", (end)-(start), start) >0 );  \
587      }while(0)
588         ASSIGN(pirate, title + S(prefix),  spc1);
589         ASSIGN(ocean,  spc1 + S(onthe),   (title + len) - S(suffix));
590
591         debugfind(" YES!\n");
592         id= w2;
593         nfound++;
594         progress_log("found YPP client (0x%lx):"
595                      " %s ocean - %s.",
596                      (unsigned long)id, ocean, pirate);
597       }
598       if (children2) XFree(children2);
599     }
600     if (children1) XFree(children1);
601   }
602   if (nfound>1)
603     fatal("Found several YPP clients."
604           " Close one, or specify the windowid with --window-id.\n");
605   if (nfound<1)
606     fatal("Did not find YPP client."
607           " Use --window-id and/or report this as a fault.\n");
608 }