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