chiark / gitweb /
Correct link to test website source code
[ypp-sc-tools.web-live.git] / yarrg / pages.c
1 /*
2  * Interaction with the YPP client via X11
3  */
4 /*
5  *  This is part of ypp-sc-tools, a set of third-party tools for assisting
6  *  players of Yohoho Puzzle Pirates.
7  * 
8  *  Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
9  * 
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.
14  * 
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.
19  * 
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/>.
22  * 
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.
26  */
27
28 /*
29  * Only this file #includes the X11 headers, as they're quite
30  * pollutant of the namespace.
31  */
32
33 #include "structure.h"
34
35 #include <X11/Xlib.h>
36 #include <X11/extensions/XTest.h>
37 #include <X11/keysym.h>
38 #include <X11/Xutil.h>
39
40 #include <X11/extensions/XShm.h>
41 #include <sys/ipc.h>
42 #include <sys/shm.h>
43
44 const char *ocean, *pirate;
45
46 static XWindowAttributes attr;
47 static Window id;
48 static Display *disp;
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;
53
54 static XImage *shmim;
55 static XShmSegmentInfo shminfo;
56
57 DEBUG_DEFINE_DEBUGF(pages)
58
59 #define xassert(what)                                   \
60   ((what) ? (void)0 :                                   \
61    fatal("X11 operation unexpectedly failed."           \
62          " %s:%d: %s\n", __FILE__,__LINE__,#what))
63
64 static KeyCode keycode(KeySym sym) {
65   return XKeysymToKeycode(disp,sym);
66 }
67
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) );
73 }
74
75 /*---------- pager ----------*/
76
77 typedef RgbImage Snapshot;
78
79 static double last_input;
80 static const double min_update_allowance= 0.25;
81
82 static double timestamp(void) {
83   struct timeval tv;
84   
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);
89   return t;
90 }
91 static void delay(double need_sleep) {
92   debugf("PAGING     delay %f\n",need_sleep);
93   sysassert(! usleep(need_sleep * 1e6) );
94 }
95
96 static void sync_after_input(void) {
97   xassert( XSync(disp, False) );
98   last_input= timestamp();
99 }
100
101 static void translate_coords_toroot(int wx, int wy, int *rx, int *ry) {
102   Window dummy;
103   xassert( XTranslateCoordinates(disp, id,attr.root, wx,wy, rx,ry, &dummy) );
104 }
105 static void translate_coords_toroot_p(Point w, int *rx, int *ry) {
106   translate_coords_toroot(w.x, w.y, rx, ry);
107 }
108
109 static void check_client_window_all_on_screen(void) {
110   Rect onroot;
111   unsigned rwidth, rheight;
112   Window dummy;
113   unsigned bd, depth;
114   int rxpos, rypos;
115
116   xassert( XGetGeometry(disp,attr.root, &dummy, &rxpos,&rypos,
117                         &rwidth, &rheight,
118                         &bd,&depth) );
119   
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 &&
123         onroot.tl.y >= 0 &&
124         onroot.br.x < rwidth &&
125         onroot.br.y < rheight))
126     fatal("YPP client window is not entirely on the screen.");
127 }
128
129 static void check_not_disturbed(void) {
130   XEvent ev;
131   int r;
132   
133   for (;;) {
134     r= XCheckMaskEvent(disp, ~0, &ev);
135     if (r==False) return;
136
137     switch (ev.type) {
138     case VisibilityNotify:
139       if (ev.xvisibility.state != VisibilityUnobscured)
140         fatal("YPP client window has become obscured.");
141       break;
142     case ConfigureNotify:
143       check_client_window_all_on_screen();
144       break;
145     case FocusOut:
146       fatal("Focus left YPP client window.");
147       break;
148     case FocusIn:
149       warning("focus entered YPP client window ?!");
150       break;
151     default:
152       fatal("Received unexpected X11 event (type code %d)!", ev.type);
153     }
154   }
155 }      
156
157 static void check_pointer_not_disturbed(void) {
158   Window got_root, got_child;
159   int got_root_x, got_root_y;
160   int got_win_x, got_win_y;
161   unsigned got_mask;
162
163   int r= XQueryPointer(disp,id, &got_root,&got_child,
164                        &got_root_x, &got_root_y,
165                        &got_win_x, &got_win_y,
166                        &got_mask);
167   if (!r ||
168       got_win_x!=commod_page_point.x ||
169       got_win_y!=commod_page_point.y) {
170     progress("");
171     fprintf(stderr,"\nunexpected mouse position:"
172             " samescreen=%d got=%dx%d want=%dx%d",
173             r, got_win_x,got_win_y,
174             commod_page_point.x,commod_page_point.y);
175     fatal("Mouse pointer moved.");
176   }
177 }
178
179 static void send_key(KeySym sym) {
180   check_not_disturbed();
181   XTestFakeKeyEvent(disp, keycode(sym),1, 0);
182   XTestFakeKeyEvent(disp, keycode(sym),0, 0);
183 }
184 static void send_mouse_1_updown_here(void) {
185   check_not_disturbed();
186   XTestFakeButtonEvent(disp,1,1, 0);
187   XTestFakeButtonEvent(disp,1,0, 0);
188 }
189 static void send_mouse_1_updown(int x, int y) {
190   check_not_disturbed();
191   int screen= XScreenNumberOfScreen(attr.screen);
192   int xpos, ypos;
193   translate_coords_toroot(x,y, &xpos,&ypos);
194   XTestFakeMotionEvent(disp, screen, xpos,ypos, 0);
195   send_mouse_1_updown_here();
196 }
197 static void pgdown_by_mouse(void) {
198   check_not_disturbed();
199   check_pointer_not_disturbed();
200   debugf("PAGING   Mouse\n");
201   send_mouse_1_updown_here();
202   sync_after_input();
203 }
204
205 static int pgupdown;
206
207 static void send_pgup_many(void) {
208   int i;
209   for (i=0; i<25; i++) {
210     send_key(XK_Prior);
211     pgupdown--;
212   }
213   debugf("PAGING   PageUp x %d\n",i);
214   sync_after_input();
215 }
216 static void send_pgdown_torestore(void) {
217   debugf("PAGING   PageDown x %d\n", -pgupdown);
218   while (pgupdown < 0) {
219     send_key(XK_Next);
220     pgupdown++;
221   }
222   sync_after_input();
223 }
224
225 static void free_snapshot(Snapshot **io) {
226   free(*io);
227   *io= 0;
228 }
229
230 #define SAMPLEMASK 0xfful
231
232 typedef struct {
233   int lshift, rshift;
234 } ShMask;
235
236 static void compute_shift_mask(ShMask *sm, unsigned long ximage_mask) {
237   sm->lshift= 0;
238   sm->rshift= 0;
239   
240   for (;;) {
241     if (ximage_mask <= (SAMPLEMASK>>1)) {
242       sm->lshift++;  ximage_mask <<= 1;
243     } else if (ximage_mask > SAMPLEMASK) {
244       sm->rshift++;  ximage_mask >>= 1;
245     } else {
246       break;
247     }
248     assert(!(sm->lshift && sm->rshift));
249   }
250   assert(sm->lshift < LONG_BIT);
251   assert(sm->rshift < LONG_BIT);
252   debugf("SHIFTMASK %p={.lshift=%d, .rshift=%d} image_mask=%lx\n",
253          sm, sm->lshift, sm->rshift, ximage_mask);
254 }
255
256 static void rtimestamp(double *t, const char *wh) {
257   double n= timestamp();
258   debugf("PAGING                INTERVAL %f  %s\n", n-*t, wh);
259   *t= n;
260 }
261
262 static void snapshot(Snapshot **output) {
263   XImage *im_use, *im_free=0;
264
265   ShMask shiftmasks[3];
266
267   debugf("PAGING   snapshot\n");
268
269   double begin= timestamp();
270   if (shmim) {
271     rtimestamp(&begin, "XShmGetImage before");
272     xassert( XShmGetImage(disp,id,shmim, 0,0, AllPlanes) );
273     rtimestamp(&begin, "XShmGetImage");
274
275     size_t dsz= shmim->bytes_per_line * shmim->height;
276     im_use= im_free= mmalloc(sizeof(*im_use) + dsz);
277     *im_free= *shmim;
278     im_free->data= (void*)(im_free+1);
279     memcpy(im_free->data, shmim->data, dsz);
280     rtimestamp(&begin, "mmalloc/memcpy");
281   } else {
282     rtimestamp(&begin, "XGetImage before");
283     xassert( im_use= im_free=
284              XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap) );
285     rtimestamp(&begin, "XGetImage");
286   }
287
288 #define COMPUTE_SHIFT_MASK(ix, rgb) \
289   compute_shift_mask(&shiftmasks[ix], im_use->rgb##_mask)
290   COMPUTE_SHIFT_MASK(0, blue);
291   COMPUTE_SHIFT_MASK(1, green);
292   COMPUTE_SHIFT_MASK(2, red);
293   
294   if (!*output)
295     *output= alloc_rgb_image(wwidth, wheight);
296
297   rtimestamp(&begin, "compute_shift_masks+alloc_rgb_image");
298
299   int x,y,i;
300   uint32_t *op32= (*output)->data;
301   for (y=0; y<wheight; y++) {
302     if (im_use->xoffset == 0 &&
303         im_use->format == ZPixmap &&
304         im_use->byte_order == LSBFirst &&
305         im_use->depth == 24 &&
306         im_use->bits_per_pixel == 32 &&
307         im_use->red_mask   == 0x0000ffU &&
308         im_use->green_mask == 0x00ff00U &&
309         im_use->blue_mask  == 0xff0000U) {
310       const char *p= im_use->data + y * im_use->bytes_per_line;
311 //      debugf("optimised copy y=%d",y);
312       memcpy(op32, p, wwidth*sizeof(*op32));
313       op32 += wwidth;
314     } else {
315       for (x=0; x<wwidth; x++) {
316         long xrgb= XGetPixel(im_use,x,y);
317         Rgb sample= 0;
318         for (i=0; i<3; i++) {
319           sample <<= 8;
320           sample |=
321             ((xrgb << shiftmasks[i].lshift) >> shiftmasks[i].rshift)
322             & SAMPLEMASK;
323         }
324         *op32++= sample;
325       }
326     }
327   }
328
329   rtimestamp(&begin,"w*h*XGetPixel");
330   if (im_free)
331     XDestroyImage(im_free);
332   
333   rtimestamp(&begin,"XDestroyImage");
334   check_not_disturbed();
335
336   debugf("PAGING   snapshot done.\n");
337 }
338
339 static int identical(const Snapshot *a, const Snapshot *b) {
340   if (!(a->w == b->w &&
341         a->h == b->h))
342     return 0;
343
344   int compare_to= a->h;
345   if (max_relevant_y>=0 && compare_to > max_relevant_y)
346     compare_to= max_relevant_y;
347   
348   return !memcmp(a->data, b->data, a->w * 3 * compare_to);
349 }
350
351 static void wait_for_stability(Snapshot **output,
352                                const Snapshot *previously,
353                                void (*with_keypress)(void),
354                                const char *fmt, ...)
355      FMT(4,5);
356
357 static void wait_for_stability(Snapshot **output,
358                                const Snapshot *previously,
359                                void (*with_keypress)(void),
360                                const char *fmt, ...) {
361   va_list al;
362   va_start(al,fmt);
363
364   Snapshot *last=0;
365   int nidentical=0;
366   /* waits longer if we're going to return an image identical to previously
367    * if previously==0, all images are considered identical to it */
368
369   char *doing;
370   sysassert( vasprintf(&doing,fmt,al) >=0 );
371
372   debugf("PAGING  wait_for_stability"
373           "  last_input=%f previously=%p `%s'\n",
374           last_input, previously, doing);
375
376   double max_interval= 1.000;
377   double min_interval= 0.100;
378   for (;;) {
379     progress_spinner("%s",doing);
380     
381     double since_last_input= timestamp() - last_input;
382     double this_interval= min_interval - since_last_input;
383     if (this_interval > max_interval) this_interval= max_interval;
384
385     if (this_interval >= 0)
386       delay(this_interval);
387
388     snapshot(output);
389
390     if (!last) {
391       debugf("PAGING  wait_for_stability first...\n");
392       last=*output; *output=0;
393     } else if (!identical(*output,last)) {
394       debugf("PAGING  wait_for_stability changed...\n");
395       free_snapshot(&last); last=*output; *output=0;
396       nidentical=0;
397       if (!with_keypress) {
398         min_interval *= 3.0;
399         min_interval += 0.1;
400       }
401     } else {
402       nidentical++;
403       int threshold=
404         !previously ? 3 :
405         identical(*output,previously) ? 5
406         : 1;
407       debugf("PAGING  wait_for_stability nidentical=%d threshold=%d\n",
408               nidentical, threshold);
409       if (nidentical >= threshold)
410         break;
411
412       min_interval += 0.1;
413       min_interval *= 2.0;
414     }
415
416     if (with_keypress)
417       with_keypress();
418   }
419
420   free_snapshot(&last);
421   free(doing);
422   debugf("PAGING  wait_for_stability done.\n");
423   va_end(al);
424 }
425
426 static void raise_and_get_details(void) {
427   int evbase,errbase,majver,minver;
428   int wxpos, wypos;
429   unsigned bd,depth;
430
431   progress("raising and checking YPP client window...");
432
433   debugf("PAGING raise_and_get_details\n");
434
435   int xtest= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
436   if (!xtest) fatal("X server does not support the XTEST extension.");
437
438   xassert( XRaiseWindow(disp, id) );
439   /* in case VisibilityNotify triggers right away before we have had a
440    * change to raise; to avoid falsely detecting lowering in that case */
441   
442   xassert( XSelectInput(disp, id,
443                         StructureNotifyMask|
444                         VisibilityChangeMask
445                         ) );
446
447   xassert( XRaiseWindow(disp, id) );
448   /* in case the window was lowered between our Raise and our SelectInput;
449    * to avoid failing to detect that lowering */
450
451   xassert( XGetWindowAttributes(disp, id, &attr) );
452   xassert( XGetGeometry(disp,id, &attr.root,
453                         &wxpos,&wypos, &wwidth,&wheight,
454                         &bd,&depth) );
455
456   if (!(wwidth >= 320 && wheight >= 320))
457     fatal("YPP client window is implausibly small?");
458
459   if (attr.depth < 24)
460     fatal("Display is not 24bpp.");
461
462   check_client_window_all_on_screen();
463
464   Bool shmpixmaps=0;
465   int major=0,minor=0;
466   int shm= XShmQueryVersion(disp, &major,&minor,&shmpixmaps);
467   debugf("PAGING shm=%d %d.%d pixmaps=%d\n",shm,major,minor,shmpixmaps);
468   if (shm) {
469     xassert( shmim= XShmCreateImage(disp, attr.visual, attr.depth, ZPixmap,
470                                     0,&shminfo, wwidth,wheight) );
471
472     sigset_t oldset, all;
473     sigfillset(&all);
474     sysassert(! sigprocmask(SIG_BLOCK,&all,&oldset) );
475
476     int pfd[2];
477     pid_t cleaner;
478     sysassert(! pipe(pfd) );
479     sysassert( (cleaner= fork()) != -1 );
480     if (!cleaner) {
481       sysassert(! close(pfd[1]) );
482       for (;;) {
483         int r= read(pfd[0], &shminfo.shmid, sizeof(shminfo.shmid));
484         if (!r) exit(0);
485         if (r==sizeof(shminfo.shmid)) break;
486         assert(r==-1 && errno==EINTR);
487       }
488       for (;;) {
489         char bc;
490         int r= read(pfd[0],&bc,1);
491         if (r>=0) break;
492         assert(r==-1 && errno==EINTR);
493       }
494       sysassert(! shmctl(shminfo.shmid,IPC_RMID,0) );
495       exit(0);
496     }
497     sysassert(! close(pfd[0]) );
498
499     sysassert(! sigprocmask(SIG_SETMASK,&oldset,0) );
500
501     assert(shmim->height == wheight);
502     sysassert( (shminfo.shmid=
503                 shmget(IPC_PRIVATE, shmim->bytes_per_line * wheight,
504                        IPC_CREAT|0600)) >= 0 );
505
506     sysassert( write(pfd[1],&shminfo.shmid,sizeof(shminfo.shmid)) ==
507                sizeof(shminfo.shmid) );
508     sysassert( shminfo.shmaddr= shmat(shminfo.shmid,0,0) );
509     shmim->data= shminfo.shmaddr;
510     shminfo.readOnly= False;
511     xassert( XShmAttach(disp,&shminfo) );
512
513     close(pfd[1]); /* causes IPC_RMID */
514   }
515 }
516
517 static void set_focus_commodity(void) {
518   int screen= XScreenNumberOfScreen(attr.screen);
519
520   progress("taking control of YPP client window...");
521
522   debugf("PAGING set_focus\n");
523
524   send_mouse_1_updown(commod_focus_point.x, commod_focus_point.y);
525   sync_after_input();
526
527   delay(0.5);
528   xassert( XSelectInput(disp, id,
529                         StructureNotifyMask|
530                         VisibilityChangeMask|
531                         FocusChangeMask
532                         ) );
533
534   int xpos,ypos;
535   translate_coords_toroot_p(commod_page_point, &xpos,&ypos);
536   XTestFakeMotionEvent(disp, screen, xpos,ypos, 0);
537
538   sync_after_input();
539
540   debugf("PAGING raise_and_set_focus done.\n");
541 }
542
543 static CanonImage *convert_page(const Snapshot *sn, RgbImage **rgb_r) {
544   CanonImage *im;
545   RgbImage *ri;
546
547   fwrite_ppmraw(screenshot_file, sn);
548
549   const Rgb *pixel= sn->data;
550   CANONICALISE_IMAGE(im, sn->w, sn->h, ri, {
551     rgb= *pixel++;
552   });
553
554   sysassert(!ferror(screenshot_file));
555   sysassert(!fflush(screenshot_file));
556
557   if (rgb_r) *rgb_r= ri;
558   else free(ri);
559
560   return im;
561 }
562
563 static void prepare_ypp_client(void) {
564   CanonImage *test;
565   Snapshot *current=0;
566   
567   /* find the window and check it's on the right kind of screen */
568   raise_and_get_details();
569   wait_for_stability(&current,0,0, "checking current YPP client screen...");
570
571   test= convert_page(current,0);
572   find_structure(test,0, &max_relevant_y,
573                  &commod_focus_point,
574                  &commod_page_point,
575                  &commod_focuslast_point);
576   check_correct_commodities();
577   Rect sunshine= find_sunshine_widget();
578
579   progress("poking client...");
580   send_mouse_1_updown((sunshine.tl.x   + sunshine.br.x) / 2,
581                       (sunshine.tl.y*9 + sunshine.br.y) / 10);
582   sync_after_input();
583
584   free(test);
585
586   wait_for_stability(&current,0,0, "checking basic YPP client screen...");
587   send_mouse_1_updown(250, wheight-10);
588   send_mouse_1_updown_here();
589   send_mouse_1_updown_here();
590   sync_after_input();
591   check_not_disturbed();
592   send_key(XK_slash);
593   send_key(XK_w);
594   send_key(XK_Return);
595   sync_after_input();
596
597   Snapshot *status=0;
598   wait_for_stability(&status,current,0, "awaiting status information...");
599   free_snapshot(&current);
600   free_snapshot(&status);
601 }
602
603 static void convert_store_page(Snapshot *current) {
604   RgbImage *rgb;
605   CanonImage *ci;
606   PageStruct *pstruct;
607   
608   progress("page %d prescanning   ...",npages);
609   ci= convert_page(current,&rgb);
610
611   progress("page %d overview      ...",npages);
612   find_structure(ci,&pstruct, 0,0,0,0);
613
614   store_current_page(ci,pstruct,rgb);
615 }
616
617 void take_screenshots(void) {
618   Snapshot *current=0, *last=0;
619
620   prepare_ypp_client();
621   
622   /* page to the top - keep pressing page up until the image stops changing */
623   set_focus_commodity();
624   wait_for_stability(&current,0, send_pgup_many,
625                      "paging up to top of commodity list...");
626
627   /* now to actually page down */
628   for (;;) {
629     debugf("page %d paging\n",npages);
630
631     pgdown_by_mouse();
632
633     if (!(npages < MAX_PAGES))
634       fatal("Paging down seems to generate too many pages - max is %d.",
635             MAX_PAGES);
636
637     convert_store_page(current);
638     free_snapshot(&last); last=current; current=0;
639     debugf("PAGING page %d converted\n",npages);
640     npages++;
641
642     wait_for_stability(&current,last, 0,
643                        "page %d collecting    ...",
644                        npages);
645     if (identical(current,last)) {
646       free_snapshot(&current);
647       break;
648     }
649   }
650   progress("finishing with the YPP client...");
651   send_mouse_1_updown(commod_focuslast_point.x, commod_focuslast_point.y);
652   sync_after_input();
653   send_pgdown_torestore();
654   sync_after_input();
655
656   debugf("PAGING all done.\n");
657   progress_log("collected %d screenshots.",npages);
658   check_pager_motion(0,npages);
659 }    
660
661 void take_one_screenshot(void) {
662   Snapshot *current=0;
663
664   prepare_ypp_client();
665   wait_for_stability(&current,0,0, "taking screenshot...");
666   convert_store_page(current);
667   npages= 1;
668   progress_log("collected single screenshot.");
669 }
670
671 void set_yppclient_window(unsigned long wul) {
672   id= wul;
673 }
674
675 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
676
677 static int nfound;
678 static Atom wm_name;
679 static int screen;
680
681 static void findypp_recurse(int depth, int targetdepth, Window w) {
682   unsigned int nchildren;
683   int i;
684   Window *children=0;
685   Window gotroot, gotparent;
686
687   static const char prefix[]= "Puzzle Pirates - ";
688   static const char onthe[]= " on the ";
689   static const char suffix[]= " ocean";
690 #define S(x) ((int)sizeof((x))-1)
691
692   debugfind("FINDYPP %d/%d screen %d  %*s %lx",
693             depth,targetdepth,screen,
694             depth,"",(unsigned long)w);
695   
696   if (depth!=targetdepth) {
697     xassert( XQueryTree(disp,w,
698                         &gotroot,&gotparent,
699                         &children,&nchildren) );
700     debugfind(" nchildren=%d\n",nchildren);
701   
702     for (i=0; i<nchildren; i++) {
703       Window child= children[i];
704       findypp_recurse(depth+1, targetdepth, child);
705     }
706     XFree(children);
707     return;
708   }
709     
710
711   int gotfmt;
712   Atom gottype;
713   unsigned long len, gotbytesafter;
714   char *title;
715   unsigned char *gottitle=0;
716   xassert( !XGetWindowProperty(disp,w, wm_name,0,512, False,
717                                AnyPropertyType,&gottype, &gotfmt, &len,
718                                &gotbytesafter, &gottitle) );
719   title= (char*)gottitle;
720
721   if (DEBUGP(findypp)) {
722     debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
723     char *p;
724     for (p=title; p < title+len; p++) {
725       char c= *p;
726       if (c>=' ' && c<=126) fputc(c,debug);
727       else fprintf(debug,"\\x%02x",c & 0xff);
728     }
729     fputs("\": ",debug);
730   }
731
732 #define REQUIRE(pred)                                                   \
733   if (!(pred)) { debugfind(" failed test  %s\n", #pred); return; }      \
734   else
735
736   REQUIRE( gottype!=None );
737   REQUIRE( len );
738   REQUIRE( gotfmt==8 );
739
740   REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
741
742   char *spc1= strchr(  title        + S(prefix), ' ');  REQUIRE(spc1);
743   char *spc2= strrchr((title + len) - S(suffix), ' ');  REQUIRE(spc2);
744
745   REQUIRE( (title + len) - spc1  >= S(onthe)  + S(suffix) );
746   REQUIRE(  spc2         - title >= S(prefix) + S(onthe) );
747
748   REQUIRE( !memcmp(title,                   prefix, S(prefix)) );
749   REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix))  );
750   REQUIRE( !memcmp(spc1,                    onthe,  S(onthe))  );
751
752 #define ASSIGN(what, start, end)                        \
753   what= masprintf("%.*s", (int)((end)-(start)), start); \
754   if (o_##what) REQUIRE( !strcasecmp(o_##what, what) ); \
755   else
756
757   ASSIGN(ocean,  spc1 + S(onthe),   (title + len) - S(suffix));
758   ASSIGN(pirate, title + S(prefix),  spc1);
759
760   debugfind(" YES!\n");
761   id= w;
762   nfound++;
763   progress_log("found YPP client (0x%lx):"
764                " %s ocean - %s.",
765                (unsigned long)id, ocean, pirate);
766 }
767
768 void find_yppclient_window(void) {
769   int targetdepth;
770
771   nfound=0;
772   
773   if (id) return;
774   
775   progress("looking for YPP client window...");
776
777   xassert( (wm_name= XInternAtom(disp,"WM_NAME",True)) != None);
778
779   for (targetdepth=1; targetdepth<4; targetdepth++) {
780     for (screen=0; screen<ScreenCount(disp); screen++) {
781       debugfind("FINDYPP screen %d\n", screen);
782       findypp_recurse(0,targetdepth, RootWindow(disp,screen));
783     }
784     if (nfound) break;
785   }
786
787   if (nfound>1)
788     fatal("Found several possible YPP clients.   Close one,\n"
789           " disambiguate with --pirate or --ocean,"
790           " or specify --window-id.\n");
791   if (nfound<1)
792     fatal("Did not find %sYPP client."
793           " Use --window-id and/or report this as a fault.\n",
794           o_ocean || o_pirate ? "matching ": "");
795 }