chiark / gitweb /
where-vessels: show unsmashed code canvas for vessel when we click on the name in...
[ypp-sc-tools.db-test.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 DEBUG_DEFINE_SOME_DEBUGF(keymap,keydebugf)
59
60 #define xassert(what)                                   \
61   ((what) ? (void)0 :                                   \
62    fatal("X11 operation unexpectedly failed."           \
63          " %s:%d: %s\n", __FILE__,__LINE__,#what))
64
65
66 /*---------- keyboard map ----------*/
67
68 #define KEYS(EACH_KEY)                          \
69   EACH_KEY(XK_slash)                            \
70   EACH_KEY(XK_w)                                \
71   EACH_KEY(XK_Return)                           \
72   EACH_KEY(XK_Prior)                            \
73   EACH_KEY(XK_Next)
74
75 #define MAXMAPCOL 6
76 typedef struct {
77   int len;
78   int kc[3];
79 } MappedKey;
80
81 #define KEY_MAP_DEF(xk) \
82 static MappedKey mk_##xk;
83 KEYS(KEY_MAP_DEF)
84
85 typedef struct {
86   int isdef; /* 'y' if defined; otherwise char indicating why not */
87   int kc;
88 } MappedModifier;
89
90 static int kc_min, kc_max;
91 static MappedModifier mm_shift, mm_modeswitch, mm_isol3shift;
92 static KeySym *mapping;
93 static int mapwidth;
94
95 static void keymap_lookup_modifier(MappedModifier *mm, const char *what,
96                                    KeySym sym, char ifnot) {
97   int kc;
98   keydebugf("KEYMAP modifier lookup %-10s %#lx or '%c' ", what,
99             (unsigned long)sym, ifnot);
100
101   mm->isdef= ifnot;
102   for (kc=kc_min; kc <= kc_max; kc++) {
103     if (mapping[(kc-kc_min)*mapwidth] == sym) {
104       keydebugf(" found kc=%d\n", kc);
105       mm->isdef= 'y';
106       mm->kc= kc;
107       return;
108     }
109   }
110   keydebugf(" none\n");
111 }
112
113 static void keymap_lookup_key(MappedKey *mk, KeySym sym, const char *what) {
114   const MappedModifier *shift, *xshift;
115   int col, kc;
116   char cols[MAXMAPCOL+1];
117
118   memset(cols,'.',MAXMAPCOL);
119   cols[MAXMAPCOL]= 0;
120
121   for (col=0; col<mapwidth && col<MAXMAPCOL; col++) {
122     keydebugf("KEYMAP lookup %-10s %#lx col=%d ",
123               what, (unsigned long)sym, col);
124
125 #define CHECK_SHIFT(sh) do{                                     \
126       if ((sh) && (sh)->isdef!='y') {                           \
127         cols[col]= (sh)->isdef;                                 \
128         keydebugf("no-modifier " #sh "'%c'\n", (sh)->isdef);    \
129         continue;                                               \
130       }                                                         \
131     }while(0)
132
133     shift= col & 1 ? &mm_shift : 0;
134     CHECK_SHIFT(shift);
135
136     xshift= col >= 4 ? &mm_isol3shift :
137             col >= 2 ? &mm_modeswitch :
138             0;
139     CHECK_SHIFT(xshift);
140
141     for (kc=kc_min; kc <= kc_max; kc++) {
142       if (mapping[(kc-kc_min)*mapwidth + col] == sym)
143         goto found;
144     }
145     cols[col]= '_';
146     keydebugf("not-found\n");
147   }
148   fprintf(stderr,"\n"
149           "Unable to find a key to press to generate %s.\n"
150           "(Technical details: cols:%s sh:%c:%d modesw:%c:%d isol3:%c:%d)\n",
151           what, cols,
152 #define SH_DETAILS(sh) mm_##sh.isdef, mm_##sh.kc
153           SH_DETAILS(shift), SH_DETAILS(modeswitch), SH_DETAILS(isol3shift));
154   fatal("Keymap is unsuitable!");
155
156  found:;
157   int *fill= mk->kc;
158   
159   if (xshift) *fill++ = xshift->kc;
160   if (shift)  *fill++ = shift->kc;
161   *fill++ += kc;
162   mk->len= fill - mk->kc;
163   keydebugf("found kc=%d len=%d\n",kc,mk->len);
164 }
165
166 static void keymap_startup(void) {
167   xassert( XDisplayKeycodes(disp,&kc_min,&kc_max) );
168   keydebugf("KEYMAP keycodes %d..%d\n",kc_min,kc_max);
169
170   xassert( mapping= XGetKeyboardMapping(disp, kc_min, kc_max-kc_min+1,
171                                         &mapwidth) );
172   keydebugf("KEYMAP got keyboard map\n");
173
174   XModifierKeymap *modmap;
175   xassert( modmap= XGetModifierMapping(disp) );
176   keydebugf("KEYMAP got modifier map\n");
177
178   /* find a shift keycode */
179   mm_shift.isdef= 'x';
180   int modent;
181   for (modent=0; modent<modmap->max_keypermod; modent++) {
182     int kc= modmap->modifiermap[modent];
183     keydebugf("KEYMAP modifier #0 key #%d is %d ", modent, kc);
184     if (!kc) { keydebugf("none\n"); continue; }
185     keydebugf("ok\n");
186     mm_shift.kc= kc;
187     mm_shift.isdef= 'y';
188     break;
189   }
190
191   XFreeModifiermap(modmap);
192
193   /* find keycodes for mode_switch (column+=2) and ISO L3 shift (column+=4) */
194   keymap_lookup_modifier(&mm_modeswitch,"modeswitch", XK_Mode_switch,     'm');
195   keymap_lookup_modifier(&mm_isol3shift,"isol3shift", XK_ISO_Level3_Shift,'l');
196   
197 #define KEY_MAP_LOOKUP(xk) \
198   keymap_lookup_key(&mk_##xk, xk, #xk);
199   KEYS(KEY_MAP_LOOKUP)
200
201   XFree(mapping);
202   mapping= 0;
203 }
204
205 #define SEND_KEY(xk) (send_key(&mk_##xk))
206
207 /*---------- pager ----------*/
208
209 typedef RgbImage Snapshot;
210
211 static double last_input;
212 static const double min_update_allowance= 0.25;
213
214 static double timestamp(void) {
215   struct timeval tv;
216   
217   sysassert(! gettimeofday(&tv,0) );
218   double t= (tv.tv_sec - tv_startup.tv_sec) +
219             (tv.tv_usec - tv_startup.tv_usec) * 1e-6;
220   debugf("PAGING %f\n",t);
221   return t;
222 }
223 static void delay(double need_sleep) {
224   debugf("PAGING     delay %f\n",need_sleep);
225   sysassert(! usleep(need_sleep * 1e6) );
226 }
227
228 static void sync_after_input(void) {
229   xassert( XSync(disp, False) );
230   last_input= timestamp();
231 }
232
233 static void translate_coords_toroot(int wx, int wy, int *rx, int *ry) {
234   Window dummy;
235   xassert( XTranslateCoordinates(disp, id,attr.root, wx,wy, rx,ry, &dummy) );
236 }
237 static void translate_coords_toroot_p(Point w, int *rx, int *ry) {
238   translate_coords_toroot(w.x, w.y, rx, ry);
239 }
240
241 static void check_client_window_all_on_screen(void) {
242   Rect onroot;
243   unsigned rwidth, rheight;
244   Window dummy;
245   unsigned bd, depth;
246   int rxpos, rypos;
247
248   xassert( XGetGeometry(disp,attr.root, &dummy, &rxpos,&rypos,
249                         &rwidth, &rheight,
250                         &bd,&depth) );
251   
252   translate_coords_toroot(0,0, &onroot.tl.x,&onroot.tl.y);
253   translate_coords_toroot(wwidth-1,wheight-1, &onroot.br.x,&onroot.br.y);
254   if (!(onroot.tl.x >= 0 &&
255         onroot.tl.y >= 0 &&
256         onroot.br.x < rwidth &&
257         onroot.br.y < rheight))
258     fatal("YPP client window is not entirely on the screen.");
259 }
260
261 static void check_not_disturbed(void) {
262   XEvent ev;
263   int r;
264   
265   for (;;) {
266     r= XCheckMaskEvent(disp, ~0, &ev);
267     if (r==False) return;
268
269     switch (ev.type) {
270     case VisibilityNotify:
271       if (ev.xvisibility.state != VisibilityUnobscured)
272         fatal("YPP client window has become obscured.");
273       break;
274     case ConfigureNotify:
275       check_client_window_all_on_screen();
276       break;
277     case FocusOut:
278       fatal("Focus left YPP client window.");
279       break;
280     case FocusIn:
281       warning("focus entered YPP client window ?!");
282       break;
283     default:
284       fatal("Received unexpected X11 event (type code %d)!", ev.type);
285     }
286   }
287 }      
288
289 static void check_pointer_not_disturbed(void) {
290   Window got_root, got_child;
291   int got_root_x, got_root_y;
292   int got_win_x, got_win_y;
293   unsigned got_mask;
294
295   int r= XQueryPointer(disp,id, &got_root,&got_child,
296                        &got_root_x, &got_root_y,
297                        &got_win_x, &got_win_y,
298                        &got_mask);
299   if (!r ||
300       got_win_x!=commod_page_point.x ||
301       got_win_y!=commod_page_point.y) {
302     progress("");
303     fprintf(stderr,"\nunexpected mouse position:"
304             " samescreen=%d got=%dx%d want=%dx%d",
305             r, got_win_x,got_win_y,
306             commod_page_point.x,commod_page_point.y);
307     fatal("Mouse pointer moved.");
308   }
309 }
310
311 static void send_key(MappedKey *mk) {
312   int i;
313   check_not_disturbed();
314   keydebugf("KEYMAP SEND_KEY len=%d kc=%d\n", mk->len, mk->kc[mk->len-1]);
315   for (i=0; i<mk->len; i++) XTestFakeKeyEvent(disp, mk->kc[i], 1, 0);
316   for (i=mk->len; --i>=0; ) XTestFakeKeyEvent(disp, mk->kc[i], 0, 0);
317 }
318 static void send_mouse_1_updown_here(void) {
319   check_not_disturbed();
320   XTestFakeButtonEvent(disp,1,1, 0);
321   XTestFakeButtonEvent(disp,1,0, 0);
322 }
323 static void send_mouse_1_updown(int x, int y) {
324   check_not_disturbed();
325   int screen= XScreenNumberOfScreen(attr.screen);
326   int xpos, ypos;
327   translate_coords_toroot(x,y, &xpos,&ypos);
328   XTestFakeMotionEvent(disp, screen, xpos,ypos, 0);
329   send_mouse_1_updown_here();
330 }
331 static void pgdown_by_mouse(void) {
332   check_not_disturbed();
333   check_pointer_not_disturbed();
334   debugf("PAGING   Mouse\n");
335   send_mouse_1_updown_here();
336   sync_after_input();
337 }
338
339 static int pgupdown;
340
341 static void send_pgup_many(void) {
342   int i;
343   for (i=0; i<25; i++) {
344     SEND_KEY(XK_Prior);
345     pgupdown--;
346   }
347   debugf("PAGING   PageUp x %d\n",i);
348   sync_after_input();
349 }
350 static void send_pgdown_torestore(void) {
351   debugf("PAGING   PageDown x %d\n", -pgupdown);
352   while (pgupdown < 0) {
353     SEND_KEY(XK_Next);
354     pgupdown++;
355   }
356   sync_after_input();
357 }
358
359 static void free_snapshot(Snapshot **io) {
360   free(*io);
361   *io= 0;
362 }
363
364 #define SAMPLEMASK 0xfful
365
366 typedef struct {
367   int lshift, rshift;
368 } ShMask;
369
370 static void compute_shift_mask(ShMask *sm, unsigned long ximage_mask) {
371   sm->lshift= 0;
372   sm->rshift= 0;
373   
374   for (;;) {
375     if (ximage_mask <= (SAMPLEMASK>>1)) {
376       sm->lshift++;  ximage_mask <<= 1;
377     } else if (ximage_mask > SAMPLEMASK) {
378       sm->rshift++;  ximage_mask >>= 1;
379     } else {
380       break;
381     }
382     assert(!(sm->lshift && sm->rshift));
383   }
384   assert(sm->lshift < LONG_BIT);
385   assert(sm->rshift < LONG_BIT);
386   debugf("SHIFTMASK %p={.lshift=%d, .rshift=%d} image_mask=%lx\n",
387          sm, sm->lshift, sm->rshift, ximage_mask);
388 }
389
390 static void rtimestamp(double *t, const char *wh) {
391   double n= timestamp();
392   debugf("PAGING                INTERVAL %f  %s\n", n-*t, wh);
393   *t= n;
394 }
395
396 static void snapshot(Snapshot **output) {
397   XImage *im_use, *im_free=0;
398
399   ShMask shiftmasks[3];
400
401   debugf("PAGING   snapshot\n");
402
403   double begin= timestamp();
404   if (shmim) {
405     rtimestamp(&begin, "XShmGetImage before");
406     xassert( XShmGetImage(disp,id,shmim, 0,0, AllPlanes) );
407     rtimestamp(&begin, "XShmGetImage");
408
409     size_t dsz= shmim->bytes_per_line * shmim->height;
410     im_use= im_free= mmalloc(sizeof(*im_use) + dsz);
411     *im_free= *shmim;
412     im_free->data= (void*)(im_free+1);
413     memcpy(im_free->data, shmim->data, dsz);
414     rtimestamp(&begin, "mmalloc/memcpy");
415   } else {
416     rtimestamp(&begin, "XGetImage before");
417     xassert( im_use= im_free=
418              XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap) );
419     rtimestamp(&begin, "XGetImage");
420   }
421
422 #define COMPUTE_SHIFT_MASK(ix, rgb) \
423   compute_shift_mask(&shiftmasks[ix], im_use->rgb##_mask)
424   COMPUTE_SHIFT_MASK(0, blue);
425   COMPUTE_SHIFT_MASK(1, green);
426   COMPUTE_SHIFT_MASK(2, red);
427   
428   if (!*output)
429     *output= alloc_rgb_image(wwidth, wheight);
430
431   rtimestamp(&begin, "compute_shift_masks+alloc_rgb_image");
432
433   int x,y,i;
434   uint32_t *op32= (*output)->data;
435   for (y=0; y<wheight; y++) {
436     if (im_use->xoffset == 0 &&
437         im_use->format == ZPixmap &&
438         im_use->byte_order == LSBFirst &&
439         im_use->depth == 24 &&
440         im_use->bits_per_pixel == 32 &&
441         im_use->red_mask   == 0x0000ffU &&
442         im_use->green_mask == 0x00ff00U &&
443         im_use->blue_mask  == 0xff0000U) {
444       const char *p= im_use->data + y * im_use->bytes_per_line;
445 //      debugf("optimised copy y=%d",y);
446       memcpy(op32, p, wwidth*sizeof(*op32));
447       op32 += wwidth;
448     } else {
449       for (x=0; x<wwidth; x++) {
450         long xrgb= XGetPixel(im_use,x,y);
451         Rgb sample= 0;
452         for (i=0; i<3; i++) {
453           sample <<= 8;
454           sample |=
455             ((xrgb << shiftmasks[i].lshift) >> shiftmasks[i].rshift)
456             & SAMPLEMASK;
457         }
458         *op32++= sample;
459       }
460     }
461   }
462
463   rtimestamp(&begin,"w*h*XGetPixel");
464   if (im_free)
465     XDestroyImage(im_free);
466   
467   rtimestamp(&begin,"XDestroyImage");
468   check_not_disturbed();
469
470   debugf("PAGING   snapshot done.\n");
471 }
472
473 static int identical(const Snapshot *a, const Snapshot *b) {
474   if (!(a->w == b->w &&
475         a->h == b->h))
476     return 0;
477
478   int compare_to= a->h;
479   if (max_relevant_y>=0 && compare_to > max_relevant_y)
480     compare_to= max_relevant_y;
481   
482   return !memcmp(a->data, b->data, a->w * 3 * compare_to);
483 }
484
485 static void wait_for_stability(Snapshot **output,
486                                const Snapshot *previously,
487                                void (*with_keypress)(void),
488                                const char *fmt, ...)
489      FMT(4,5);
490
491 static void wait_for_stability(Snapshot **output,
492                                const Snapshot *previously,
493                                void (*with_keypress)(void),
494                                const char *fmt, ...) {
495   va_list al;
496   va_start(al,fmt);
497
498   Snapshot *last=0;
499   int nidentical=0;
500   /* waits longer if we're going to return an image identical to previously
501    * if previously==0, all images are considered identical to it */
502
503   char *doing;
504   sysassert( vasprintf(&doing,fmt,al) >=0 );
505
506   debugf("PAGING  wait_for_stability"
507           "  last_input=%f previously=%p `%s'\n",
508           last_input, previously, doing);
509
510   double max_interval= 1.000;
511   double min_interval= 0.100;
512   for (;;) {
513     progress_spinner("%s",doing);
514     
515     double since_last_input= timestamp() - last_input;
516     double this_interval= min_interval - since_last_input;
517     if (this_interval > max_interval) this_interval= max_interval;
518
519     if (this_interval >= 0)
520       delay(this_interval);
521
522     snapshot(output);
523
524     if (!last) {
525       debugf("PAGING  wait_for_stability first...\n");
526       last=*output; *output=0;
527     } else if (!identical(*output,last)) {
528       debugf("PAGING  wait_for_stability changed...\n");
529       free_snapshot(&last); last=*output; *output=0;
530       nidentical=0;
531       if (!with_keypress) {
532         min_interval *= 3.0;
533         min_interval += 0.1;
534       }
535     } else {
536       nidentical++;
537       int threshold=
538         !previously ? 3 :
539         identical(*output,previously) ? 5
540         : 1;
541       debugf("PAGING  wait_for_stability nidentical=%d threshold=%d\n",
542               nidentical, threshold);
543       if (nidentical >= threshold)
544         break;
545
546       min_interval += 0.1;
547       min_interval *= 2.0;
548     }
549
550     if (with_keypress)
551       with_keypress();
552   }
553
554   free_snapshot(&last);
555   free(doing);
556   debugf("PAGING  wait_for_stability done.\n");
557   va_end(al);
558 }
559
560 static void raise_and_get_details(void) {
561   int evbase,errbase,majver,minver;
562   int wxpos, wypos;
563   unsigned bd,depth;
564
565   progress("raising and checking YPP client window...");
566
567   debugf("PAGING raise_and_get_details\n");
568
569   int xtest= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
570   if (!xtest) fatal("X server does not support the XTEST extension.");
571
572   xassert( XRaiseWindow(disp, id) );
573   /* in case VisibilityNotify triggers right away before we have had a
574    * change to raise; to avoid falsely detecting lowering in that case */
575   
576   xassert( XSelectInput(disp, id,
577                         StructureNotifyMask|
578                         VisibilityChangeMask
579                         ) );
580
581   xassert( XRaiseWindow(disp, id) );
582   /* in case the window was lowered between our Raise and our SelectInput;
583    * to avoid failing to detect that lowering */
584
585   xassert( XGetWindowAttributes(disp, id, &attr) );
586   xassert( XGetGeometry(disp,id, &attr.root,
587                         &wxpos,&wypos, &wwidth,&wheight,
588                         &bd,&depth) );
589
590   if (!(wwidth >= 320 && wheight >= 320))
591     fatal("YPP client window is implausibly small?");
592
593   if (attr.depth < 24)
594     fatal("Display is not 24bpp.");
595
596   check_client_window_all_on_screen();
597
598   Bool shmpixmaps=0;
599   int major=0,minor=0;
600   int shm= XShmQueryVersion(disp, &major,&minor,&shmpixmaps);
601   debugf("PAGING shm=%d %d.%d pixmaps=%d\n",shm,major,minor,shmpixmaps);
602   if (shm) {
603     xassert( shmim= XShmCreateImage(disp, attr.visual, attr.depth, ZPixmap,
604                                     0,&shminfo, wwidth,wheight) );
605
606     sigset_t oldset, all;
607     sigfillset(&all);
608     sysassert(! sigprocmask(SIG_BLOCK,&all,&oldset) );
609
610     int pfd[2];
611     pid_t cleaner;
612     sysassert(! pipe(pfd) );
613     sysassert( (cleaner= fork()) != -1 );
614     if (!cleaner) {
615       sysassert(! close(pfd[1]) );
616       for (;;) {
617         int r= read(pfd[0], &shminfo.shmid, sizeof(shminfo.shmid));
618         if (!r) exit(0);
619         if (r==sizeof(shminfo.shmid)) break;
620         assert(r==-1 && errno==EINTR);
621       }
622       for (;;) {
623         char bc;
624         int r= read(pfd[0],&bc,1);
625         if (r>=0) break;
626         assert(r==-1 && errno==EINTR);
627       }
628       sysassert(! shmctl(shminfo.shmid,IPC_RMID,0) );
629       exit(0);
630     }
631     sysassert(! close(pfd[0]) );
632
633     sysassert(! sigprocmask(SIG_SETMASK,&oldset,0) );
634
635     assert(shmim->height == wheight);
636     sysassert( (shminfo.shmid=
637                 shmget(IPC_PRIVATE, shmim->bytes_per_line * wheight,
638                        IPC_CREAT|0600)) >= 0 );
639
640     sysassert( write(pfd[1],&shminfo.shmid,sizeof(shminfo.shmid)) ==
641                sizeof(shminfo.shmid) );
642     sysassert( shminfo.shmaddr= shmat(shminfo.shmid,0,0) );
643     shmim->data= shminfo.shmaddr;
644     shminfo.readOnly= False;
645     xassert( XShmAttach(disp,&shminfo) );
646
647     close(pfd[1]); /* causes IPC_RMID */
648   }
649 }
650
651 static void set_focus_commodity(void) {
652   int screen= XScreenNumberOfScreen(attr.screen);
653
654   progress("taking control of YPP client window...");
655
656   debugf("PAGING set_focus\n");
657
658   send_mouse_1_updown(commod_focus_point.x, commod_focus_point.y);
659   sync_after_input();
660
661   delay(0.5);
662   xassert( XSelectInput(disp, id,
663                         StructureNotifyMask|
664                         VisibilityChangeMask|
665                         FocusChangeMask
666                         ) );
667
668   int xpos,ypos;
669   translate_coords_toroot_p(commod_page_point, &xpos,&ypos);
670   XTestFakeMotionEvent(disp, screen, xpos,ypos, 0);
671
672   sync_after_input();
673
674   debugf("PAGING raise_and_set_focus done.\n");
675 }
676
677 static CanonImage *convert_page(const Snapshot *sn, RgbImage **rgb_r) {
678   CanonImage *im;
679   RgbImage *ri;
680
681   fwrite_ppmraw(screenshot_file, sn);
682
683   const Rgb *pixel= sn->data;
684   CANONICALISE_IMAGE(im, sn->w, sn->h, ri, {
685     rgb= *pixel++;
686   });
687
688   sysassert(!ferror(screenshot_file));
689   sysassert(!fflush(screenshot_file));
690
691   if (rgb_r) *rgb_r= ri;
692   else free(ri);
693
694   return im;
695 }
696
697 static void prepare_ypp_client(void) {
698   CanonImage *test;
699   Snapshot *current=0;
700   
701   /* find the window and check it's on the right kind of screen */
702   raise_and_get_details();
703   wait_for_stability(&current,0,0, "checking current YPP client screen...");
704
705   test= convert_page(current,0);
706   find_structure(test,0, &max_relevant_y,
707                  &commod_focus_point,
708                  &commod_page_point,
709                  &commod_focuslast_point);
710   check_correct_commodities();
711   Rect sunshine= find_sunshine_widget();
712
713   progress("poking client...");
714   send_mouse_1_updown((sunshine.tl.x   + sunshine.br.x) / 2,
715                       (sunshine.tl.y*9 + sunshine.br.y) / 10);
716   sync_after_input();
717
718   free(test);
719
720   wait_for_stability(&current,0,0, "checking basic YPP client screen...");
721   send_mouse_1_updown(250, wheight-10);
722   send_mouse_1_updown_here();
723   send_mouse_1_updown_here();
724   sync_after_input();
725   check_not_disturbed();
726   SEND_KEY(XK_slash);
727   SEND_KEY(XK_w);
728   SEND_KEY(XK_Return);
729   sync_after_input();
730
731   Snapshot *status=0;
732   wait_for_stability(&status,current,0, "awaiting status information...");
733   free_snapshot(&current);
734   free_snapshot(&status);
735 }
736
737 static void convert_store_page(Snapshot *current) {
738   RgbImage *rgb;
739   CanonImage *ci;
740   PageStruct *pstruct;
741   
742   progress("page %d prescanning   ...",npages);
743   ci= convert_page(current,&rgb);
744
745   progress("page %d overview      ...",npages);
746   find_structure(ci,&pstruct, 0,0,0,0);
747
748   store_current_page(ci,pstruct,rgb);
749 }
750
751 void take_screenshots(void) {
752   Snapshot *current=0, *last=0;
753
754   prepare_ypp_client();
755   
756   /* page to the top - keep pressing page up until the image stops changing */
757   set_focus_commodity();
758   wait_for_stability(&current,0, send_pgup_many,
759                      "paging up to top of commodity list...");
760
761   /* now to actually page down */
762   for (;;) {
763     debugf("page %d paging\n",npages);
764
765     pgdown_by_mouse();
766
767     if (!(npages < MAX_PAGES))
768       fatal("Paging down seems to generate too many pages - max is %d.",
769             MAX_PAGES);
770
771     convert_store_page(current);
772     free_snapshot(&last); last=current; current=0;
773     debugf("PAGING page %d converted\n",npages);
774     npages++;
775
776     wait_for_stability(&current,last, 0,
777                        "page %d collecting    ...",
778                        npages);
779     if (identical(current,last)) {
780       free_snapshot(&current);
781       break;
782     }
783   }
784   progress("finishing with the YPP client...");
785   send_mouse_1_updown(commod_focuslast_point.x, commod_focuslast_point.y);
786   sync_after_input();
787   send_pgdown_torestore();
788   sync_after_input();
789
790   debugf("PAGING all done.\n");
791   progress_log("collected %d screenshots.",npages);
792   check_pager_motion(0,npages);
793 }    
794
795 void take_one_screenshot(void) {
796   Snapshot *current=0;
797
798   prepare_ypp_client();
799   wait_for_stability(&current,0,0, "taking screenshot...");
800   convert_store_page(current);
801   npages= 1;
802   progress_log("collected single screenshot.");
803 }
804
805 void set_yppclient_window(unsigned long wul) {
806   id= wul;
807 }
808
809 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
810
811 static int nfound;
812 static Atom wm_name;
813 static int screen;
814
815 static void findypp_recurse(int depth, int targetdepth, Window w) {
816   unsigned int nchildren;
817   int i;
818   Window *children=0;
819   Window gotroot, gotparent;
820
821   static const char prefix[]= "Puzzle Pirates - ";
822   static const char onthe[]= " on the ";
823   static const char suffix[]= " ocean";
824 #define S(x) ((int)sizeof((x))-1)
825
826   debugfind("FINDYPP %d/%d screen %d  %*s %lx",
827             depth,targetdepth,screen,
828             depth,"",(unsigned long)w);
829   
830   if (depth!=targetdepth) {
831     xassert( XQueryTree(disp,w,
832                         &gotroot,&gotparent,
833                         &children,&nchildren) );
834     debugfind(" nchildren=%d\n",nchildren);
835   
836     for (i=0; i<nchildren; i++) {
837       Window child= children[i];
838       findypp_recurse(depth+1, targetdepth, child);
839     }
840     XFree(children);
841     return;
842   }
843     
844
845   int gotfmt;
846   Atom gottype;
847   unsigned long len, gotbytesafter;
848   char *title;
849   unsigned char *gottitle=0;
850   xassert( !XGetWindowProperty(disp,w, wm_name,0,512, False,
851                                AnyPropertyType,&gottype, &gotfmt, &len,
852                                &gotbytesafter, &gottitle) );
853   title= (char*)gottitle;
854
855   if (DEBUGP(findypp)) {
856     debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
857     char *p;
858     for (p=title; p < title+len; p++) {
859       char c= *p;
860       if (c>=' ' && c<=126) fputc(c,debug);
861       else fprintf(debug,"\\x%02x",c & 0xff);
862     }
863     fputs("\": ",debug);
864   }
865
866 #define REQUIRE(pred)                                                   \
867   if (!(pred)) { debugfind(" failed test  %s\n", #pred); return; }      \
868   else
869
870   REQUIRE( gottype!=None );
871   REQUIRE( len );
872   REQUIRE( gotfmt==8 );
873
874   REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
875
876   char *spc1= strchr(  title        + S(prefix), ' ');  REQUIRE(spc1);
877   char *spc2= strrchr((title + len) - S(suffix), ' ');  REQUIRE(spc2);
878
879   REQUIRE( (title + len) - spc1  >= S(onthe)  + S(suffix) );
880   REQUIRE(  spc2         - title >= S(prefix) + S(onthe) );
881
882   REQUIRE( !memcmp(title,                   prefix, S(prefix)) );
883   REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix))  );
884   REQUIRE( !memcmp(spc1,                    onthe,  S(onthe))  );
885
886 #define ASSIGN(what, start, end)                        \
887   what= masprintf("%.*s", (int)((end)-(start)), start); \
888   if (o_##what) REQUIRE( !strcasecmp(o_##what, what) ); \
889   else
890
891   ASSIGN(ocean,  spc1 + S(onthe),   (title + len) - S(suffix));
892   ASSIGN(pirate, title + S(prefix),  spc1);
893
894   debugfind(" YES!\n");
895   id= w;
896   nfound++;
897   progress_log("found YPP client (0x%lx):"
898                " %s ocean - %s.",
899                (unsigned long)id, ocean, pirate);
900 }
901
902 void find_yppclient_window(void) {
903   int targetdepth;
904
905   nfound=0;
906   
907   if (id) return;
908   
909   progress("looking for YPP client window...");
910
911   xassert( (wm_name= XInternAtom(disp,"WM_NAME",True)) != None);
912
913   for (targetdepth=1; targetdepth<4; targetdepth++) {
914     for (screen=0; screen<ScreenCount(disp); screen++) {
915       debugfind("FINDYPP screen %d\n", screen);
916       findypp_recurse(0,targetdepth, RootWindow(disp,screen));
917     }
918     if (nfound) break;
919   }
920
921   if (nfound>1)
922     fatal("Found several possible YPP clients.   Close one,\n"
923           " disambiguate with --pirate or --ocean,"
924           " or specify --window-id.\n");
925   if (nfound<1)
926     fatal("Did not find %sYPP client."
927           " Use --window-id and/or report this as a fault.\n",
928           o_ocean || o_pirate ? "matching ": "");
929 }
930
931 void screenshot_startup(void) {
932   progress("starting...");
933   disp= XOpenDisplay(0);
934   if (!disp) fatal("Unable to open X11 display.");
935   sysassert(! gettimeofday(&tv_startup,0) );
936
937   keymap_startup();
938 }