chiark / gitweb /
wip finding window
[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 static int wxpos, wypos;
22
23 DEBUG_DEFINE_DEBUGF(pages)
24
25 static KeyCode keycode(KeySym sym) {
26   return XKeysymToKeycode(disp,sym);
27 }
28
29 void screenshot_startup(void) {
30   int r;
31   disp= XOpenDisplay(0);  eassert(disp);
32   r= gettimeofday(&tv_startup,0);  eassert(!r);
33 }
34
35 /*---------- pager ----------*/
36
37 typedef XImage Snapshot;
38
39 static double last_input;
40 static const double min_update_allowance= 0.25;
41
42 static double timestamp(void) {
43   struct timeval tv;
44   int r;
45   
46   r= gettimeofday(&tv,0);  eassert(!r);
47   double t= (tv.tv_sec - tv_startup.tv_sec) +
48             (tv.tv_usec - tv_startup.tv_usec) * 1e-6;
49   debugf("PAGING %f\n",t);
50   return t;
51 }
52 static void delay(double need_sleep) {
53   int r;
54   debugf("PAGING     delay %f\n",need_sleep);
55   r= usleep(need_sleep * 1e6);  eassert(!r);
56 }
57
58 static void sync_after_input(void) {
59   int r;
60   r= XSync(disp, False);  eassert(r);
61   last_input= timestamp();
62 }
63
64 static void send_key(KeySym sym) {
65   XTestFakeKeyEvent(disp, keycode(sym),1, 10);
66   XTestFakeKeyEvent(disp, keycode(sym),0, 10);
67 }
68
69 static void send_pgup_many(void) {
70   int i;
71   for (i=0; i<25; i++)
72     send_key(XK_Prior);
73   debugf("PAGING   PageUp x %d\n",i);
74   sync_after_input();
75 }
76 static void send_pgdown(void) {
77   send_key(XK_Next);
78   debugf("PAGING   PageDown\n");
79   sync_after_input();
80 }
81
82 static void free_snapshot(Snapshot **io) {
83   if (*io) XDestroyImage(*io);
84   *io= 0;
85 }
86
87 static void snapshot(Snapshot **output) {
88 //  char *cmd;
89 //  int r;
90 //  XImage *xim;
91   
92   free_snapshot(output);
93
94   debugf("PAGING   snapshot\n");
95
96   timestamp();
97   *output= XGetImage(disp,id, 0,0, wwidth,wheight, AllPlanes, ZPixmap);
98   timestamp();
99   
100   debugf("PAGING   snapshot done.\n");
101 }
102
103 static int identical(const Snapshot *a, const Snapshot *b) {
104   if (!(a->width == b->width &&
105         a->height == b->height &&
106         a->bytes_per_line == b->bytes_per_line &&
107         a->format == b->format))
108     return 0;
109   return !memcmp(a->data, b->data, a->bytes_per_line * a->height);
110 }
111
112 static void wait_for_stability(Snapshot **output,
113                                const Snapshot *previously,
114                                void (*with_keypress)(void)) {
115   Snapshot *last=0;
116   /* waits longer if we're going to return an image identical to previously
117    * if previously==0, all images are considered identical to it */
118
119   debugf("PAGING  wait_for_stability"
120           "  last_input=%f previously=%p\n",
121           last_input, previously);
122
123   for (;;) {
124     double at_snapshot= timestamp();
125     double need_sleep= min_update_allowance - (at_snapshot - last_input);
126     if (need_sleep > 0) { delay(need_sleep); continue; }
127
128     snapshot(output);
129
130     if (!with_keypress &&
131         !(previously && identical(*output,previously))) {
132       debugf("PAGING  wait_for_stability  simple\n");
133       break;
134     }
135
136     if (last && identical(*output,last)) {
137       debugf("PAGING  wait_for_stability  stabilised\n");
138       break;
139     }
140     
141     debugf("PAGING  wait_for_stability  retry\n");
142
143     free_snapshot(&last); last=*output; *output=0;
144
145     if (with_keypress)
146       with_keypress();
147
148     delay(0.5);
149   }
150
151   free_snapshot(&last);
152   debugf("PAGING  wait_for_stability done.\n");
153 }
154
155 static void raise_and_get_details(void) {
156   int r;
157   int evbase,errbase,majver,minver;
158   unsigned bd,depth;
159   Window dummy;
160   
161   debugf("PAGING raise_and_get_details\n");
162
163   r= XTestQueryExtension(disp, &evbase,&errbase,&majver,&minver);
164   eassert(r==True);
165
166   r= XRaiseWindow(disp, id);  eassert(r);
167
168   r= XGetWindowAttributes(disp, id, &attr);  eassert(r);
169   r= XGetGeometry(disp,id, &attr.root,
170                   &wxpos,&wypos, &wwidth,&wheight,
171                   &bd,&depth);
172   eassert(r);
173
174   r= XTranslateCoordinates(disp, id,attr.root, 160,160, &wxpos,&wypos,
175                            &dummy);
176   eassert(r);
177 }
178
179 static void set_focus(void) {
180   int screen= XScreenNumberOfScreen(attr.screen);
181
182   debugf("PAGING set_focus\n");
183
184   XTestFakeMotionEvent(disp,screen, wxpos,wypos, 0);
185
186   XTestFakeButtonEvent(disp,1,1, 50);
187   XTestFakeButtonEvent(disp,1,0, 50);
188
189   sync_after_input();
190   debugf("PAGING raise_and_set_focus done.\n");
191 }
192
193 #define SAMPLEMASK 0xfful
194
195 typedef struct {
196   int lshift, rshift;
197 } ShMask;
198
199 static void compute_shift_mask(ShMask *sm, unsigned long ximage_mask) {
200   sm->lshift= 0;
201   sm->rshift= 0;
202   
203   for (;;) {
204     if (ximage_mask <= (SAMPLEMASK>>1)) {
205       sm->lshift++;  ximage_mask <<= 1;
206     } else if (ximage_mask > SAMPLEMASK) {
207       sm->rshift++;  ximage_mask >>= 1;
208     } else {
209       break;
210     }
211     assert(!(sm->lshift && sm->rshift));
212   }
213   assert(sm->lshift < LONG_BIT);
214   assert(sm->rshift < LONG_BIT);
215 }
216
217 static CanonImage *convert_page(Snapshot *sn) {
218   ShMask shiftmasks[3];
219   CanonImage *im;
220
221   fprintf(screenshots_file,
222           "P6\n"
223           "%d %d\n"
224           "255\n", sn->width, sn->height);
225
226 #define COMPUTE_SHIFT_MASK(ix, rgb) \
227   compute_shift_mask(&shiftmasks[ix], sn->rgb##_mask)
228   COMPUTE_SHIFT_MASK(0, red);
229   COMPUTE_SHIFT_MASK(1, green);
230   COMPUTE_SHIFT_MASK(2, blue);
231
232   CANONICALISE_IMAGE(im, sn->width, sn->height, {
233     long xrgb= XGetPixel(sn, x, y);
234     int i;
235     rgb= 0;
236     for (i=0; i<3; i++) {
237       rgb <<= 8;
238       unsigned long sample=
239         ((xrgb << shiftmasks[i].lshift)
240               >> shiftmasks[i].rshift) & SAMPLEMASK;
241       rgb |= sample;
242       fputc(sample, screenshots_file);
243     }
244   });
245
246   eassert(!fflush(screenshots_file));
247
248   return im;
249 }
250
251 void take_screenshots(void) {
252   Snapshot *current=0, *last=0;
253   CanonImage *test;
254
255   /* find the window and check it's on the right kind of screen */
256   raise_and_get_details();
257   wait_for_stability(&current,0,0);
258   test= convert_page(current);
259   find_structure(test);
260   free(test);
261
262   /* page to the top - keep pressing page up until the image stops changing */
263   set_focus();
264   wait_for_stability(&current,0, send_pgup_many);
265
266   /* now to actually page down */
267   for (;;) {
268     debugf("paging page %d\n",npages);
269
270     eassert(npages < MAX_PAGES);
271     page_images[npages]= convert_page(current);
272     free_snapshot(&last); last=current; current=0;
273
274     debugf("PAGING page %d converted\n",npages);
275
276     wait_for_stability(&current,last, 0);
277     if (npages &&  /* first pagedown doesn't do much */
278         identical(current,last)) {
279       free_snapshot(&current);
280       break;
281     }
282
283     send_pgdown();
284     npages++;
285   }
286   debugf("PAGING all done.\n");
287 }    
288
289 void take_one_screenshot(void) {
290   Snapshot *current=0;
291   
292   raise_and_get_details();
293   sync_after_input();
294   wait_for_stability(&current,0,0);
295   page_images[0]= convert_page(current);
296   npages= 1;
297 }
298
299 void set_yppclient_window(unsigned long wul) {
300   id= wul;
301 }
302
303 DEBUG_DEFINE_SOME_DEBUGF(findypp,debugfind)
304
305 void find_yppclient_window(void) {
306   Window root, gotroot, gotparent;
307   int screen, r;
308   int nfound=0;
309   
310   if (id) return;
311   
312   static const char prefix[]= "Puzzle Pirates - ";
313   static const char onthe[]= " on the ";
314   static const char suffix[]= " ocean";
315 #define S(x) (sizeof((x))-1)
316
317   Atom wm_name= XInternAtom(disp,"WM_NAME",True);
318   eassert(wm_name != None);
319
320   for (screen=0; screen<ScreenCount(disp); screen++) {
321     debugfind("FINDYPP screen %d\n", screen);
322     root= RootWindow(disp,screen);
323     unsigned int nchildren1;
324     Window *children1=0;
325
326     r= XQueryTree(disp,root,
327                   &gotroot,&gotparent,
328                   &children1,&nchildren1);
329     eassert(r);
330     debugfind("FINDYPP screen %d nchildren1=%d\n", screen, nchildren1);
331
332     int i;
333     for (i=0; i<nchildren1; i++) {
334       Window w1= children1[i];
335       unsigned int nchildren2;
336       Window *children2=0;
337
338       r= XQueryTree(disp,w1,
339                     &gotroot,&gotparent,
340                     &children2,&nchildren2);
341       eassert(r);
342       debugfind("FINDYPP screen %d c1[%2d]=0x%08lx nchildren2=%d\n",
343                 screen, i, (unsigned long)w1, nchildren2);
344
345       int j;
346       for (j=-1; j<(int)nchildren2; j++) {
347         Window w2= j<0 ? w1 : children2[j];
348         debugfind("FINDYPP screen %d c1[%2d]=0x%08lx c2[%2d]=0x%08lx",
349                   screen, i, (unsigned long)w1, j, (unsigned long)w2);
350
351         int gotfmt;
352         Atom gottype;
353         unsigned long len, gotbytesafter;
354         char *title;
355         unsigned char *gottitle=0;
356         r= XGetWindowProperty(disp,w2, wm_name,0,512, False,
357                               AnyPropertyType,&gottype, &gotfmt, &len,
358                               &gotbytesafter, &gottitle);
359         eassert(!r);
360         title= (char*)gottitle;
361
362         if (DEBUGP(findypp)) {
363           debugfind(" gf=%d len=%lu gba=%lu \"", gotfmt,len,gotbytesafter);
364           char *p;
365           for (p=title; p < title+len; p++) {
366             char c= *p;
367             if (c>=' ' && c<=126) fputc(c,debug);
368             else fprintf(debug,"\\x%02x",c & 0xff);
369           }
370           fputs("\": ",debug);
371         }
372
373 #define REQUIRE(pred)                                                      \
374         if (!(pred)) { debugfind(" failed test  %s\n", #pred); continue; } \
375         else
376
377         REQUIRE( gottype!=None );
378         REQUIRE( len );
379         REQUIRE( gotfmt==8 );
380
381         REQUIRE( len >= S(prefix) + 1 + S(onthe) + 1 + S(suffix) );
382
383         char *spc1= strchr(  title        + S(prefix), ' ');  REQUIRE(spc1);
384         char *spc2= strrchr((title + len) - S(suffix), ' ');  REQUIRE(spc2);
385
386         REQUIRE( (title + len) - spc1  >= S(onthe)  + S(suffix) );
387         REQUIRE(  spc2         - title >= S(prefix) + S(onthe) );
388
389         REQUIRE( !memcmp(title,                   prefix, S(prefix)) );
390         REQUIRE( !memcmp(title + len - S(suffix), suffix, S(suffix))  );
391         REQUIRE( !memcmp(spc1,                    onthe,  S(onthe))  );
392
393 #define ASSIGN(what, start, end) do {                                   \
394         r= asprintf(&what, "%.*s", end - start, start);  eassert(r>0);  \
395      }while(0)
396         ASSIGN(ocean,  title + S(prefix),  spc1);
397         ASSIGN(pirate, spc1 + S(onthe),   (title + len) - S(suffix));
398
399         debugfind(" YES!\n");
400         id= w2;
401         nfound++;
402       }
403       if (children2) XFree(children2);
404     }
405     if (children1) XFree(children1);
406   }
407   eassert(nfound==1);
408 }