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