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