chiark / gitweb /
mention need to turn off antialias
[ypp-sc-tools.main.git] / pctb / convert.c
1 /*
2  * ypp-commodities main program: argument parsing etc.
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 #include "convert.h"
29
30 void debug_flush(void) {
31   sysassert(!ferror(debug));
32   sysassert(!fflush(debug));
33 }
34
35 const char *get_vardir(void) { return "."; }
36 const char *get_libdir(void) { return "."; }
37
38
39 enum mode {
40   mf_findwindow=      0001,
41   mf_screenshot=      0010,
42   mf_readscreenshot=  0020,
43   mf_analyse=         0100,
44   
45   mode_findwindow=    0001,
46   mode_screenshot=    0011,
47   mode_analyse=       0120,
48
49   mode_all=           0111,
50 };
51
52 enum outmodekind {
53   omk_unset, omk_upload, omk_str, omk_raw, omk_none
54 };
55 static enum outmodekind o_outmode_kind;
56 static const char *o_outmode_str= 0;
57
58 static enum mode o_mode= mode_all;
59 static char *o_screenshot_fn;
60 static const char *o_serv_pctb, *o_serv_dict_fetch, *o_serv_dict_submit;
61
62 const char *o_resolver= "./dictionary-manager";
63 FILE *screenshot_file;
64 const char *o_ocean, *o_pirate;
65 int o_quiet;
66
67 enum flags o_flags= ff_dict_fetch|ff_dict_submit|ff_dict_pirate;
68
69 static void vbadusage(const char *fmt, va_list) FMT(1,0) NORET;
70 static void vbadusage(const char *fmt, va_list al) {
71   fputs("bad usage: ",stderr);
72   vfprintf(stderr,fmt,al);
73   fputc('\n',stderr);
74   exit(12);
75 }
76 DEFINE_VWRAPPERF(static, badusage, NORET);
77
78 static void open_screenshot_file(const char *mode) {
79   screenshot_file= fopen(o_screenshot_fn, mode);
80   if (!screenshot_file)
81     fatal("could not open screenshots file `%s': %s",
82           o_screenshot_fn, strerror(errno));
83 }
84
85 static void run_analysis(void) {
86   FILE *tf;
87
88   sysassert( tf= tmpfile() );
89   progress("running recognition...");
90   analyse(tf);
91
92   if (o_flags & ff_upload) {
93     if (o_flags & ff_singlepage)
94       fatal("Recognition successful, but refusing to upload partial data\n"
95             " (--single-page specified).  Specify an output mode?");
96   }
97
98   sysassert( fseek(tf,0,SEEK_SET) == 0);
99
100   progress_log("processing results (--%s)...", o_outmode_str);
101   pid_t processor;
102   sysassert( (processor= fork()) != -1 );
103
104   if (!processor) {
105     sysassert( dup2(fileno(tf),0) ==0 );
106     EXECLP_HELPER("commod-results-processor", o_outmode_str, (char*)0);
107   }
108
109   waitpid_check_exitstatus(processor, "output processor/uploader");
110   fclose(tf);
111   progress_log("all complete.");
112 }
113
114 void fetch_with_rsync(const char *stem) {
115   pid_t fetcher;
116
117   sysassert( (fetcher= fork()) != -1 );
118   if (!fetcher) {
119     const char *rsync= getenv("YPPSC_PCTB_RSYNC");
120     if (!rsync) rsync= "rsync";
121   
122     const char *src= getenv("YPPSC_PCTB_DICT_UPDATE");
123     char *remote= masprintf("%s/master-%s.txt", src, stem);
124     char *local= masprintf("#master-%s#.txt", stem);
125     execlp(rsync, "rsync",
126            DEBUGP(rsync) ? "-vLt" : "-Lt",
127            "--",remote,local,(char*)0);
128     sysassert(!"exec rsync failed");
129   }
130
131   waitpid_check_exitstatus(fetcher, "rsync");
132 }
133
134 static void set_server(const char *envname, const char *defprotocol,
135                        const char *defvalue, const char *defvalue_test,
136                        const char *userspecified,
137                        int enable) {
138   const char *value;
139   
140   if (!enable) { value= "0"; goto ok; }
141
142   if (userspecified)
143     value= userspecified;
144   else if ((value= getenv(envname)))
145     ;
146   else if (o_flags & ff_testservers)
147     value= defvalue_test;
148   else
149     value= defvalue;
150
151   if (value[0]=='/' || (value[0]=='.' && value[1]=='/'))
152     /* absolute or relative pathname - or anyway, something with no hostname */
153     goto ok;
154
155   const char *colon= strchr(value, ':');
156   const char *slash= strchr(value, '/');
157
158   if (colon && (!slash || colon < slash))
159     /* colon before the first slash, if any */
160     /* rsync :: protocol specification - anyway, adding scheme:// won't help */
161     goto ok;
162
163   int vallen= strlen(value);
164
165   value= masprintf("%s%s%s", defprotocol, value,
166                    vallen && value[vallen-1]=='/' ? "" : "/");
167
168  ok:
169   sysassert(! setenv(envname,value,1) );
170 }
171
172 int main(int argc, char **argv) {
173   const char *arg;
174
175   sysassert( setlocale(LC_MESSAGES,"") );
176   sysassert( setlocale(LC_CTYPE,"en_GB.UTF-8") ||
177              setlocale(LC_CTYPE,"en.UTF-8") );
178
179 #define ARGVAL  ((*++argv) ? *argv : \
180                  (badusage("missing value for option %s",arg),(char*)0))
181
182 #define IS(s) (!strcmp(arg,(s)))
183
184   while ((arg=*++argv)) {
185     if (IS("--find-window-only"))      o_mode= mode_findwindow;
186     else if (IS("--screenshot-only"))  o_mode= mode_screenshot;
187     else if (IS("--analyse-only") ||
188              IS("--same"))             o_mode= mode_analyse;
189     else if (IS("--everything"))       o_mode= mode_all;
190     else if (IS("--find-island"))      o_flags |= ffs_printisland;
191     else if (IS("--single-page"))      o_flags |= ff_singlepage;
192     else if (IS("--quiet"))            o_quiet= 1;
193     else if (IS("--edit-charset"))     o_flags |= ff_editcharset;
194     else if (IS("--test-servers"))     o_flags |= ff_testservers;
195     else if (IS("--dict-local-only"))  o_flags &= ~ffs_dict;
196     else if (IS("--dict-read-only"))   o_flags &= (~ffs_dict | ff_dict_fetch);
197     else if (IS("--dict-anon"))        o_flags &= ~ff_dict_pirate;
198     else if (IS("--dict-submit"))      o_flags |= ff_dict_fetch|ff_dict_submit;
199     else if (IS("--raw-tsv"))          o_outmode_kind= omk_raw;
200     else if (IS("--upload"))           o_outmode_kind= omk_upload;
201     else if (IS("--arbitrage") ||
202              IS("--tsv") ||
203              IS("--best-prices"))      o_outmode_kind=omk_str,
204                                        o_outmode_str=arg+2;
205
206     else if (IS("--screenshot-file"))  o_screenshot_fn= ARGVAL;
207     else if (IS("--pctb-server"))         o_serv_pctb=        ARGVAL;
208     else if (IS("--dict-submit-server"))  o_serv_dict_submit= ARGVAL;
209     else if (IS("--dict-update-server"))  o_serv_dict_fetch=  ARGVAL;
210     else if (IS("--ocean"))            o_ocean=  ARGVAL;
211     else if (IS("--pirate"))           o_pirate= ARGVAL;
212 #define DF(f)                                   \
213     else if (IS("-D" #f))                       \
214       debug_flags |= dbg_##f;
215     DEBUG_FLAG_LIST
216 #undef DF
217     else if (IS("--window-id")) {
218       char *ep;
219       unsigned long windowid= strtoul(ARGVAL,&ep,0);
220       if (*ep) badusage("invalid window id");
221       set_yppclient_window(windowid);
222     } else
223       badusage("unknown option `%s'",arg);
224   }
225
226   /* Consequential changes to options */
227
228   if (o_mode & mf_analyse) {
229     if (!o_outmode_kind) {
230       if (o_flags & ff_printisland) {
231         o_outmode_kind= omk_none;
232         o_flags |= ff_singlepage;
233       } else {
234         o_outmode_kind= omk_str;
235       }
236     }
237
238     if (o_outmode_kind==omk_upload) {
239       o_flags |= ffs_upload;
240       o_outmode_str= "upload";
241     }
242   }
243
244   /* Defaults */
245   
246   set_server("YPPSC_PCTB_PCTB",
247              "http://",          "pctb.ilk.org" /*pctb.crabdance.com*/,
248                                  "pctb.ilk.org",
249              o_serv_pctb,        o_flags & (ff_needisland|ff_upload));
250              
251   set_server("YPPSC_PCTB_DICT_UPDATE",
252              "rsync://",         "rsync.pctb.chiark.greenend.org.uk/pctb",
253                                  "rsync.pctb.chiark.greenend.org.uk/pctb/test",
254              o_serv_dict_fetch,   o_flags & ff_dict_fetch);
255
256   set_server("YPPSC_PCTB_DICT_SUBMIT",
257              "http://",           "dictup.pctb.chiark.greenend.org.uk",
258                                   "dictup.pctb.chiark.greenend.org.uk/test",
259              o_serv_dict_submit,  o_flags & ff_dict_submit);
260
261   if (!o_screenshot_fn)
262     o_screenshot_fn= masprintf("%s/#pages#.ppm",get_vardir());
263
264   /* Actually do the work */
265              
266   if (o_mode & mf_findwindow) {
267     screenshot_startup();
268     find_yppclient_window();
269   }
270   if (!ocean)  ocean=  o_ocean;
271   if (!pirate) pirate= o_pirate;
272   
273   if (o_flags & ff_needisland)
274     if (!ocean)
275       badusage("need --ocean option when replaying images"
276                " (consider supplying --pirate too)");
277   if (ocean)
278     sysassert(! setenv("YPPSC_OCEAN",ocean,1) );
279   if (pirate && (o_flags & ff_dict_pirate))
280     sysassert(! setenv("YPPSC_PIRATE",pirate,1) );
281
282   if (o_mode & mf_screenshot) {
283     open_screenshot_file("w");
284     if (o_flags & ff_singlepage) take_one_screenshot();
285     else take_screenshots();
286   }
287   if (o_mode & mf_readscreenshot) {
288     open_screenshot_file("r");
289     if (o_flags & ff_singlepage) read_one_screenshot();
290     else read_screenshots();
291   }
292   if (o_mode & mf_analyse) {
293     if (o_flags & ff_needisland) {
294       find_islandname();
295       if (o_flags & ff_printisland)
296         printf("%s, %s\n", archipelago, island);
297     }
298     switch (o_outmode_kind) {
299     case omk_upload: case omk_str:   run_analysis();        break;
300     case omk_raw:                    analyse(stdout);       break;
301     case omk_none:                                          break;
302     default: abort();
303     }
304   }
305   progress_log("Finished.");
306   return 0;
307 }
308
309
310
311
312 DEFINE_VWRAPPERF(, progress, )
313 DEFINE_VWRAPPERF(, progress_log, )
314 DEFINE_VWRAPPERF(, progress_spinner, )
315 DEFINE_VWRAPPERF(, warning, )
316 DEFINE_VWRAPPERF(, fatal, NORET)
317
318 static int last_progress_len;
319      
320 static void vprogress_core(int spinner, const char *fmt, va_list al) {
321   int r;
322   
323   if (o_quiet) return;
324   if (!isatty(2)) return;
325   
326   if (last_progress_len)
327     putc('\r',stderr);
328
329   r= vfprintf(stderr,fmt,al);
330
331   if (spinner) {
332     putc(spinner,stderr);
333     r++;
334   }
335
336   if (r < last_progress_len) {
337     fprintf(stderr,"%*s", last_progress_len - r, "");
338     if (!r) putc('\r', stderr);
339     else while (last_progress_len-- > r) putc('\b',stderr);
340   }
341   last_progress_len= r;
342
343   if (ferror(stderr) || fflush(stderr)) _exit(16);
344 }
345    
346 void vprogress(const char *fmt, va_list al) { vprogress_core(0,fmt,al); }
347 void vprogress_spinner(const char *fmt, va_list al) {
348   static const char spinchars[]="/-\\";
349   static int spinner;
350
351   vprogress_core(spinchars[spinner],fmt,al);
352   spinner++;
353   spinner %= (sizeof(spinchars)-1);
354 }
355
356 void vprogress_log(const char *fmt, va_list al) {
357   if (o_quiet) return;
358   
359   progress("");
360   vfprintf(stderr,fmt,al);
361   putc('\n',stderr);
362   fflush(stderr);
363 }
364
365 void vwarning(const char *fmt, va_list al) {
366   progress("");
367   fputs("Warning: ",stderr);
368   vfprintf(stderr,fmt,al);
369   fputs("\n",stderr);
370   fflush(stderr);
371 }
372
373 void vfatal(const char *fmt, va_list al) {
374   progress("");
375   fputs("\n\nFatal error: ",stderr);
376   vfprintf(stderr,fmt,al);
377   fflush(stderr);
378   fputs("\n\n",stderr);
379   _exit(4);
380 }
381
382 void sysassert_fail(const char *file, int line, const char *what) {
383   int e= errno;
384   progress("");
385   fprintf(stderr,
386           "\nfatal operational error:\n"
387           " unsuccessful execution of: %s\n"
388           " %s:%d: %s\n\n",
389           what, file,line, strerror(e));
390   _exit(16);
391 }
392
393 void waitpid_check_exitstatus(pid_t pid, const char *what) { 
394   pid_t got;
395   int st;
396   for (;;) {
397     got= waitpid(pid, &st, 0);
398     if (pid==-1) { sysassert(errno==EINTR); continue; }
399     break;
400   }
401   sysassert( got==pid );
402
403   if (WIFEXITED(st)) {
404     if (WEXITSTATUS(st))
405       fatal("%s failed with nonzero exit status %d",
406             what, WEXITSTATUS(st));
407   } else if (WIFSIGNALED(st)) {
408     fatal("%s died due to signal %s%s", what,
409           strsignal(WTERMSIG(st)), WCOREDUMP(st)?" (core dumped)":"");
410   } else {
411     fatal("%s gave strange wait status %d", what, st);
412   }
413 }
414
415 char *masprintf(const char *fmt, ...) {
416   char *r;
417   va_list al;
418   va_start(al,fmt);
419   sysassert( vasprintf(&r,fmt,al) >= 0);
420   sysassert(r);
421   va_end(al);
422   return r;
423 }