chiark / gitweb /
WIP island determination; pixmap handling in progress
[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
156 static int pgupdown;
157
158 static void send_pgup_many(void) {
159   int i;
160   for (i=0; i<25; i++) {
161     send_key(XK_Prior);
162     pgupdown--;
163   }
164   debugf("PAGING   PageUp x %d\n",i);
165   sync_after_input();
166 }
167 static void send_pgdown(void) {
168   send_key(XK_Next);
169   pgupdown++;
170   debugf("PAGING   PageDown\n");
171   sync_after_input();
172 }
173 static void send_pgdown_torestore(void) {
174   debugf("PAGING   PageDown x %d\n", -pgupdown);
175   while (pgupdown < 0) {
176     send_key(XK_Next);
177     pgupdown++;
178   }
179   sync_after_input();
180 }
181
182 static void free_snapshot(Snapshot **io) {
183   if (*io) XDestroyImage(*io);
184   *io= 0;
185 }
186
187 static void snapshot(Snapshot **output) {
188   free_snapshot(output);
189
190   debugf("PAGING   snapshot\n");
191
192   timestamp();
193   *output= XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap);
194   timestamp();
195
196   check_not_disturbed();
197
198   debugf("PAGING   snapshot done.\n");
199 }
200
201 static int identical(const Snapshot *a, const Snapshot *b) {
202   if (!(a->width == b->width &&
203         a->height == b->height &&
204         a->bytes_per_line == b->bytes_per_line &&
205         a->format == b->format))
206     return 0;
207
208   int compare_to= a->height;
209   if (max_relevant_y && compare_to > max_relevant_y)
210     compare_to= max_relevant_y;
211   
212   return !memcmp(a->data, b->data, a->bytes_per_line * compare_to);
213 }
214
215 static void wait_for_stability(Snapshot **output,
216                                const Snapshot *previously,
217                                void (*with_keypress)(void),
218                                const char *fmt, ...)
219      FMT(4,5);
220
221 static void wait_for_stability(Snapshot **output,
222                                const Snapshot *previously,
223                                void (*with_keypress)(void),
224                                const char *fmt, ...) {
225   va_list al;
226   va_start(al,fmt);
227
228   Snapshot *last=0;
229   /* waits longer if we're going to return an image identical to previously
230    * if previously==0, all images are considered identical to it */
231
232   debugf("PAGING  wait_for_stability"
233           "  last_input=%f previously=%p\n",
234           last_input, previously);
235
236   char *doing;
237   sysassert( vasprintf(&doing,fmt,al) >=0);
238
239   progress("%s",doing);
240
241   for (;;) {
242     double at_snapshot= timestamp();
243     double need_sleep= min_update_allowance - (at_snapshot - last_input);
244     if (need_sleep > 0) { delay(need_sleep); continue; }
245
246     snapshot(output);
247
248     if (!with_keypress &&
249         !(previously && identical(*output,previously))) {
250       debugf("PAGING  wait_for_stability  simple\n");
251       break;
252     }
253
254     if (last && identical(*output,last)) {
255       debugf("PAGING  wait_for_stability  stabilised\n");
256       break;
257     }
258     
259     progress_spinner("%s",doing);
260
261     debugf("PAGING  wait_for_stability  retry\n");
262
263     free_snapshot(&last); last=*output; *output=0;
264
265     if (with_keypress)
266       with_keypress();
267
268     delay(0.5);
269   }
270
271   free_snapshot(&last);
272   free(doing);
273   debugf("PAGING  wait_for_stability done.\n");
274   va_end(al);
275 }
276
277 static void raise_and_get_details(void) {
278   int evbase,errbase,majver,minver;
279   int wxpos, wypos;
280   unsigned bd,depth;
281
282   progress("raising and checking YPP client window...");
283
284   debugf("PAGING raise_and_get_details\n");
285
286   int xtest= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
287   if (!xtest) fatal("X server does not support the XTEST extension.");
288
289   xassert( XRaiseWindow(disp, id) );
290   /* in case VisibilityNotify triggers right away before we have had a
291    * change to raise; to avoid falsely detecting lowering in that case */
292   
293   xassert( XSelectInput(disp, id,
294                         StructureNotifyMask|
295                         VisibilityChangeMask
296                         ) );
297
298   xassert( XRaiseWindow(disp, id) );
299   /* in case the window was lowered between our Raise and our SelectInput;
300    * to avoid failing to detect that lowering */
301
302   xassert( XGetWindowAttributes(disp, id, &attr) );
303   xassert( XGetGeometry(disp,id, &attr.root,
304                         &wxpos,&wypos, &wwidth,&wheight,
305                         &bd,&depth) );
306
307   if (!(wwidth >= 320 && wheight >= 320))
308     fatal("YPP client window is implausibly small?");
309
310   check_client_window_all_on_screen();
311 }
312
313 static void set_focus(void) {
314   int screen= XScreenNumberOfScreen(attr.screen);
315
316   progress("taking control of YPP client window...");
317
318   debugf("PAGING set_focus\n");
319
320   int xpos, ypos;
321   translate_coords_toroot(160,160, &xpos,&ypos);
322   XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
323
324   XTestFakeButtonEvent(disp,1,1, 50);
325   XTestFakeButtonEvent(disp,1,0, 50);
326
327   sync_after_input();
328
329   delay(0.5);
330   xassert( XSelectInput(disp, id,
331                         StructureNotifyMask|
332                         VisibilityChangeMask|
333                         FocusChangeMask
334                         ) );
335
336   translate_coords_toroot(10,10, &xpos,&ypos);
337   XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
338
339   sync_after_input();
340
341   debugf("PAGING raise_and_set_focus done.\n");
342 }
343
344 #define SAMPLEMASK 0xfful
345
346 typedef struct {
347   int lshift, rshift;
348 } ShMask;
349
350 static void compute_shift_mask(ShMask *sm, unsigned long ximage_mask) {
351   sm->lshift= 0;
352   sm->rshift= 0;
353   
354   for (;;) {
355     if (ximage_mask <= (SAMPLEMASK>>1)) {
356       sm->lshift++;  ximage_mask <<= 1;
357     } else if (ximage_mask > SAMPLEMASK) {
358       sm->rshift++;  ximage_mask >>= 1;
359     } else {
360       break;
361     }
362     assert(!(sm->lshift && sm->rshift));
363   }
364   assert(sm->lshift < LONG_BIT);
365   assert(sm->rshift < LONG_BIT);
366 }
367
368 static CanonImage *convert_page(Snapshot *sn, RgbImage *ri) {
369   ShMask shiftmasks[3];
370   CanonImage *im;
371
372   fprintf(screenshot_file,
373           "P6\n"
374           "%d %d\n"
375           "255\n", sn->width, sn->height);
376
377 #define COMPUTE_SHIFT_MASK(ix, rgb) \
378   compute_shift_mask(&shiftmasks[ix], sn->rgb##_mask)
379   COMPUTE_SHIFT_MASK(0, red);
380   COMPUTE_SHIFT_MASK(1, green);
381   COMPUTE_SHIFT_MASK(2, blue);
382
383   CANONICALISE_IMAGE(im, sn->width, sn->height, {
384     long xrgb= XGetPixel(sn, x, y);
385     int i;
386     rgb= 0;
387     for (i=0; i<3; i++) {
388       rgb <<= 8;
389       unsigned long sample=
390         ((xrgb << shiftmasks[i].lshift)
391               >> shiftmasks[i].rshift) & SAMPLEMASK;
392       rgb |= sample;
393       fputc(sample, screenshot_file);
394     }
395     if (ri)
396       CANONIMG_ALSO_STORERGB(ri);
397   });
398
399   sysassert(!ferror(screenshot_file));
400   sysassert(!fflush(screenshot_file));
401
402   return im;
403 }
404
405 void take_screenshots(void) {
406   Snapshot *current=0, *last=0;
407   CanonImage *test;
408
409   /* find the window and check it's on the right kind of screen */
410   raise_and_get_details();
411   wait_for_stability(&current,0,0, "checking current YPP client screen...");
412   test= convert_page(current, 0);
413   find_structure(test, &max_relevant_y);
414   check_correct_commodities();
415   free(test);
416
417   /* page to the top - keep pressing page up until the image stops changing */
418   set_focus();
419   wait_for_stability(&current,0, send_pgup_many,
420                      "paging up to top of commodity list...");
421
422   /* now to actually page down */
423   for (;;) {
424     debugf("paging page %d\n",npages);
425
426     if (!(npages < MAX_PAGES))
427       fatal("Paging down seems to generate too many pages - max is %d.",
428             MAX_PAGES);
429     
430     page_images[npages]= convert_page(current, 0);
431     free_snapshot(&last); last=current; current=0;
432
433     debugf("PAGING page %d converted\n",npages);
434
435     wait_for_stability(&current,last, 0,
436                        "collecting screenshot of page %d...",
437                        npages+1);
438
439     if (npages &&  /* first pagedown doesn't do much */
440         identical(current,last)) {
441       free_snapshot(&current);
442       break;
443     }
444
445     send_pgdown();
446     npages++;
447   }
448   progress("finishing with the YPP client...");
449   send_pgdown_torestore();
450
451   debugf("PAGING all done.\n");
452   progress_log("collected %d screenshots.",npages);
453 }    
454
455 void take_one_screenshot(void) {
456   Snapshot *current=0;
457   
458   raise_and_get_details();
459   sync_after_input();
460   wait_for_stability(&current,0,0, "taking screenshot...");
461   page0_rgbimage= alloc_rgb_image(current->width, current->height);
462   page_images[0]= convert_page(current, 0);
463   npages= 1;
464   progress_log("collected single screenshot.");
465 }
466
467 void set_yppclient_window(unsigned long wul) {
468   id= wul;
469 }
470
471 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
472
473 void find_yppclient_window(void) {
474   Window root, gotroot, gotparent;
475   int screen;
476   int nfound=0;
477   
478   if (id) return;
479   
480   progress("looking for YPP client window...");
481
482   static const char prefix[]= "Puzzle Pirates - ";
483   static const char onthe[]= " on the ";
484   static const char suffix[]= " ocean";
485 #define S(x) (sizeof((x))-1)
486
487   Atom wm_name= XInternAtom(disp,"WM_NAME",True);
488   xassert(wm_name != None);
489
490   for (screen=0; screen<ScreenCount(disp); screen++) {
491     debugfind("FINDYPP screen %d\n", screen);
492     root= RootWindow(disp,screen);
493     unsigned int nchildren1;
494     Window *children1=0;
495
496     xassert( XQueryTree(disp,root,
497                   &gotroot,&gotparent,
498                   &children1,&nchildren1) );
499     debugfind("FINDYPP screen %d nchildren1=%d\n", screen, nchildren1);
500
501     int i;
502     for (i=0; i<nchildren1; i++) {
503       Window w1= children1[i];
504       unsigned int nchildren2;
505       Window *children2=0;
506
507       xassert( XQueryTree(disp,w1,
508                           &gotroot,&gotparent,
509                           &children2,&nchildren2) );
510       debugfind("FINDYPP screen %d c1[%2d]=0x%08lx nchildren2=%d\n",
511                 screen, i, (unsigned long)w1, nchildren2);
512
513       int j;
514       for (j=-1; j<(int)nchildren2; j++) {
515         Window w2= j<0 ? w1 : children2[j];
516         debugfind("FINDYPP screen %d c1[%2d]=0x%08lx c2[%2d]=0x%08lx",
517                   screen, i, (unsigned long)w1, j, (unsigned long)w2);
518
519         int gotfmt;
520         Atom gottype;
521         unsigned long len, gotbytesafter;
522         char *title;
523         unsigned char *gottitle=0;
524         xassert( !XGetWindowProperty(disp,w2, wm_name,0,512, False,
525                                      AnyPropertyType,&gottype, &gotfmt, &len,
526                                      &gotbytesafter, &gottitle) );
527         title= (char*)gottitle;
528
529         if (DEBUGP(findypp)) {
530           debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
531           char *p;
532           for (p=title; p < title+len; p++) {
533             char c= *p;
534             if (c>=' ' && c<=126) fputc(c,debug);
535             else fprintf(debug,"\\x%02x",c & 0xff);
536           }
537           fputs("\": ",debug);
538         }
539
540 #define REQUIRE(pred)                                                      \
541         if (!(pred)) { debugfind(" failed test  %s\n", #pred); continue; } \
542         else
543
544         REQUIRE( gottype!=None );
545         REQUIRE( len );
546         REQUIRE( gotfmt==8 );
547
548         REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
549
550         char *spc1= strchr(  title        + S(prefix), ' ');  REQUIRE(spc1);
551         char *spc2= strrchr((title + len) - S(suffix), ' ');  REQUIRE(spc2);
552
553         REQUIRE( (title + len) - spc1  >= S(onthe)  + S(suffix) );
554         REQUIRE(  spc2         - title >= S(prefix) + S(onthe) );
555
556         REQUIRE( !memcmp(title,                   prefix, S(prefix)) );
557         REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix))  );
558         REQUIRE( !memcmp(spc1,                    onthe,  S(onthe))  );
559
560 #define ASSIGN(what, start, end) do {                                   \
561         sysassert( asprintf(&what, "%.*s", (end)-(start), start) >0 );  \
562      }while(0)
563         ASSIGN(pirate, title + S(prefix),  spc1);
564         ASSIGN(ocean,  spc1 + S(onthe),   (title + len) - S(suffix));
565
566         debugfind(" YES!\n");
567         id= w2;
568         nfound++;
569         progress_log("found YPP client (0x%lx):"
570                      " %s ocean - %s.",
571                      (unsigned long)id, ocean, pirate);
572       }
573       if (children2) XFree(children2);
574     }
575     if (children1) XFree(children1);
576   }
577   if (nfound>1)
578     fatal("Found several YPP clients."
579           " Close one, or specify the windowid with --window-id.\n");
580   if (nfound<1)
581     fatal("Did not find YPP client."
582           " Use --window-id and/or report this as a fault.\n");
583 }