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;
50 static int max_relevant_y= -1;
52 DEBUG_DEFINE_DEBUGF(pages)
54 #define xassert(what) \
56 fatal("X11 operation unexpectedly failed." \
57 " %s:%d: %s\n", __FILE__,__LINE__,#what))
59 static KeyCode keycode(KeySym sym) {
60 return XKeysymToKeycode(disp,sym);
63 void screenshot_startup(void) {
64 progress("starting...");
65 disp= XOpenDisplay(0);
66 if (!disp) fatal("Unable to open X11 display.");
67 sysassert(! gettimeofday(&tv_startup,0) );
70 /*---------- pager ----------*/
72 typedef XImage Snapshot;
74 static double last_input;
75 static const double min_update_allowance= 0.25;
77 static double timestamp(void) {
80 sysassert(! gettimeofday(&tv,0) );
81 double t= (tv.tv_sec - tv_startup.tv_sec) +
82 (tv.tv_usec - tv_startup.tv_usec) * 1e-6;
83 debugf("PAGING %f\n",t);
86 static void delay(double need_sleep) {
87 debugf("PAGING delay %f\n",need_sleep);
88 sysassert(! usleep(need_sleep * 1e6) );
91 static void sync_after_input(void) {
92 xassert( XSync(disp, False) );
93 last_input= timestamp();
96 static void translate_coords_toroot(int wx, int wy, int *rx, int *ry) {
98 xassert( XTranslateCoordinates(disp, id,attr.root, wx,wy, rx,ry, &dummy) );
101 static void check_client_window_all_on_screen(void) {
103 unsigned rwidth, rheight;
108 xassert( XGetGeometry(disp,attr.root, &dummy, &rxpos,&rypos,
112 translate_coords_toroot(0,0, &onroot.tl.x,&onroot.tl.y);
113 translate_coords_toroot(wwidth-1,wheight-1, &onroot.br.x,&onroot.br.y);
114 if (!(onroot.tl.x >= 0 &&
116 onroot.br.x < rwidth &&
117 onroot.br.y < rheight))
118 fatal("YPP client window is not entirely on the screen.");
121 static void check_not_disturbed(void) {
126 r= XCheckMaskEvent(disp, ~0, &ev);
127 if (r==False) return;
130 case VisibilityNotify:
131 if (ev.xvisibility.state != VisibilityUnobscured)
132 fatal("YPP client window has become obscured.");
134 case ConfigureNotify:
135 check_client_window_all_on_screen();
138 fatal("Focus left YPP client window.");
141 warning("focus entered YPP client window ?!");
144 fatal("Received unexpected X11 event (type code %d)!", ev.type);
149 static void send_key(KeySym sym) {
150 check_not_disturbed();
151 XTestFakeKeyEvent(disp, keycode(sym),1, 10);
152 XTestFakeKeyEvent(disp, keycode(sym),0, 10);
157 static void send_pgup_many(void) {
159 for (i=0; i<25; i++) {
163 debugf("PAGING PageUp x %d\n",i);
166 static void send_pgdown(void) {
169 debugf("PAGING PageDown\n");
172 static void send_pgdown_torestore(void) {
173 debugf("PAGING PageDown x %d\n", -pgupdown);
174 while (pgupdown < 0) {
181 static void free_snapshot(Snapshot **io) {
182 if (*io) XDestroyImage(*io);
186 static void snapshot(Snapshot **output) {
187 free_snapshot(output);
189 debugf("PAGING snapshot\n");
192 *output= XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap);
195 check_not_disturbed();
197 debugf("PAGING snapshot done.\n");
200 static int identical(const Snapshot *a, const Snapshot *b) {
201 if (!(a->width == b->width &&
202 a->height == b->height &&
203 a->bytes_per_line == b->bytes_per_line &&
204 a->format == b->format))
207 int compare_to= a->height;
208 if (max_relevant_y && compare_to > max_relevant_y)
209 compare_to= max_relevant_y;
211 return !memcmp(a->data, b->data, a->bytes_per_line * compare_to);
214 static void wait_for_stability(Snapshot **output,
215 const Snapshot *previously,
216 void (*with_keypress)(void),
217 const char *fmt, ...)
220 static void wait_for_stability(Snapshot **output,
221 const Snapshot *previously,
222 void (*with_keypress)(void),
223 const char *fmt, ...) {
228 /* waits longer if we're going to return an image identical to previously
229 * if previously==0, all images are considered identical to it */
231 debugf("PAGING wait_for_stability"
232 " last_input=%f previously=%p\n",
233 last_input, previously);
236 sysassert( vasprintf(&doing,fmt,al) >=0);
238 progress("%s",doing);
241 double at_snapshot= timestamp();
242 double need_sleep= min_update_allowance - (at_snapshot - last_input);
243 if (need_sleep > 0) { delay(need_sleep); continue; }
247 if (!with_keypress &&
248 !(previously && identical(*output,previously))) {
249 debugf("PAGING wait_for_stability simple\n");
253 if (last && identical(*output,last)) {
254 debugf("PAGING wait_for_stability stabilised\n");
258 progress_spinner("%s",doing);
260 debugf("PAGING wait_for_stability retry\n");
262 free_snapshot(&last); last=*output; *output=0;
270 free_snapshot(&last);
272 debugf("PAGING wait_for_stability done.\n");
276 static void raise_and_get_details(void) {
277 int evbase,errbase,majver,minver;
281 progress("raising and checking YPP client window...");
283 debugf("PAGING raise_and_get_details\n");
285 int xtest= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
286 if (!xtest) fatal("X server does not support the XTEST extension.");
288 xassert( XRaiseWindow(disp, id) );
289 /* in case VisibilityNotify triggers right away before we have had a
290 * change to raise; to avoid falsely detecting lowering in that case */
292 xassert( XSelectInput(disp, id,
297 xassert( XRaiseWindow(disp, id) );
298 /* in case the window was lowered between our Raise and our SelectInput;
299 * to avoid failing to detect that lowering */
301 xassert( XGetWindowAttributes(disp, id, &attr) );
302 xassert( XGetGeometry(disp,id, &attr.root,
303 &wxpos,&wypos, &wwidth,&wheight,
306 if (!(wwidth >= 320 && wheight >= 320))
307 fatal("YPP client window is implausibly small?");
309 check_client_window_all_on_screen();
312 static void set_focus(void) {
313 int screen= XScreenNumberOfScreen(attr.screen);
315 progress("taking control of YPP client window...");
317 debugf("PAGING set_focus\n");
320 translate_coords_toroot(160,160, &xpos,&ypos);
321 XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
323 XTestFakeButtonEvent(disp,1,1, 50);
324 XTestFakeButtonEvent(disp,1,0, 50);
329 xassert( XSelectInput(disp, id,
331 VisibilityChangeMask|
335 translate_coords_toroot(10,10, &xpos,&ypos);
336 XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
340 debugf("PAGING raise_and_set_focus done.\n");
343 #define SAMPLEMASK 0xfful
349 static void compute_shift_mask(ShMask *sm, unsigned long ximage_mask) {
354 if (ximage_mask <= (SAMPLEMASK>>1)) {
355 sm->lshift++; ximage_mask <<= 1;
356 } else if (ximage_mask > SAMPLEMASK) {
357 sm->rshift++; ximage_mask >>= 1;
361 assert(!(sm->lshift && sm->rshift));
363 assert(sm->lshift < LONG_BIT);
364 assert(sm->rshift < LONG_BIT);
367 static CanonImage *convert_page(Snapshot *sn) {
368 ShMask shiftmasks[3];
371 fprintf(screenshot_file,
374 "255\n", sn->width, sn->height);
376 #define COMPUTE_SHIFT_MASK(ix, rgb) \
377 compute_shift_mask(&shiftmasks[ix], sn->rgb##_mask)
378 COMPUTE_SHIFT_MASK(0, red);
379 COMPUTE_SHIFT_MASK(1, green);
380 COMPUTE_SHIFT_MASK(2, blue);
382 CANONICALISE_IMAGE(im, sn->width, sn->height, {
383 long xrgb= XGetPixel(sn, x, y);
386 for (i=0; i<3; i++) {
388 unsigned long sample=
389 ((xrgb << shiftmasks[i].lshift)
390 >> shiftmasks[i].rshift) & SAMPLEMASK;
392 fputc(sample, screenshot_file);
396 sysassert(!ferror(screenshot_file));
397 sysassert(!fflush(screenshot_file));
402 void take_screenshots(void) {
403 Snapshot *current=0, *last=0;
406 /* find the window and check it's on the right kind of screen */
407 raise_and_get_details();
408 wait_for_stability(¤t,0,0, "checking current YPP client screen...");
409 test= convert_page(current);
410 find_structure(test, &max_relevant_y);
411 check_correct_commodities();
414 /* page to the top - keep pressing page up until the image stops changing */
416 wait_for_stability(¤t,0, send_pgup_many,
417 "paging up to top of commodity list...");
419 /* now to actually page down */
421 debugf("paging page %d\n",npages);
423 if (!(npages < MAX_PAGES))
424 fatal("Paging down seems to generate too many pages - max is %d.",
427 page_images[npages]= convert_page(current);
428 free_snapshot(&last); last=current; current=0;
430 debugf("PAGING page %d converted\n",npages);
432 wait_for_stability(¤t,last, 0,
433 "collecting screenshot of page %d...",
436 if (npages && /* first pagedown doesn't do much */
437 identical(current,last)) {
438 free_snapshot(¤t);
445 progress("finishing with the YPP client...");
446 send_pgdown_torestore();
448 debugf("PAGING all done.\n");
449 progress_log("collected %d screenshots.",npages);
452 void take_one_screenshot(void) {
455 raise_and_get_details();
457 wait_for_stability(¤t,0,0, "taking screenshot...");
458 page_images[0]= convert_page(current);
460 progress_log("collected single screenshot.");
463 void set_yppclient_window(unsigned long wul) {
467 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
469 void find_yppclient_window(void) {
470 Window root, gotroot, gotparent;
476 progress("looking for YPP client window...");
478 static const char prefix[]= "Puzzle Pirates - ";
479 static const char onthe[]= " on the ";
480 static const char suffix[]= " ocean";
481 #define S(x) (sizeof((x))-1)
483 Atom wm_name= XInternAtom(disp,"WM_NAME",True);
484 xassert(wm_name != None);
486 for (screen=0; screen<ScreenCount(disp); screen++) {
487 debugfind("FINDYPP screen %d\n", screen);
488 root= RootWindow(disp,screen);
489 unsigned int nchildren1;
492 xassert( XQueryTree(disp,root,
494 &children1,&nchildren1) );
495 debugfind("FINDYPP screen %d nchildren1=%d\n", screen, nchildren1);
498 for (i=0; i<nchildren1; i++) {
499 Window w1= children1[i];
500 unsigned int nchildren2;
503 xassert( XQueryTree(disp,w1,
505 &children2,&nchildren2) );
506 debugfind("FINDYPP screen %d c1[%2d]=0x%08lx nchildren2=%d\n",
507 screen, i, (unsigned long)w1, nchildren2);
510 for (j=-1; j<(int)nchildren2; j++) {
511 Window w2= j<0 ? w1 : children2[j];
512 debugfind("FINDYPP screen %d c1[%2d]=0x%08lx c2[%2d]=0x%08lx",
513 screen, i, (unsigned long)w1, j, (unsigned long)w2);
517 unsigned long len, gotbytesafter;
519 unsigned char *gottitle=0;
520 xassert( !XGetWindowProperty(disp,w2, wm_name,0,512, False,
521 AnyPropertyType,&gottype, &gotfmt, &len,
522 &gotbytesafter, &gottitle) );
523 title= (char*)gottitle;
525 if (DEBUGP(findypp)) {
526 debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
528 for (p=title; p < title+len; p++) {
530 if (c>=' ' && c<=126) fputc(c,debug);
531 else fprintf(debug,"\\x%02x",c & 0xff);
536 #define REQUIRE(pred) \
537 if (!(pred)) { debugfind(" failed test %s\n", #pred); continue; } \
540 REQUIRE( gottype!=None );
542 REQUIRE( gotfmt==8 );
544 REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
546 char *spc1= strchr( title + S(prefix), ' '); REQUIRE(spc1);
547 char *spc2= strrchr((title + len) - S(suffix), ' '); REQUIRE(spc2);
549 REQUIRE( (title + len) - spc1 >= S(onthe) + S(suffix) );
550 REQUIRE( spc2 - title >= S(prefix) + S(onthe) );
552 REQUIRE( !memcmp(title, prefix, S(prefix)) );
553 REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix)) );
554 REQUIRE( !memcmp(spc1, onthe, S(onthe)) );
556 #define ASSIGN(what, start, end) do { \
557 sysassert( asprintf(&what, "%.*s", (end)-(start), start) >0 ); \
559 ASSIGN(pirate, title + S(prefix), spc1);
560 ASSIGN(ocean, spc1 + S(onthe), (title + len) - S(suffix));
562 debugfind(" YES!\n");
565 progress_log("found YPP client (0x%lx):"
567 (unsigned long)id, ocean, pirate);
569 if (children2) XFree(children2);
571 if (children1) XFree(children1);
574 fatal("Found several YPP clients."
575 " Close one, or specify the windowid with --window-id.\n");
577 fatal("Did not find YPP client."
578 " Use --window-id and/or report this as a fault.\n");