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