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