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 CanonImage *page_images[MAX_PAGES];
45 static XWindowAttributes attr;
48 static struct timeval tv_startup;
49 static unsigned wwidth, wheight;
51 DEBUG_DEFINE_DEBUGF(pages)
53 #define xassert(what) \
55 fatal("X11 operation unexpectedly failed." \
56 " %s:%d: %s\n", __FILE__,__LINE__,#what))
58 static KeyCode keycode(KeySym sym) {
59 return XKeysymToKeycode(disp,sym);
62 void screenshot_startup(void) {
63 progress("starting...");
64 disp= XOpenDisplay(0);
65 if (!disp) fatal("Unable to open X11 display.");
66 sysassert(! gettimeofday(&tv_startup,0) );
69 /*---------- pager ----------*/
71 typedef XImage Snapshot;
73 static double last_input;
74 static const double min_update_allowance= 0.25;
76 static double timestamp(void) {
79 sysassert(! gettimeofday(&tv,0) );
80 double t= (tv.tv_sec - tv_startup.tv_sec) +
81 (tv.tv_usec - tv_startup.tv_usec) * 1e-6;
82 debugf("PAGING %f\n",t);
85 static void delay(double need_sleep) {
86 debugf("PAGING delay %f\n",need_sleep);
87 sysassert(! usleep(need_sleep * 1e6) );
90 static void sync_after_input(void) {
91 xassert( XSync(disp, False) );
92 last_input= timestamp();
95 static void translate_coords_toroot(int wx, int wy, int *rx, int *ry) {
97 xassert( XTranslateCoordinates(disp, id,attr.root, wx,wy, rx,ry, &dummy) );
100 static void check_client_window_all_on_screen(void) {
102 unsigned rwidth, rheight;
107 xassert( XGetGeometry(disp,attr.root, &dummy, &rxpos,&rypos,
111 translate_coords_toroot(0,0, &onroot.tl.x,&onroot.tl.y);
112 translate_coords_toroot(wwidth-1,wheight-1, &onroot.br.x,&onroot.br.y);
113 if (!(onroot.tl.x >= 0 &&
115 onroot.br.x < rwidth &&
116 onroot.br.y < rheight))
117 fatal("YPP client window is not entirely on the screen.");
120 static void check_not_disturbed(void) {
125 r= XCheckMaskEvent(disp, ~0, &ev);
126 if (r==False) return;
129 case VisibilityNotify:
130 if (ev.xvisibility.state != VisibilityUnobscured)
131 fatal("YPP client window has become obscured.");
133 case ConfigureNotify:
134 check_client_window_all_on_screen();
137 fatal("Focus left YPP client window.");
140 warning("focus entered YPP client window ?!");
143 fatal("Received unexpected X11 event (type code %d)!", ev.type);
148 static void send_key(KeySym sym) {
149 XTestFakeKeyEvent(disp, keycode(sym),1, 10);
150 XTestFakeKeyEvent(disp, keycode(sym),0, 10);
153 static void send_pgup_many(void) {
157 debugf("PAGING PageUp x %d\n",i);
160 static void send_pgdown(void) {
162 debugf("PAGING PageDown\n");
166 static void free_snapshot(Snapshot **io) {
167 if (*io) XDestroyImage(*io);
171 static void snapshot(Snapshot **output) {
172 free_snapshot(output);
174 debugf("PAGING snapshot\n");
177 *output= XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap);
180 check_not_disturbed();
182 debugf("PAGING snapshot done.\n");
185 static int identical(const Snapshot *a, const Snapshot *b) {
186 if (!(a->width == b->width &&
187 a->height == b->height &&
188 a->bytes_per_line == b->bytes_per_line &&
189 a->format == b->format))
191 return !memcmp(a->data, b->data, a->bytes_per_line * a->height);
194 static void wait_for_stability(Snapshot **output,
195 const Snapshot *previously,
196 void (*with_keypress)(void),
197 const char *fmt, ...)
200 static void wait_for_stability(Snapshot **output,
201 const Snapshot *previously,
202 void (*with_keypress)(void),
203 const char *fmt, ...) {
208 /* waits longer if we're going to return an image identical to previously
209 * if previously==0, all images are considered identical to it */
211 debugf("PAGING wait_for_stability"
212 " last_input=%f previously=%p\n",
213 last_input, previously);
216 sysassert( vasprintf(&doing,fmt,al) >=0);
218 progress("%s",doing);
221 double at_snapshot= timestamp();
222 double need_sleep= min_update_allowance - (at_snapshot - last_input);
223 if (need_sleep > 0) { delay(need_sleep); continue; }
227 if (!with_keypress &&
228 !(previously && identical(*output,previously))) {
229 debugf("PAGING wait_for_stability simple\n");
233 if (last && identical(*output,last)) {
234 debugf("PAGING wait_for_stability stabilised\n");
238 progress_spinner("%s",doing);
240 debugf("PAGING wait_for_stability retry\n");
242 free_snapshot(&last); last=*output; *output=0;
250 free_snapshot(&last);
252 debugf("PAGING wait_for_stability done.\n");
256 static void raise_and_get_details(void) {
257 int evbase,errbase,majver,minver;
261 progress("raising and checking YPP client window...");
263 debugf("PAGING raise_and_get_details\n");
265 int xtest= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
266 if (!xtest) fatal("X server does not support the XTEST extension.");
268 xassert( XRaiseWindow(disp, id) );
269 /* in case VisibilityNotify triggers right away before we have had a
270 * change to raise; to avoid falsely detecting lowering in that case */
272 xassert( XSelectInput(disp, id,
277 xassert( XRaiseWindow(disp, id) );
278 /* in case the window was lowered between our Raise and our SelectInput;
279 * to avoid failing to detect that lowering */
281 xassert( XGetWindowAttributes(disp, id, &attr) );
282 xassert( XGetGeometry(disp,id, &attr.root,
283 &wxpos,&wypos, &wwidth,&wheight,
286 if (!(wwidth >= 320 && wheight >= 320))
287 fatal("YPP client window is implausibly small?");
289 check_client_window_all_on_screen();
292 static void set_focus(void) {
293 int screen= XScreenNumberOfScreen(attr.screen);
295 progress("taking control of YPP client window...");
297 debugf("PAGING set_focus\n");
300 translate_coords_toroot(160,160, &xpos,&ypos);
301 XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
303 XTestFakeButtonEvent(disp,1,1, 50);
304 XTestFakeButtonEvent(disp,1,0, 50);
309 xassert( XSelectInput(disp, id,
311 VisibilityChangeMask|
315 translate_coords_toroot(10,10, &xpos,&ypos);
316 XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
320 debugf("PAGING raise_and_set_focus done.\n");
323 #define SAMPLEMASK 0xfful
329 static void compute_shift_mask(ShMask *sm, unsigned long ximage_mask) {
334 if (ximage_mask <= (SAMPLEMASK>>1)) {
335 sm->lshift++; ximage_mask <<= 1;
336 } else if (ximage_mask > SAMPLEMASK) {
337 sm->rshift++; ximage_mask >>= 1;
341 assert(!(sm->lshift && sm->rshift));
343 assert(sm->lshift < LONG_BIT);
344 assert(sm->rshift < LONG_BIT);
347 static CanonImage *convert_page(Snapshot *sn) {
348 ShMask shiftmasks[3];
351 fprintf(screenshots_file,
354 "255\n", sn->width, sn->height);
356 #define COMPUTE_SHIFT_MASK(ix, rgb) \
357 compute_shift_mask(&shiftmasks[ix], sn->rgb##_mask)
358 COMPUTE_SHIFT_MASK(0, red);
359 COMPUTE_SHIFT_MASK(1, green);
360 COMPUTE_SHIFT_MASK(2, blue);
362 CANONICALISE_IMAGE(im, sn->width, sn->height, {
363 long xrgb= XGetPixel(sn, x, y);
366 for (i=0; i<3; i++) {
368 unsigned long sample=
369 ((xrgb << shiftmasks[i].lshift)
370 >> shiftmasks[i].rshift) & SAMPLEMASK;
372 fputc(sample, screenshots_file);
376 sysassert(!ferror(screenshots_file));
377 sysassert(!fflush(screenshots_file));
382 void take_screenshots(void) {
383 Snapshot *current=0, *last=0;
386 /* find the window and check it's on the right kind of screen */
387 raise_and_get_details();
388 wait_for_stability(¤t,0,0, "checking current YPP client screen...");
389 test= convert_page(current);
390 find_structure(test);
393 /* page to the top - keep pressing page up until the image stops changing */
395 wait_for_stability(¤t,0, send_pgup_many,
396 "paging up to top of commodity list...");
398 /* now to actually page down */
400 debugf("paging page %d\n",npages);
402 if (!(npages < MAX_PAGES))
403 fatal("Paging down seems to generate too many pages - max is %d.",
406 page_images[npages]= convert_page(current);
407 free_snapshot(&last); last=current; current=0;
409 debugf("PAGING page %d converted\n",npages);
411 wait_for_stability(¤t,last, 0,
412 "collecting screenshot of page %d...",
415 if (npages && /* first pagedown doesn't do much */
416 identical(current,last)) {
417 free_snapshot(¤t);
424 debugf("PAGING all done.\n");
425 progress_log("collected %d screenshots.",npages);
428 void take_one_screenshot(void) {
431 raise_and_get_details();
433 wait_for_stability(¤t,0,0, "taking screenshot...");
434 page_images[0]= convert_page(current);
436 progress_log("collected single screenshot.");
439 void set_yppclient_window(unsigned long wul) {
443 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
445 void find_yppclient_window(void) {
446 Window root, gotroot, gotparent;
452 progress("looking for YPP client window...");
454 static const char prefix[]= "Puzzle Pirates - ";
455 static const char onthe[]= " on the ";
456 static const char suffix[]= " ocean";
457 #define S(x) (sizeof((x))-1)
459 Atom wm_name= XInternAtom(disp,"WM_NAME",True);
460 xassert(wm_name != None);
462 for (screen=0; screen<ScreenCount(disp); screen++) {
463 debugfind("FINDYPP screen %d\n", screen);
464 root= RootWindow(disp,screen);
465 unsigned int nchildren1;
468 xassert( XQueryTree(disp,root,
470 &children1,&nchildren1) );
471 debugfind("FINDYPP screen %d nchildren1=%d\n", screen, nchildren1);
474 for (i=0; i<nchildren1; i++) {
475 Window w1= children1[i];
476 unsigned int nchildren2;
479 xassert( XQueryTree(disp,w1,
481 &children2,&nchildren2) );
482 debugfind("FINDYPP screen %d c1[%2d]=0x%08lx nchildren2=%d\n",
483 screen, i, (unsigned long)w1, nchildren2);
486 for (j=-1; j<(int)nchildren2; j++) {
487 Window w2= j<0 ? w1 : children2[j];
488 debugfind("FINDYPP screen %d c1[%2d]=0x%08lx c2[%2d]=0x%08lx",
489 screen, i, (unsigned long)w1, j, (unsigned long)w2);
493 unsigned long len, gotbytesafter;
495 unsigned char *gottitle=0;
496 xassert( !XGetWindowProperty(disp,w2, wm_name,0,512, False,
497 AnyPropertyType,&gottype, &gotfmt, &len,
498 &gotbytesafter, &gottitle) );
499 title= (char*)gottitle;
501 if (DEBUGP(findypp)) {
502 debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
504 for (p=title; p < title+len; p++) {
506 if (c>=' ' && c<=126) fputc(c,debug);
507 else fprintf(debug,"\\x%02x",c & 0xff);
512 #define REQUIRE(pred) \
513 if (!(pred)) { debugfind(" failed test %s\n", #pred); continue; } \
516 REQUIRE( gottype!=None );
518 REQUIRE( gotfmt==8 );
520 REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
522 char *spc1= strchr( title + S(prefix), ' '); REQUIRE(spc1);
523 char *spc2= strrchr((title + len) - S(suffix), ' '); REQUIRE(spc2);
525 REQUIRE( (title + len) - spc1 >= S(onthe) + S(suffix) );
526 REQUIRE( spc2 - title >= S(prefix) + S(onthe) );
528 REQUIRE( !memcmp(title, prefix, S(prefix)) );
529 REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix)) );
530 REQUIRE( !memcmp(spc1, onthe, S(onthe)) );
532 #define ASSIGN(what, start, end) do { \
533 sysassert( asprintf(&what, "%.*s", (end)-(start), start) >0 ); \
535 ASSIGN(pirate, title + S(prefix), spc1);
536 ASSIGN(ocean, spc1 + S(onthe), (title + len) - S(suffix));
538 debugfind(" YES!\n");
541 progress_log("found YPP client (0x%lx):"
543 (unsigned long)id, ocean, pirate);
545 if (children2) XFree(children2);
547 if (children1) XFree(children1);
550 fatal("Found several YPP clients."
551 " Close one, or specify the windowid with --window-id.\n");
553 fatal("Did not find YPP client."
554 " Use --window-id and/or report this as a fault.\n");