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