2 * Interaction with the YPP client via X11
5 * This is part of ypp-sc-tools, a set of third-party tools for assisting
6 * players of Yohoho Puzzle Pirates.
8 * Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
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.
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.
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/>.
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.
29 * Only this file #includes the X11 headers, as they're quite
30 * pollutant of the namespace.
33 #include "structure.h"
36 #include <X11/extensions/XTest.h>
37 #include <X11/keysym.h>
38 #include <X11/Xutil.h>
40 #include <X11/extensions/XShm.h>
44 CanonImage *page_images[MAX_PAGES];
46 RgbImage *page0_rgbimage;
48 const char *ocean, *pirate;
50 static XWindowAttributes attr;
53 static struct timeval tv_startup;
54 static unsigned wwidth, wheight;
55 static int max_relevant_y= -1;
58 static XShmSegmentInfo shminfo;
60 DEBUG_DEFINE_DEBUGF(pages)
62 #define xassert(what) \
64 fatal("X11 operation unexpectedly failed." \
65 " %s:%d: %s\n", __FILE__,__LINE__,#what))
67 static KeyCode keycode(KeySym sym) {
68 return XKeysymToKeycode(disp,sym);
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) );
78 /*---------- pager ----------*/
80 typedef RgbImage Snapshot;
82 static double last_input;
83 static const double min_update_allowance= 0.25;
85 static double timestamp(void) {
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);
94 static void delay(double need_sleep) {
95 debugf("PAGING delay %f\n",need_sleep);
96 sysassert(! usleep(need_sleep * 1e6) );
99 static void sync_after_input(void) {
100 xassert( XSync(disp, False) );
101 last_input= timestamp();
104 static void translate_coords_toroot(int wx, int wy, int *rx, int *ry) {
106 xassert( XTranslateCoordinates(disp, id,attr.root, wx,wy, rx,ry, &dummy) );
109 static void check_client_window_all_on_screen(void) {
111 unsigned rwidth, rheight;
116 xassert( XGetGeometry(disp,attr.root, &dummy, &rxpos,&rypos,
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 &&
124 onroot.br.x < rwidth &&
125 onroot.br.y < rheight))
126 fatal("YPP client window is not entirely on the screen.");
129 static void check_not_disturbed(void) {
134 r= XCheckMaskEvent(disp, ~0, &ev);
135 if (r==False) return;
138 case VisibilityNotify:
139 if (ev.xvisibility.state != VisibilityUnobscured)
140 fatal("YPP client window has become obscured.");
142 case ConfigureNotify:
143 check_client_window_all_on_screen();
146 fatal("Focus left YPP client window.");
149 warning("focus entered YPP client window ?!");
152 fatal("Received unexpected X11 event (type code %d)!", ev.type);
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);
162 static void mouse_1_updown_here(void) {
163 check_not_disturbed();
164 XTestFakeButtonEvent(disp,1,1, 50);
165 XTestFakeButtonEvent(disp,1,0, 50);
167 static void mouse_1_updown(int x, int y) {
168 check_not_disturbed();
169 int screen= XScreenNumberOfScreen(attr.screen);
171 translate_coords_toroot(x,y, &xpos,&ypos);
172 XTestFakeMotionEvent(disp, screen, xpos,ypos, 0);
173 mouse_1_updown_here();
178 static void send_pgup_many(void) {
180 for (i=0; i<25; i++) {
184 debugf("PAGING PageUp x %d\n",i);
187 static void send_pgdown(void) {
190 debugf("PAGING PageDown\n");
193 static void send_pgdown_torestore(void) {
194 debugf("PAGING PageDown x %d\n", -pgupdown);
195 while (pgupdown < 0) {
202 static void free_snapshot(Snapshot **io) {
207 #define SAMPLEMASK 0xfful
213 static void compute_shift_mask(ShMask *sm, unsigned long ximage_mask) {
218 if (ximage_mask <= (SAMPLEMASK>>1)) {
219 sm->lshift++; ximage_mask <<= 1;
220 } else if (ximage_mask > SAMPLEMASK) {
221 sm->rshift++; ximage_mask >>= 1;
225 assert(!(sm->lshift && sm->rshift));
227 assert(sm->lshift < LONG_BIT);
228 assert(sm->rshift < LONG_BIT);
231 static void rtimestamp(double *t, const char *wh) {
232 double n= timestamp();
233 debugf("PAGING INTERVAL %f %s\n", n-*t, wh);
237 static void snapshot(Snapshot **output) {
238 XImage *im_use, *im_free=0;
240 ShMask shiftmasks[3];
242 debugf("PAGING snapshot\n");
244 double begin= timestamp();
246 rtimestamp(&begin, "XShmGetImage before");
247 xassert( XShmGetImage(disp,id,shmim, 0,0, AllPlanes) );
248 rtimestamp(&begin, "XShmGetImage");
250 size_t dsz= shmim->bytes_per_line * shmim->height;
251 im_use= im_free= mmalloc(sizeof(*im_use) + dsz);
253 im_free->data= (void*)(im_free+1);
254 memcpy(im_free->data, shmim->data, dsz);
255 rtimestamp(&begin, "mmalloc/memcpy");
257 rtimestamp(&begin, "XGetImage before");
258 xassert( im_use= im_free=
259 XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap) );
260 rtimestamp(&begin, "XGetImage");
263 #define COMPUTE_SHIFT_MASK(ix, rgb) \
264 compute_shift_mask(&shiftmasks[ix], im_use->rgb##_mask)
265 COMPUTE_SHIFT_MASK(0, red);
266 COMPUTE_SHIFT_MASK(1, green);
267 COMPUTE_SHIFT_MASK(2, blue);
270 *output= alloc_rgb_image(wwidth, wheight);
272 rtimestamp(&begin, "compute_shift_masks+alloc_rgb_image");
275 unsigned char *op= (*output)->data;
276 for (y=0; y<wheight; y++) {
277 for (x=0; x<wwidth; x++) {
278 long xrgb= XGetPixel(im_use,x,y);
279 for (i=0; i<3; i++) {
280 unsigned long sample=
281 ((xrgb << shiftmasks[i].lshift) >> shiftmasks[i].rshift)
288 rtimestamp(&begin,"w*h*XGetPixel");
290 XDestroyImage(im_free);
292 rtimestamp(&begin,"XDestroyImage");
293 check_not_disturbed();
295 debugf("PAGING snapshot done.\n");
298 static int identical(const Snapshot *a, const Snapshot *b) {
299 if (!(a->w == b->w &&
303 int compare_to= a->h;
304 if (max_relevant_y && compare_to > max_relevant_y)
305 compare_to= max_relevant_y;
307 return !memcmp(a->data, b->data, a->w * 3 * compare_to);
310 static void wait_for_stability(Snapshot **output,
311 const Snapshot *previously,
312 void (*with_keypress)(void),
313 const char *fmt, ...)
316 static void wait_for_stability(Snapshot **output,
317 const Snapshot *previously,
318 void (*with_keypress)(void),
319 const char *fmt, ...) {
324 /* waits longer if we're going to return an image identical to previously
325 * if previously==0, all images are considered identical to it */
328 sysassert( vasprintf(&doing,fmt,al) >=0 );
329 progress("%s",doing);
331 debugf("PAGING wait_for_stability"
332 " last_input=%f previously=%p `%s'\n",
333 last_input, previously, doing);
336 double at_snapshot= timestamp();
337 double need_sleep= min_update_allowance - (at_snapshot - last_input);
338 if (need_sleep > 0) { delay(need_sleep); continue; }
342 if (!with_keypress &&
343 !(previously && identical(*output,previously))) {
344 debugf("PAGING wait_for_stability simple\n");
348 if (last && identical(*output,last)) {
349 debugf("PAGING wait_for_stability stabilised\n");
353 progress_spinner("%s",doing);
355 debugf("PAGING wait_for_stability retry\n");
357 free_snapshot(&last); last=*output; *output=0;
365 free_snapshot(&last);
367 debugf("PAGING wait_for_stability done.\n");
371 static void raise_and_get_details(void) {
372 int evbase,errbase,majver,minver;
376 progress("raising and checking YPP client window...");
378 debugf("PAGING raise_and_get_details\n");
380 int xtest= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
381 if (!xtest) fatal("X server does not support the XTEST extension.");
383 xassert( XRaiseWindow(disp, id) );
384 /* in case VisibilityNotify triggers right away before we have had a
385 * change to raise; to avoid falsely detecting lowering in that case */
387 xassert( XSelectInput(disp, id,
392 xassert( XRaiseWindow(disp, id) );
393 /* in case the window was lowered between our Raise and our SelectInput;
394 * to avoid failing to detect that lowering */
396 xassert( XGetWindowAttributes(disp, id, &attr) );
397 xassert( XGetGeometry(disp,id, &attr.root,
398 &wxpos,&wypos, &wwidth,&wheight,
401 if (!(wwidth >= 320 && wheight >= 320))
402 fatal("YPP client window is implausibly small?");
404 check_client_window_all_on_screen();
406 int shm= XShmQueryExtension(disp);
407 debugf("PAGING shm=%d\n",shm);
409 xassert( shmim= XShmCreateImage(disp, attr.visual, attr.depth, ZPixmap,
410 0,&shminfo, wwidth,wheight) );
412 sigset_t oldset, all;
414 sysassert(! sigprocmask(SIG_BLOCK,&all,&oldset) );
418 sysassert(! pipe(pfd) );
419 sysassert( (cleaner= fork()) != -1 );
421 sysassert(! close(pfd[1]) );
423 int r= read(pfd[0], &shminfo.shmid, sizeof(shminfo.shmid));
425 if (r==sizeof(shminfo.shmid)) break;
426 assert(r==-1 && errno==EINTR);
430 int r= read(pfd[0],&bc,1);
432 assert(r==-1 && errno==EINTR);
434 sysassert(! shmctl(shminfo.shmid,IPC_RMID,0) );
437 sysassert(! close(pfd[0]) );
439 sysassert(! sigprocmask(SIG_SETMASK,&oldset,0) );
441 assert(shmim->height == wheight);
442 sysassert( (shminfo.shmid=
443 shmget(IPC_PRIVATE, shmim->bytes_per_line * wheight,
444 IPC_CREAT|0600)) >= 0 );
446 sysassert( write(pfd[1],&shminfo.shmid,sizeof(shminfo.shmid)) ==
447 sizeof(shminfo.shmid) );
448 sysassert( shminfo.shmaddr= shmat(shminfo.shmid,0,0) );
449 shmim->data= shminfo.shmaddr;
450 shminfo.readOnly= False;
451 xassert( XShmAttach(disp,&shminfo) );
453 close(pfd[1]); /* causes IPC_RMID */
457 static void set_focus_commodity(void) {
458 int screen= XScreenNumberOfScreen(attr.screen);
460 progress("taking control of YPP client window...");
462 debugf("PAGING set_focus\n");
464 mouse_1_updown(160,160);
468 xassert( XSelectInput(disp, id,
470 VisibilityChangeMask|
475 translate_coords_toroot(10,10, &xpos,&ypos);
476 XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
480 debugf("PAGING raise_and_set_focus done.\n");
483 static CanonImage *convert_page(Snapshot *sn, RgbImage *ri) {
486 fprintf(screenshot_file,
489 "255\n", sn->w, sn->h);
491 CANONICALISE_IMAGE(im, sn->w, sn->h, {
494 for (i=0; i<3; i++) {
496 unsigned long sample= RI_PIXEL(sn,x,y)[i];
498 fputc(sample, screenshot_file);
501 CANONIMG_ALSO_STORERGB(ri);
504 sysassert(!ferror(screenshot_file));
505 sysassert(!fflush(screenshot_file));
510 static void prepare_ypp_client(void) {
514 /* find the window and check it's on the right kind of screen */
515 raise_and_get_details();
516 wait_for_stability(¤t,0,0, "checking current YPP client screen...");
518 test= convert_page(current, 0);
519 find_structure(test, &max_relevant_y);
520 check_correct_commodities();
521 Rect sunshine= find_sunshine_widget();
523 progress("poking client...");
524 mouse_1_updown((sunshine.tl.x + sunshine.br.x) / 2,
525 (sunshine.tl.y*9 + sunshine.br.y) / 10);
529 wait_for_stability(¤t,0,0, "checking basic YPP client screen...");
530 mouse_1_updown(250, wheight-10);
531 mouse_1_updown_here();
532 mouse_1_updown_here();
534 check_not_disturbed();
541 wait_for_stability(&status,current,0, "awaiting status information...");
542 free_snapshot(¤t);
543 free_snapshot(&status);
546 void take_screenshots(void) {
547 Snapshot *current=0, *last=0;
549 prepare_ypp_client();
551 /* page to the top - keep pressing page up until the image stops changing */
552 set_focus_commodity();
553 wait_for_stability(¤t,0, send_pgup_many,
554 "paging up to top of commodity list...");
556 /* now to actually page down */
558 debugf("paging page %d\n",npages);
560 if (!(npages < MAX_PAGES))
561 fatal("Paging down seems to generate too many pages - max is %d.",
564 page_images[npages]= convert_page(current, 0);
565 free_snapshot(&last); last=current; current=0;
567 debugf("PAGING page %d converted\n",npages);
569 wait_for_stability(¤t,last, 0,
570 "collecting screenshot of page %d...",
573 if (npages && /* first pagedown doesn't do much */
574 identical(current,last)) {
575 free_snapshot(¤t);
582 progress("finishing with the YPP client...");
583 send_pgdown_torestore();
585 debugf("PAGING all done.\n");
586 progress_log("collected %d screenshots.",npages);
589 void take_one_screenshot(void) {
592 prepare_ypp_client();
593 wait_for_stability(¤t,0,0, "taking screenshot...");
594 page0_rgbimage= alloc_rgb_image(current->w, current->h);
595 page_images[0]= convert_page(current, page0_rgbimage);
597 progress_log("collected single screenshot.");
600 void set_yppclient_window(unsigned long wul) {
604 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
606 void find_yppclient_window(void) {
607 Window root, gotroot, gotparent;
613 progress("looking for YPP client window...");
615 static const char prefix[]= "Puzzle Pirates - ";
616 static const char onthe[]= " on the ";
617 static const char suffix[]= " ocean";
618 #define S(x) (sizeof((x))-1)
620 Atom wm_name= XInternAtom(disp,"WM_NAME",True);
621 xassert(wm_name != None);
623 for (screen=0; screen<ScreenCount(disp); screen++) {
624 debugfind("FINDYPP screen %d\n", screen);
625 root= RootWindow(disp,screen);
626 unsigned int nchildren1;
629 xassert( XQueryTree(disp,root,
631 &children1,&nchildren1) );
632 debugfind("FINDYPP screen %d nchildren1=%d\n", screen, nchildren1);
635 for (i=0; i<nchildren1; i++) {
636 Window w1= children1[i];
637 unsigned int nchildren2;
640 xassert( XQueryTree(disp,w1,
642 &children2,&nchildren2) );
643 debugfind("FINDYPP screen %d c1[%2d]=0x%08lx nchildren2=%d\n",
644 screen, i, (unsigned long)w1, nchildren2);
647 for (j=-1; j<(int)nchildren2; j++) {
648 Window w2= j<0 ? w1 : children2[j];
649 debugfind("FINDYPP screen %d c1[%2d]=0x%08lx c2[%2d]=0x%08lx",
650 screen, i, (unsigned long)w1, j, (unsigned long)w2);
654 unsigned long len, gotbytesafter;
656 unsigned char *gottitle=0;
657 xassert( !XGetWindowProperty(disp,w2, wm_name,0,512, False,
658 AnyPropertyType,&gottype, &gotfmt, &len,
659 &gotbytesafter, &gottitle) );
660 title= (char*)gottitle;
662 if (DEBUGP(findypp)) {
663 debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
665 for (p=title; p < title+len; p++) {
667 if (c>=' ' && c<=126) fputc(c,debug);
668 else fprintf(debug,"\\x%02x",c & 0xff);
673 #define REQUIRE(pred) \
674 if (!(pred)) { debugfind(" failed test %s\n", #pred); continue; } \
677 REQUIRE( gottype!=None );
679 REQUIRE( gotfmt==8 );
681 REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
683 char *spc1= strchr( title + S(prefix), ' '); REQUIRE(spc1);
684 char *spc2= strrchr((title + len) - S(suffix), ' '); REQUIRE(spc2);
686 REQUIRE( (title + len) - spc1 >= S(onthe) + S(suffix) );
687 REQUIRE( spc2 - title >= S(prefix) + S(onthe) );
689 REQUIRE( !memcmp(title, prefix, S(prefix)) );
690 REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix)) );
691 REQUIRE( !memcmp(spc1, onthe, S(onthe)) );
693 #define ASSIGN(what, start, end) \
694 what= masprintf("%.*s", (end)-(start), start); \
695 if (o_##what) REQUIRE( !strcasecmp(o_##what, what) ); \
698 ASSIGN(ocean, spc1 + S(onthe), (title + len) - S(suffix));
699 ASSIGN(pirate, title + S(prefix), spc1);
701 debugfind(" YES!\n");
704 progress_log("found YPP client (0x%lx):"
706 (unsigned long)id, ocean, pirate);
708 if (children2) XFree(children2);
710 if (children1) XFree(children1);
713 fatal("Found several possible YPP clients. Close one,\n"
714 " disambiguate with --pirate or --ocean,"
715 " or specify --window-id.\n");
717 fatal("Did not find %sYPP client."
718 " Use --window-id and/or report this as a fault.\n",
719 o_ocean || o_pirate ? "matching ": "");