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 const char *ocean, *pirate;
46 static XWindowAttributes attr;
49 static struct timeval tv_startup;
50 static unsigned wwidth, wheight;
51 static int max_relevant_y= -1;
52 static Point commod_focus_point, commod_page_point, commod_focuslast_point;
55 static XShmSegmentInfo shminfo;
57 DEBUG_DEFINE_DEBUGF(pages)
59 #define xassert(what) \
61 fatal("X11 operation unexpectedly failed." \
62 " %s:%d: %s\n", __FILE__,__LINE__,#what))
64 static KeyCode keycode(KeySym sym) {
65 return XKeysymToKeycode(disp,sym);
68 void screenshot_startup(void) {
69 progress("starting...");
70 disp= XOpenDisplay(0);
71 if (!disp) fatal("Unable to open X11 display.");
72 sysassert(! gettimeofday(&tv_startup,0) );
75 /*---------- pager ----------*/
77 typedef RgbImage Snapshot;
79 static double last_input;
80 static const double min_update_allowance= 0.25;
82 static double timestamp(void) {
85 sysassert(! gettimeofday(&tv,0) );
86 double t= (tv.tv_sec - tv_startup.tv_sec) +
87 (tv.tv_usec - tv_startup.tv_usec) * 1e-6;
88 debugf("PAGING %f\n",t);
91 static void delay(double need_sleep) {
92 debugf("PAGING delay %f\n",need_sleep);
93 sysassert(! usleep(need_sleep * 1e6) );
96 static void sync_after_input(void) {
97 xassert( XSync(disp, False) );
98 last_input= timestamp();
101 static void translate_coords_toroot(int wx, int wy, int *rx, int *ry) {
103 xassert( XTranslateCoordinates(disp, id,attr.root, wx,wy, rx,ry, &dummy) );
105 static void translate_coords_toroot_p(Point w, int *rx, int *ry) {
106 translate_coords_toroot(w.x, w.y, rx, ry);
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, 0);
160 XTestFakeKeyEvent(disp, keycode(sym),0, 0);
162 static void send_mouse_1_updown_here(void) {
163 check_not_disturbed();
164 XTestFakeButtonEvent(disp,1,1, 0);
165 XTestFakeButtonEvent(disp,1,0, 0);
167 static void send_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 send_mouse_1_updown_here();
175 static void pgdown_by_mouse(void) {
176 check_not_disturbed();
177 debugf("PAGING Mouse\n");
178 send_mouse_1_updown_here();
184 static void send_pgup_many(void) {
186 for (i=0; i<25; i++) {
190 debugf("PAGING PageUp x %d\n",i);
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);
229 debugf("SHIFTMASK %p={.lshift=%d, .rshift=%d} image_mask=%lx\n",
230 sm, sm->lshift, sm->rshift, ximage_mask);
233 static void rtimestamp(double *t, const char *wh) {
234 double n= timestamp();
235 debugf("PAGING INTERVAL %f %s\n", n-*t, wh);
239 static void snapshot(Snapshot **output) {
240 XImage *im_use, *im_free=0;
242 ShMask shiftmasks[3];
244 debugf("PAGING snapshot\n");
246 double begin= timestamp();
248 rtimestamp(&begin, "XShmGetImage before");
249 xassert( XShmGetImage(disp,id,shmim, 0,0, AllPlanes) );
250 rtimestamp(&begin, "XShmGetImage");
252 size_t dsz= shmim->bytes_per_line * shmim->height;
253 im_use= im_free= mmalloc(sizeof(*im_use) + dsz);
255 im_free->data= (void*)(im_free+1);
256 memcpy(im_free->data, shmim->data, dsz);
257 rtimestamp(&begin, "mmalloc/memcpy");
259 rtimestamp(&begin, "XGetImage before");
260 xassert( im_use= im_free=
261 XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap) );
262 rtimestamp(&begin, "XGetImage");
265 #define COMPUTE_SHIFT_MASK(ix, rgb) \
266 compute_shift_mask(&shiftmasks[ix], im_use->rgb##_mask)
267 COMPUTE_SHIFT_MASK(0, blue);
268 COMPUTE_SHIFT_MASK(1, green);
269 COMPUTE_SHIFT_MASK(2, red);
272 *output= alloc_rgb_image(wwidth, wheight);
274 rtimestamp(&begin, "compute_shift_masks+alloc_rgb_image");
277 uint32_t *op32= (*output)->data;
278 for (y=0; y<wheight; y++) {
279 if (im_use->xoffset == 0 &&
280 im_use->format == ZPixmap &&
281 im_use->byte_order == LSBFirst &&
282 im_use->depth == 24 &&
283 im_use->bits_per_pixel == 32 &&
284 im_use->red_mask == 0x0000ffU &&
285 im_use->green_mask == 0x00ff00U &&
286 im_use->blue_mask == 0xff0000U) {
287 const char *p= im_use->data + y * im_use->bytes_per_line;
288 // debugf("optimised copy y=%d",y);
289 memcpy(op32, p, wwidth*sizeof(*op32));
292 for (x=0; x<wwidth; x++) {
293 long xrgb= XGetPixel(im_use,x,y);
295 for (i=0; i<3; i++) {
298 ((xrgb << shiftmasks[i].lshift) >> shiftmasks[i].rshift)
306 rtimestamp(&begin,"w*h*XGetPixel");
308 XDestroyImage(im_free);
310 rtimestamp(&begin,"XDestroyImage");
311 check_not_disturbed();
313 debugf("PAGING snapshot done.\n");
316 static int identical(const Snapshot *a, const Snapshot *b) {
317 if (!(a->w == b->w &&
321 int compare_to= a->h;
322 if (max_relevant_y>=0 && compare_to > max_relevant_y)
323 compare_to= max_relevant_y;
325 return !memcmp(a->data, b->data, a->w * 3 * compare_to);
328 static void wait_for_stability(Snapshot **output,
329 const Snapshot *previously,
330 void (*with_keypress)(void),
331 const char *fmt, ...)
334 static void wait_for_stability(Snapshot **output,
335 const Snapshot *previously,
336 void (*with_keypress)(void),
337 const char *fmt, ...) {
343 /* waits longer if we're going to return an image identical to previously
344 * if previously==0, all images are considered identical to it */
347 sysassert( vasprintf(&doing,fmt,al) >=0 );
349 debugf("PAGING wait_for_stability"
350 " last_input=%f previously=%p `%s'\n",
351 last_input, previously, doing);
353 double max_interval= 5.000;
354 double min_interval= 0.100;
356 progress_spinner("%s",doing);
358 double since_last_input= timestamp() - last_input;
359 double this_interval= min_interval - since_last_input;
360 if (this_interval > max_interval) this_interval= max_interval;
362 if (this_interval >= 0)
363 delay(this_interval);
368 debugf("PAGING wait_for_stability first...\n");
369 last=*output; *output=0;
370 } else if (!identical(*output,last)) {
371 debugf("PAGING wait_for_stability changed...\n");
372 free_snapshot(&last); last=*output; *output=0;
374 if (!with_keypress) {
382 identical(*output,previously) ? 5
384 debugf("PAGING wait_for_stability nidentical=%d threshold=%d\n",
385 nidentical, threshold);
386 if (nidentical >= threshold)
397 free_snapshot(&last);
399 debugf("PAGING wait_for_stability done.\n");
403 static void raise_and_get_details(void) {
404 int evbase,errbase,majver,minver;
408 progress("raising and checking YPP client window...");
410 debugf("PAGING raise_and_get_details\n");
412 int xtest= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
413 if (!xtest) fatal("X server does not support the XTEST extension.");
415 xassert( XRaiseWindow(disp, id) );
416 /* in case VisibilityNotify triggers right away before we have had a
417 * change to raise; to avoid falsely detecting lowering in that case */
419 xassert( XSelectInput(disp, id,
424 xassert( XRaiseWindow(disp, id) );
425 /* in case the window was lowered between our Raise and our SelectInput;
426 * to avoid failing to detect that lowering */
428 xassert( XGetWindowAttributes(disp, id, &attr) );
429 xassert( XGetGeometry(disp,id, &attr.root,
430 &wxpos,&wypos, &wwidth,&wheight,
433 if (!(wwidth >= 320 && wheight >= 320))
434 fatal("YPP client window is implausibly small?");
437 fatal("Display is not 24bpp.");
439 check_client_window_all_on_screen();
443 int shm= XShmQueryVersion(disp, &major,&minor,&shmpixmaps);
444 debugf("PAGING shm=%d %d.%d pixmaps=%d\n",shm,major,minor,shmpixmaps);
446 xassert( shmim= XShmCreateImage(disp, attr.visual, attr.depth, ZPixmap,
447 0,&shminfo, wwidth,wheight) );
449 sigset_t oldset, all;
451 sysassert(! sigprocmask(SIG_BLOCK,&all,&oldset) );
455 sysassert(! pipe(pfd) );
456 sysassert( (cleaner= fork()) != -1 );
458 sysassert(! close(pfd[1]) );
460 int r= read(pfd[0], &shminfo.shmid, sizeof(shminfo.shmid));
462 if (r==sizeof(shminfo.shmid)) break;
463 assert(r==-1 && errno==EINTR);
467 int r= read(pfd[0],&bc,1);
469 assert(r==-1 && errno==EINTR);
471 sysassert(! shmctl(shminfo.shmid,IPC_RMID,0) );
474 sysassert(! close(pfd[0]) );
476 sysassert(! sigprocmask(SIG_SETMASK,&oldset,0) );
478 assert(shmim->height == wheight);
479 sysassert( (shminfo.shmid=
480 shmget(IPC_PRIVATE, shmim->bytes_per_line * wheight,
481 IPC_CREAT|0600)) >= 0 );
483 sysassert( write(pfd[1],&shminfo.shmid,sizeof(shminfo.shmid)) ==
484 sizeof(shminfo.shmid) );
485 sysassert( shminfo.shmaddr= shmat(shminfo.shmid,0,0) );
486 shmim->data= shminfo.shmaddr;
487 shminfo.readOnly= False;
488 xassert( XShmAttach(disp,&shminfo) );
490 close(pfd[1]); /* causes IPC_RMID */
494 static void set_focus_commodity(void) {
495 int screen= XScreenNumberOfScreen(attr.screen);
497 progress("taking control of YPP client window...");
499 debugf("PAGING set_focus\n");
501 send_mouse_1_updown(commod_focus_point.x, commod_focus_point.y);
505 xassert( XSelectInput(disp, id,
507 VisibilityChangeMask|
512 translate_coords_toroot_p(commod_page_point, &xpos,&ypos);
513 XTestFakeMotionEvent(disp, screen, xpos,ypos, 0);
517 debugf("PAGING raise_and_set_focus done.\n");
520 static CanonImage *convert_page(const Snapshot *sn, RgbImage **rgb_r) {
524 fwrite_ppmraw(screenshot_file, sn);
526 const Rgb *pixel= sn->data;
527 CANONICALISE_IMAGE(im, sn->w, sn->h, ri, {
531 sysassert(!ferror(screenshot_file));
532 sysassert(!fflush(screenshot_file));
534 if (rgb_r) *rgb_r= ri;
540 static void prepare_ypp_client(void) {
544 /* find the window and check it's on the right kind of screen */
545 raise_and_get_details();
546 wait_for_stability(¤t,0,0, "checking current YPP client screen...");
548 test= convert_page(current,0);
549 find_structure(test,0, &max_relevant_y,
552 &commod_focuslast_point);
553 check_correct_commodities();
554 Rect sunshine= find_sunshine_widget();
556 progress("poking client...");
557 send_mouse_1_updown((sunshine.tl.x + sunshine.br.x) / 2,
558 (sunshine.tl.y*9 + sunshine.br.y) / 10);
563 wait_for_stability(¤t,0,0, "checking basic YPP client screen...");
564 send_mouse_1_updown(250, wheight-10);
565 send_mouse_1_updown_here();
566 send_mouse_1_updown_here();
568 check_not_disturbed();
575 wait_for_stability(&status,current,0, "awaiting status information...");
576 free_snapshot(¤t);
577 free_snapshot(&status);
580 static void convert_store_page(Snapshot *current) {
585 progress("page %d prescanning ...",npages);
586 ci= convert_page(current,&rgb);
588 progress("page %d overview ...",npages);
589 find_structure(ci,&pstruct, 0,0,0,0);
591 store_current_page(ci,pstruct,rgb);
594 void take_screenshots(void) {
595 Snapshot *current=0, *last=0;
597 prepare_ypp_client();
599 /* page to the top - keep pressing page up until the image stops changing */
600 set_focus_commodity();
601 wait_for_stability(¤t,0, send_pgup_many,
602 "paging up to top of commodity list...");
604 /* now to actually page down */
606 debugf("page %d paging\n",npages);
608 if (!(npages < MAX_PAGES))
609 fatal("Paging down seems to generate too many pages - max is %d.",
612 convert_store_page(current);
613 free_snapshot(&last); last=current; current=0;
615 debugf("PAGING page %d converted\n",npages);
617 wait_for_stability(¤t,last, 0,
618 "page %d collecting ...",
621 if (npages && /* first pagedown doesn't do much */
622 identical(current,last)) {
624 free_snapshot(¤t);
631 progress("finishing with the YPP client...");
632 send_mouse_1_updown(commod_focuslast_point.x, commod_focuslast_point.y);
634 send_pgdown_torestore();
637 debugf("PAGING all done.\n");
638 progress_log("collected %d screenshots.",npages);
641 void take_one_screenshot(void) {
644 prepare_ypp_client();
645 wait_for_stability(¤t,0,0, "taking screenshot...");
646 convert_store_page(current);
648 progress_log("collected single screenshot.");
651 void set_yppclient_window(unsigned long wul) {
655 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
661 static void findypp_recurse(int depth, int targetdepth, Window w) {
662 unsigned int nchildren;
665 Window gotroot, gotparent;
667 static const char prefix[]= "Puzzle Pirates - ";
668 static const char onthe[]= " on the ";
669 static const char suffix[]= " ocean";
670 #define S(x) ((int)sizeof((x))-1)
672 debugfind("FINDYPP %d/%d screen %d %*s %lx",
673 depth,targetdepth,screen,
674 depth,"",(unsigned long)w);
676 if (depth!=targetdepth) {
677 xassert( XQueryTree(disp,w,
679 &children,&nchildren) );
680 debugfind(" nchildren=%d\n",nchildren);
682 for (i=0; i<nchildren; i++) {
683 Window child= children[i];
684 findypp_recurse(depth+1, targetdepth, child);
693 unsigned long len, gotbytesafter;
695 unsigned char *gottitle=0;
696 xassert( !XGetWindowProperty(disp,w, wm_name,0,512, False,
697 AnyPropertyType,&gottype, &gotfmt, &len,
698 &gotbytesafter, &gottitle) );
699 title= (char*)gottitle;
701 if (DEBUGP(findypp)) {
702 debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
704 for (p=title; p < title+len; p++) {
706 if (c>=' ' && c<=126) fputc(c,debug);
707 else fprintf(debug,"\\x%02x",c & 0xff);
712 #define REQUIRE(pred) \
713 if (!(pred)) { debugfind(" failed test %s\n", #pred); return; } \
716 REQUIRE( gottype!=None );
718 REQUIRE( gotfmt==8 );
720 REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
722 char *spc1= strchr( title + S(prefix), ' '); REQUIRE(spc1);
723 char *spc2= strrchr((title + len) - S(suffix), ' '); REQUIRE(spc2);
725 REQUIRE( (title + len) - spc1 >= S(onthe) + S(suffix) );
726 REQUIRE( spc2 - title >= S(prefix) + S(onthe) );
728 REQUIRE( !memcmp(title, prefix, S(prefix)) );
729 REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix)) );
730 REQUIRE( !memcmp(spc1, onthe, S(onthe)) );
732 #define ASSIGN(what, start, end) \
733 what= masprintf("%.*s", (int)((end)-(start)), start); \
734 if (o_##what) REQUIRE( !strcasecmp(o_##what, what) ); \
737 ASSIGN(ocean, spc1 + S(onthe), (title + len) - S(suffix));
738 ASSIGN(pirate, title + S(prefix), spc1);
740 debugfind(" YES!\n");
743 progress_log("found YPP client (0x%lx):"
745 (unsigned long)id, ocean, pirate);
748 void find_yppclient_window(void) {
755 progress("looking for YPP client window...");
757 xassert( (wm_name= XInternAtom(disp,"WM_NAME",True)) != None);
759 for (targetdepth=1; targetdepth<4; targetdepth++) {
760 for (screen=0; screen<ScreenCount(disp); screen++) {
761 debugfind("FINDYPP screen %d\n", screen);
762 findypp_recurse(0,targetdepth, RootWindow(disp,screen));
768 fatal("Found several possible YPP clients. Close one,\n"
769 " disambiguate with --pirate or --ocean,"
770 " or specify --window-id.\n");
772 fatal("Did not find %sYPP client."
773 " Use --window-id and/or report this as a fault.\n",
774 o_ocean || o_pirate ? "matching ": "");