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];
49 static XWindowAttributes attr;
52 static struct timeval tv_startup;
53 static unsigned wwidth, wheight;
54 static int max_relevant_y= -1;
57 static XShmSegmentInfo shminfo;
59 DEBUG_DEFINE_DEBUGF(pages)
61 #define xassert(what) \
63 fatal("X11 operation unexpectedly failed." \
64 " %s:%d: %s\n", __FILE__,__LINE__,#what))
66 static KeyCode keycode(KeySym sym) {
67 return XKeysymToKeycode(disp,sym);
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) );
77 /*---------- pager ----------*/
79 typedef XImage Snapshot;
81 static double last_input;
82 static const double min_update_allowance= 0.25;
84 static double timestamp(void) {
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);
93 static void delay(double need_sleep) {
94 debugf("PAGING delay %f\n",need_sleep);
95 sysassert(! usleep(need_sleep * 1e6) );
98 static void sync_after_input(void) {
99 xassert( XSync(disp, False) );
100 last_input= timestamp();
103 static void translate_coords_toroot(int wx, int wy, int *rx, int *ry) {
105 xassert( XTranslateCoordinates(disp, id,attr.root, wx,wy, rx,ry, &dummy) );
108 static void check_client_window_all_on_screen(void) {
110 unsigned rwidth, rheight;
115 xassert( XGetGeometry(disp,attr.root, &dummy, &rxpos,&rypos,
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 &&
123 onroot.br.x < rwidth &&
124 onroot.br.y < rheight))
125 fatal("YPP client window is not entirely on the screen.");
128 static void check_not_disturbed(void) {
133 r= XCheckMaskEvent(disp, ~0, &ev);
134 if (r==False) return;
137 case VisibilityNotify:
138 if (ev.xvisibility.state != VisibilityUnobscured)
139 fatal("YPP client window has become obscured.");
141 case ConfigureNotify:
142 check_client_window_all_on_screen();
145 fatal("Focus left YPP client window.");
148 warning("focus entered YPP client window ?!");
151 fatal("Received unexpected X11 event (type code %d)!", ev.type);
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);
164 static void send_pgup_many(void) {
166 for (i=0; i<25; i++) {
170 debugf("PAGING PageUp x %d\n",i);
173 static void send_pgdown(void) {
176 debugf("PAGING PageDown\n");
179 static void send_pgdown_torestore(void) {
180 debugf("PAGING PageDown x %d\n", -pgupdown);
181 while (pgupdown < 0) {
188 static void free_snapshot(Snapshot **io) {
189 if (*io) XDestroyImage(*io);
193 static void snapshot(Snapshot **output) {
194 free_snapshot(output);
196 debugf("PAGING snapshot\n");
199 *output= XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap);
202 check_not_disturbed();
204 debugf("PAGING snapshot done.\n");
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))
214 int compare_to= a->height;
215 if (max_relevant_y && compare_to > max_relevant_y)
216 compare_to= max_relevant_y;
218 return !memcmp(a->data, b->data, a->bytes_per_line * compare_to);
221 static void wait_for_stability(Snapshot **output,
222 const Snapshot *previously,
223 void (*with_keypress)(void),
224 const char *fmt, ...)
227 static void wait_for_stability(Snapshot **output,
228 const Snapshot *previously,
229 void (*with_keypress)(void),
230 const char *fmt, ...) {
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 */
238 debugf("PAGING wait_for_stability"
239 " last_input=%f previously=%p\n",
240 last_input, previously);
243 sysassert( vasprintf(&doing,fmt,al) >=0);
245 progress("%s",doing);
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; }
254 if (!with_keypress &&
255 !(previously && identical(*output,previously))) {
256 debugf("PAGING wait_for_stability simple\n");
260 if (last && identical(*output,last)) {
261 debugf("PAGING wait_for_stability stabilised\n");
265 progress_spinner("%s",doing);
267 debugf("PAGING wait_for_stability retry\n");
269 free_snapshot(&last); last=*output; *output=0;
277 free_snapshot(&last);
279 debugf("PAGING wait_for_stability done.\n");
283 static void raise_and_get_details(void) {
284 int evbase,errbase,majver,minver;
288 progress("raising and checking YPP client window...");
290 debugf("PAGING raise_and_get_details\n");
292 int xtest= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
293 if (!xtest) fatal("X server does not support the XTEST extension.");
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 */
299 xassert( XSelectInput(disp, id,
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 */
308 xassert( XGetWindowAttributes(disp, id, &attr) );
309 xassert( XGetGeometry(disp,id, &attr.root,
310 &wxpos,&wypos, &wwidth,&wheight,
313 if (!(wwidth >= 320 && wheight >= 320))
314 fatal("YPP client window is implausibly small?");
316 check_client_window_all_on_screen();
318 int shm= XShmQueryExtension(disp);
320 xassert( shmim= XShmCreateImage(disp, attr.visual, attr.depth, ZPixmap,
321 0,&shminfo, wwidth,wheight) );
323 sigset_t oldset, all;
325 sysassert(! sigprocmask(SIG_BLOCK,&all,&oldset) );
329 sysassert(! pipe(pfd) );
330 sysassert( (cleaner= fork()) != -1 );
332 sysassert(! close(pfd[1]) );
334 int r= read(pfd[0], &shminfo.shmid, sizeof(shminfo.shmid));
336 if (r==sizeof(shminfo.shmid)) break;
337 assert(r==-1 && errno==EINTR);
341 int r= read(pfd[0],&bc,1);
343 assert(r==-1 && errno==EINTR);
345 sysassert(! shmctl(shminfo.shmid,IPC_RMID,0) );
348 sysassert(! close(pfd[0]) );
350 sysassert(! sigprocmask(SIG_SETMASK,&oldset,0) );
352 assert(shmim->height == wheight);
353 sysassert( (shminfo.shmid=
354 shmget(IPC_PRIVATE, shmim->bytes_per_line * wheight,
355 IPC_CREAT|0600)) >= 0 );
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) );
364 close(pfd[1]); /* causes IPC_RMID */
368 static void set_focus(void) {
369 int screen= XScreenNumberOfScreen(attr.screen);
371 progress("taking control of YPP client window...");
373 debugf("PAGING set_focus\n");
376 translate_coords_toroot(160,160, &xpos,&ypos);
377 XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
379 XTestFakeButtonEvent(disp,1,1, 50);
380 XTestFakeButtonEvent(disp,1,0, 50);
385 xassert( XSelectInput(disp, id,
387 VisibilityChangeMask|
391 translate_coords_toroot(10,10, &xpos,&ypos);
392 XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
396 debugf("PAGING raise_and_set_focus done.\n");
399 #define SAMPLEMASK 0xfful
405 static void compute_shift_mask(ShMask *sm, unsigned long ximage_mask) {
410 if (ximage_mask <= (SAMPLEMASK>>1)) {
411 sm->lshift++; ximage_mask <<= 1;
412 } else if (ximage_mask > SAMPLEMASK) {
413 sm->rshift++; ximage_mask >>= 1;
417 assert(!(sm->lshift && sm->rshift));
419 assert(sm->lshift < LONG_BIT);
420 assert(sm->rshift < LONG_BIT);
423 static CanonImage *convert_page(Snapshot *sn) {
424 ShMask shiftmasks[3];
427 fprintf(screenshot_file,
430 "255\n", sn->width, sn->height);
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);
438 CANONICALISE_IMAGE(im, sn->width, sn->height, {
439 long xrgb= XGetPixel(sn, x, y);
442 for (i=0; i<3; i++) {
444 unsigned long sample=
445 ((xrgb << shiftmasks[i].lshift)
446 >> shiftmasks[i].rshift) & SAMPLEMASK;
448 fputc(sample, screenshot_file);
452 sysassert(!ferror(screenshot_file));
453 sysassert(!fflush(screenshot_file));
458 void take_screenshots(void) {
459 Snapshot *current=0, *last=0;
462 /* find the window and check it's on the right kind of screen */
463 raise_and_get_details();
464 wait_for_stability(¤t,0,0, "checking current YPP client screen...");
465 test= convert_page(current);
466 find_structure(test, &max_relevant_y);
467 check_correct_commodities();
470 /* page to the top - keep pressing page up until the image stops changing */
472 wait_for_stability(¤t,0, send_pgup_many,
473 "paging up to top of commodity list...");
475 /* now to actually page down */
477 debugf("paging page %d\n",npages);
479 if (!(npages < MAX_PAGES))
480 fatal("Paging down seems to generate too many pages - max is %d.",
483 page_images[npages]= convert_page(current);
484 free_snapshot(&last); last=current; current=0;
486 debugf("PAGING page %d converted\n",npages);
488 wait_for_stability(¤t,last, 0,
489 "collecting screenshot of page %d...",
492 if (npages && /* first pagedown doesn't do much */
493 identical(current,last)) {
494 free_snapshot(¤t);
501 progress("finishing with the YPP client...");
502 send_pgdown_torestore();
504 debugf("PAGING all done.\n");
505 progress_log("collected %d screenshots.",npages);
508 void take_one_screenshot(void) {
511 raise_and_get_details();
513 wait_for_stability(¤t,0,0, "taking screenshot...");
514 page_images[0]= convert_page(current);
516 progress_log("collected single screenshot.");
519 void set_yppclient_window(unsigned long wul) {
523 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
525 void find_yppclient_window(void) {
526 Window root, gotroot, gotparent;
532 progress("looking for YPP client window...");
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)
539 Atom wm_name= XInternAtom(disp,"WM_NAME",True);
540 xassert(wm_name != None);
542 for (screen=0; screen<ScreenCount(disp); screen++) {
543 debugfind("FINDYPP screen %d\n", screen);
544 root= RootWindow(disp,screen);
545 unsigned int nchildren1;
548 xassert( XQueryTree(disp,root,
550 &children1,&nchildren1) );
551 debugfind("FINDYPP screen %d nchildren1=%d\n", screen, nchildren1);
554 for (i=0; i<nchildren1; i++) {
555 Window w1= children1[i];
556 unsigned int nchildren2;
559 xassert( XQueryTree(disp,w1,
561 &children2,&nchildren2) );
562 debugfind("FINDYPP screen %d c1[%2d]=0x%08lx nchildren2=%d\n",
563 screen, i, (unsigned long)w1, nchildren2);
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);
573 unsigned long len, gotbytesafter;
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;
581 if (DEBUGP(findypp)) {
582 debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
584 for (p=title; p < title+len; p++) {
586 if (c>=' ' && c<=126) fputc(c,debug);
587 else fprintf(debug,"\\x%02x",c & 0xff);
592 #define REQUIRE(pred) \
593 if (!(pred)) { debugfind(" failed test %s\n", #pred); continue; } \
596 REQUIRE( gottype!=None );
598 REQUIRE( gotfmt==8 );
600 REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
602 char *spc1= strchr( title + S(prefix), ' '); REQUIRE(spc1);
603 char *spc2= strrchr((title + len) - S(suffix), ' '); REQUIRE(spc2);
605 REQUIRE( (title + len) - spc1 >= S(onthe) + S(suffix) );
606 REQUIRE( spc2 - title >= S(prefix) + S(onthe) );
608 REQUIRE( !memcmp(title, prefix, S(prefix)) );
609 REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix)) );
610 REQUIRE( !memcmp(spc1, onthe, S(onthe)) );
612 #define ASSIGN(what, start, end) do { \
613 sysassert( asprintf(&what, "%.*s", (end)-(start), start) >0 ); \
615 ASSIGN(pirate, title + S(prefix), spc1);
616 ASSIGN(ocean, spc1 + S(onthe), (title + len) - S(suffix));
618 debugfind(" YES!\n");
621 progress_log("found YPP client (0x%lx):"
623 (unsigned long)id, ocean, pirate);
625 if (children2) XFree(children2);
627 if (children1) XFree(children1);
630 fatal("Found several YPP clients."
631 " Close one, or specify the windowid with --window-id.\n");
633 fatal("Did not find YPP client."
634 " Use --window-id and/or report this as a fault.\n");