chiark / gitweb /
Much better error handling.
[ypp-sc-tools.web-live.git] / pctb / pages.c
1 /*
2   */
3
4 #include "structure.h"
5
6 #include <X11/Xlib.h>
7 #include <X11/extensions/XTest.h>
8 #include <X11/keysym.h>
9 #include <X11/Xutil.h>
10
11 CanonImage *page_images[MAX_PAGES];
12 int npages;
13
14 char *ocean, *pirate;
15
16 static XWindowAttributes attr;
17 static Window id;
18 static Display *disp;
19 static struct timeval tv_startup;
20 static unsigned wwidth, wheight;
21
22 DEBUG_DEFINE_DEBUGF(pages)
23
24 #define xassert(what)                                   \
25   ((what) ? (void)0 :                                   \
26    fatal("X11 operation unexpectedly failed."           \
27          " %s:%d: %s\n", __FILE__,__LINE__,#what))
28
29 static KeyCode keycode(KeySym sym) {
30   return XKeysymToKeycode(disp,sym);
31 }
32
33 void screenshot_startup(void) {
34   progress("starting...");
35   disp= XOpenDisplay(0);
36   if (!disp) fatal("Unable to open X11 display.");
37   sysassert(! gettimeofday(&tv_startup,0) );
38 }
39
40 /*---------- pager ----------*/
41
42 typedef XImage Snapshot;
43
44 static double last_input;
45 static const double min_update_allowance= 0.25;
46
47 static double timestamp(void) {
48   struct timeval tv;
49   
50   sysassert(! gettimeofday(&tv,0) );
51   double t= (tv.tv_sec - tv_startup.tv_sec) +
52             (tv.tv_usec - tv_startup.tv_usec) * 1e-6;
53   debugf("PAGING %f\n",t);
54   return t;
55 }
56 static void delay(double need_sleep) {
57   debugf("PAGING     delay %f\n",need_sleep);
58   sysassert(! usleep(need_sleep * 1e6) );
59 }
60
61 static void sync_after_input(void) {
62   xassert( XSync(disp, False) );
63   last_input= timestamp();
64 }
65
66 static void translate_coords_toroot(int wx, int wy, int *rx, int *ry) {
67   Window dummy;
68   xassert( XTranslateCoordinates(disp, id,attr.root, wx,wy, rx,ry, &dummy) );
69 }
70
71 static void check_client_window_all_on_screen(void) {
72   Rect onroot;
73   unsigned rwidth, rheight;
74   Window dummy;
75   unsigned bd, depth;
76   int rxpos, rypos;
77
78   xassert( XGetGeometry(disp,attr.root, &dummy, &rxpos,&rypos,
79                         &rwidth, &rheight,
80                         &bd,&depth) );
81   
82   translate_coords_toroot(0,0, &onroot.tl.x,&onroot.tl.y);
83   translate_coords_toroot(wwidth-1,wheight-1, &onroot.br.x,&onroot.br.y);
84   if (!(onroot.tl.x >= 0 &&
85         onroot.tl.y >= 0 &&
86         onroot.br.x < rwidth &&
87         onroot.br.y < rheight))
88     fatal("YPP client window is not entirely on the screen.");
89 }
90
91 static void check_not_disturbed(void) {
92   XEvent ev;
93   int r;
94   
95   for (;;) {
96     r= XCheckMaskEvent(disp, ~0, &ev);
97     if (r==False) return;
98
99     switch (ev.type) {
100     case VisibilityNotify:
101       if (ev.xvisibility.state != VisibilityUnobscured)
102         fatal("YPP client window has become obscured.");
103       break;
104     case ConfigureNotify:
105       check_client_window_all_on_screen();
106       break;
107     case FocusOut:
108       fatal("Focus left YPP client window.");
109       break;
110     case FocusIn:
111       warning("focus entered YPP client window ?!");
112       break;
113     default:
114       fatal("Received unexpected X11 event (type code %d)!", ev.type);
115     }
116   }
117 }      
118
119 static void send_key(KeySym sym) {
120   XTestFakeKeyEvent(disp, keycode(sym),1, 10);
121   XTestFakeKeyEvent(disp, keycode(sym),0, 10);
122 }
123
124 static void send_pgup_many(void) {
125   int i;
126   for (i=0; i<25; i++)
127     send_key(XK_Prior);
128   debugf("PAGING   PageUp x %d\n",i);
129   sync_after_input();
130 }
131 static void send_pgdown(void) {
132   send_key(XK_Next);
133   debugf("PAGING   PageDown\n");
134   sync_after_input();
135 }
136
137 static void free_snapshot(Snapshot **io) {
138   if (*io) XDestroyImage(*io);
139   *io= 0;
140 }
141
142 static void snapshot(Snapshot **output) {
143   free_snapshot(output);
144
145   debugf("PAGING   snapshot\n");
146
147   timestamp();
148   *output= XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap);
149   timestamp();
150
151   check_not_disturbed();
152
153   debugf("PAGING   snapshot done.\n");
154 }
155
156 static int identical(const Snapshot *a, const Snapshot *b) {
157   if (!(a->width == b->width &&
158         a->height == b->height &&
159         a->bytes_per_line == b->bytes_per_line &&
160         a->format == b->format))
161     return 0;
162   return !memcmp(a->data, b->data, a->bytes_per_line * a->height);
163 }
164
165 static void wait_for_stability(Snapshot **output,
166                                const Snapshot *previously,
167                                void (*with_keypress)(void),
168                                const char *fmt, ...)
169      FMT(4,5);
170
171 static void wait_for_stability(Snapshot **output,
172                                const Snapshot *previously,
173                                void (*with_keypress)(void),
174                                const char *fmt, ...) {
175   va_list al;
176   va_start(al,fmt);
177
178   Snapshot *last=0;
179   /* waits longer if we're going to return an image identical to previously
180    * if previously==0, all images are considered identical to it */
181
182   debugf("PAGING  wait_for_stability"
183           "  last_input=%f previously=%p\n",
184           last_input, previously);
185
186   char *doing;
187   sysassert( vasprintf(&doing,fmt,al) >=0);
188
189   progress("%s",doing);
190
191   for (;;) {
192     double at_snapshot= timestamp();
193     double need_sleep= min_update_allowance - (at_snapshot - last_input);
194     if (need_sleep > 0) { delay(need_sleep); continue; }
195
196     snapshot(output);
197
198     if (!with_keypress &&
199         !(previously && identical(*output,previously))) {
200       debugf("PAGING  wait_for_stability  simple\n");
201       break;
202     }
203
204     if (last && identical(*output,last)) {
205       debugf("PAGING  wait_for_stability  stabilised\n");
206       break;
207     }
208     
209     progress_spinner("%s",doing);
210
211     debugf("PAGING  wait_for_stability  retry\n");
212
213     free_snapshot(&last); last=*output; *output=0;
214
215     if (with_keypress)
216       with_keypress();
217
218     delay(0.5);
219   }
220
221   free_snapshot(&last);
222   free(doing);
223   debugf("PAGING  wait_for_stability done.\n");
224   va_end(al);
225 }
226
227 static void raise_and_get_details(void) {
228   int evbase,errbase,majver,minver;
229   int wxpos, wypos;
230   unsigned bd,depth;
231
232   progress("raising and checking YPP client window...");
233
234   debugf("PAGING raise_and_get_details\n");
235
236   int xtest= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
237   if (!xtest) fatal("X server does not support the XTEST extension.");
238
239   xassert( XRaiseWindow(disp, id) );
240   /* in case VisibilityNotify triggers right away before we have had a
241    * change to raise; to avoid falsely detecting lowering in that case */
242   
243   xassert( XSelectInput(disp, id,
244                         StructureNotifyMask|
245                         VisibilityChangeMask
246                         ) );
247
248   xassert( XRaiseWindow(disp, id) );
249   /* in case the window was lowered between our Raise and our SelectInput;
250    * to avoid failing to detect that lowering */
251
252   xassert( XGetWindowAttributes(disp, id, &attr) );
253   xassert( XGetGeometry(disp,id, &attr.root,
254                         &wxpos,&wypos, &wwidth,&wheight,
255                         &bd,&depth) );
256
257   if (!(wwidth >= 320 && wheight >= 320))
258     fatal("YPP client window is implausibly small?");
259
260   check_client_window_all_on_screen();
261 }
262
263 static void set_focus(void) {
264   int screen= XScreenNumberOfScreen(attr.screen);
265
266   progress("taking control of YPP client window...");
267
268   debugf("PAGING set_focus\n");
269
270   int xpos, ypos;
271   translate_coords_toroot(160,160, &xpos,&ypos);
272   XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
273
274   XTestFakeButtonEvent(disp,1,1, 50);
275   XTestFakeButtonEvent(disp,1,0, 50);
276
277   sync_after_input();
278
279   delay(0.5);
280   xassert( XSelectInput(disp, id,
281                         StructureNotifyMask|
282                         VisibilityChangeMask|
283                         FocusChangeMask
284                         ) );
285
286   translate_coords_toroot(10,10, &xpos,&ypos);
287   XTestFakeMotionEvent(disp,screen, xpos,ypos, 0);
288
289   sync_after_input();
290
291   debugf("PAGING raise_and_set_focus done.\n");
292 }
293
294 #define SAMPLEMASK 0xfful
295
296 typedef struct {
297   int lshift, rshift;
298 } ShMask;
299
300 static void compute_shift_mask(ShMask *sm, unsigned long ximage_mask) {
301   sm->lshift= 0;
302   sm->rshift= 0;
303   
304   for (;;) {
305     if (ximage_mask <= (SAMPLEMASK>>1)) {
306       sm->lshift++;  ximage_mask <<= 1;
307     } else if (ximage_mask > SAMPLEMASK) {
308       sm->rshift++;  ximage_mask >>= 1;
309     } else {
310       break;
311     }
312     assert(!(sm->lshift && sm->rshift));
313   }
314   assert(sm->lshift < LONG_BIT);
315   assert(sm->rshift < LONG_BIT);
316 }
317
318 static CanonImage *convert_page(Snapshot *sn) {
319   ShMask shiftmasks[3];
320   CanonImage *im;
321
322   fprintf(screenshots_file,
323           "P6\n"
324           "%d %d\n"
325           "255\n", sn->width, sn->height);
326
327 #define COMPUTE_SHIFT_MASK(ix, rgb) \
328   compute_shift_mask(&shiftmasks[ix], sn->rgb##_mask)
329   COMPUTE_SHIFT_MASK(0, red);
330   COMPUTE_SHIFT_MASK(1, green);
331   COMPUTE_SHIFT_MASK(2, blue);
332
333   CANONICALISE_IMAGE(im, sn->width, sn->height, {
334     long xrgb= XGetPixel(sn, x, y);
335     int i;
336     rgb= 0;
337     for (i=0; i<3; i++) {
338       rgb <<= 8;
339       unsigned long sample=
340         ((xrgb << shiftmasks[i].lshift)
341               >> shiftmasks[i].rshift) & SAMPLEMASK;
342       rgb |= sample;
343       fputc(sample, screenshots_file);
344     }
345   });
346
347   sysassert(!ferror(screenshots_file));
348   sysassert(!fflush(screenshots_file));
349
350   return im;
351 }
352
353 void take_screenshots(void) {
354   Snapshot *current=0, *last=0;
355   CanonImage *test;
356
357   /* find the window and check it's on the right kind of screen */
358   raise_and_get_details();
359   wait_for_stability(&current,0,0, "checking current YPP client screen...");
360   test= convert_page(current);
361   find_structure(test);
362   free(test);
363
364   /* page to the top - keep pressing page up until the image stops changing */
365   set_focus();
366   wait_for_stability(&current,0, send_pgup_many,
367                      "paging up to top of commodity list...");
368
369   /* now to actually page down */
370   for (;;) {
371     debugf("paging page %d\n",npages);
372
373     if (!(npages < MAX_PAGES))
374       fatal("Paging down seems to generate too many pages - max is %d.",
375             MAX_PAGES);
376     
377     page_images[npages]= convert_page(current);
378     free_snapshot(&last); last=current; current=0;
379
380     debugf("PAGING page %d converted\n",npages);
381
382     wait_for_stability(&current,last, 0,
383                        "collecting screenshot of page %d...",
384                        npages+1);
385
386     if (npages &&  /* first pagedown doesn't do much */
387         identical(current,last)) {
388       free_snapshot(&current);
389       break;
390     }
391
392     send_pgdown();
393     npages++;
394   }
395   debugf("PAGING all done.\n");
396   progress_log("collected %d screenshots.",npages);
397 }    
398
399 void take_one_screenshot(void) {
400   Snapshot *current=0;
401   
402   raise_and_get_details();
403   sync_after_input();
404   wait_for_stability(&current,0,0, "taking screenshot...");
405   page_images[0]= convert_page(current);
406   npages= 1;
407   progress_log("collected single screenshot.");
408 }
409
410 void set_yppclient_window(unsigned long wul) {
411   id= wul;
412 }
413
414 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
415
416 void find_yppclient_window(void) {
417   Window root, gotroot, gotparent;
418   int screen;
419   int nfound=0;
420   
421   if (id) return;
422   
423   progress("looking for YPP client window...");
424
425   static const char prefix[]= "Puzzle Pirates - ";
426   static const char onthe[]= " on the ";
427   static const char suffix[]= " ocean";
428 #define S(x) (sizeof((x))-1)
429
430   Atom wm_name= XInternAtom(disp,"WM_NAME",True);
431   xassert(wm_name != None);
432
433   for (screen=0; screen<ScreenCount(disp); screen++) {
434     debugfind("FINDYPP screen %d\n", screen);
435     root= RootWindow(disp,screen);
436     unsigned int nchildren1;
437     Window *children1=0;
438
439     xassert( XQueryTree(disp,root,
440                   &gotroot,&gotparent,
441                   &children1,&nchildren1) );
442     debugfind("FINDYPP screen %d nchildren1=%d\n", screen, nchildren1);
443
444     int i;
445     for (i=0; i<nchildren1; i++) {
446       Window w1= children1[i];
447       unsigned int nchildren2;
448       Window *children2=0;
449
450       xassert( XQueryTree(disp,w1,
451                           &gotroot,&gotparent,
452                           &children2,&nchildren2) );
453       debugfind("FINDYPP screen %d c1[%2d]=0x%08lx nchildren2=%d\n",
454                 screen, i, (unsigned long)w1, nchildren2);
455
456       int j;
457       for (j=-1; j<(int)nchildren2; j++) {
458         Window w2= j<0 ? w1 : children2[j];
459         debugfind("FINDYPP screen %d c1[%2d]=0x%08lx c2[%2d]=0x%08lx",
460                   screen, i, (unsigned long)w1, j, (unsigned long)w2);
461
462         int gotfmt;
463         Atom gottype;
464         unsigned long len, gotbytesafter;
465         char *title;
466         unsigned char *gottitle=0;
467         xassert( !XGetWindowProperty(disp,w2, wm_name,0,512, False,
468                                      AnyPropertyType,&gottype, &gotfmt, &len,
469                                      &gotbytesafter, &gottitle) );
470         title= (char*)gottitle;
471
472         if (DEBUGP(findypp)) {
473           debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
474           char *p;
475           for (p=title; p < title+len; p++) {
476             char c= *p;
477             if (c>=' ' && c<=126) fputc(c,debug);
478             else fprintf(debug,"\\x%02x",c & 0xff);
479           }
480           fputs("\": ",debug);
481         }
482
483 #define REQUIRE(pred)                                                      \
484         if (!(pred)) { debugfind(" failed test  %s\n", #pred); continue; } \
485         else
486
487         REQUIRE( gottype!=None );
488         REQUIRE( len );
489         REQUIRE( gotfmt==8 );
490
491         REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
492
493         char *spc1= strchr(  title        + S(prefix), ' ');  REQUIRE(spc1);
494         char *spc2= strrchr((title + len) - S(suffix), ' ');  REQUIRE(spc2);
495
496         REQUIRE( (title + len) - spc1  >= S(onthe)  + S(suffix) );
497         REQUIRE(  spc2         - title >= S(prefix) + S(onthe) );
498
499         REQUIRE( !memcmp(title,                   prefix, S(prefix)) );
500         REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix))  );
501         REQUIRE( !memcmp(spc1,                    onthe,  S(onthe))  );
502
503 #define ASSIGN(what, start, end) do {                                   \
504         sysassert( asprintf(&what, "%.*s", (end)-(start), start) >0 );  \
505      }while(0)
506         ASSIGN(pirate, title + S(prefix),  spc1);
507         ASSIGN(ocean,  spc1 + S(onthe),   (title + len) - S(suffix));
508
509         debugfind(" YES!\n");
510         id= w2;
511         nfound++;
512         progress_log("found YPP client (0x%lx):"
513                      " %s ocean - %s.",
514                      (unsigned long)id, ocean, pirate);
515       }
516       if (children2) XFree(children2);
517     }
518     if (children1) XFree(children1);
519   }
520   if (nfound>1)
521     fatal("Found several YPP clients."
522           " Close one, or specify the windowid with --window-id.\n");
523   if (nfound<1)
524     fatal("Did not find YPP client."
525           " Use --window-id and/or report this as a fault.\n");
526 }