2 * yarrg main program: argument parsing etc.
5 * This is part of ypp-sc-tools, a set of third-party tools for assisting
6 * players of Yohoho Puzzle Pirates.
8 * Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
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.
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.
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/>.
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.
30 void debug_flush(void) {
31 sysassert(!ferror(debug));
32 sysassert(!fflush(debug));
35 const char *get_vardir(void) { return "."; }
36 const char *get_libdir(void) { return "."; }
40 omk_unset, omk_raw, omk_str, omk_upload_yarrg, omk_upload_pctb
44 enum outmodekind kind; /* unset is sentinel */
45 const char *str; /* non-0 iff not unset or raw */
48 static OutputMode o_outmodes[10];
50 static char *o_screenshot_fn;
51 static const char *o_serv_pctb, *o_serv_yarrg;
52 static const char *o_serv_dict_fetch, *o_serv_dict_submit;
54 const char *o_resolver= "./dictionary-manager";
55 FILE *screenshot_file;
56 const char *o_ocean, *o_pirate;
59 static pid_t screenshot_compressor=-1;
61 enum mode o_mode= mode_all;
63 ff_charset_allowedit |
64 ff_dict_fetch|ff_dict_submit|ff_dict_pirate;
66 static void vbadusage(const char *fmt, va_list) FMT(1,0) NORET;
67 static void vbadusage(const char *fmt, va_list al) {
68 fputs("bad usage: ",stderr);
69 vfprintf(stderr,fmt,al);
73 DEFINE_VWRAPPERF(static, badusage, NORET);
75 static void open_screenshot_file(int for_write) {
76 if (!fnmatch("*.gz",o_screenshot_fn,0)) {
77 int mode= for_write ? O_WRONLY|O_CREAT|O_TRUNC : O_RDONLY;
78 sysassert(! gzopen(o_screenshot_fn, mode, &screenshot_file,
79 &screenshot_compressor, "-1") );
81 screenshot_file= fopen(o_screenshot_fn, for_write ? "w" : "r");
83 fatal("could not open screenshots file `%s': %s",
84 o_screenshot_fn, strerror(errno));
88 static void run_analysis(void) {
92 sysassert( tf= tmpfile() );
93 progress("running recognition...");
96 if (o_flags & ff_upload) {
98 fatal("Recognition successful, but refusing to upload partial data\n"
99 " (--single-page specified). Specify an output mode?");
102 for (om=o_outmodes; om->kind != omk_unset; om++) {
103 sysassert( fseek(tf,0,SEEK_SET) == 0);
105 progress_log("processing results (--%s)...", om->str);
107 sysassert( (processor= fork()) != -1 );
110 sysassert( dup2(fileno(tf),0) ==0 );
111 if (om->kind==omk_raw) {
112 execlp("cat","cat",(char*)0);
113 sysassert(!"execute cat");
115 EXECLP_HELPER("commod-results-processor", om->str, (char*)0);
119 waitpid_check_exitstatus(processor, "output processor/uploader", 0);
123 progress_log("all complete.");
126 static void rsync_core(const char *stem, const char *suffix,
130 progress("Updating dictionary %s...",stem);
132 sysassert( (fetcher= fork()) != -1 );
134 const char *rsync= getenv("YPPSC_YARRG_RSYNC");
135 if (!rsync) rsync= "rsync";
137 const char *src= getenv("YPPSC_YARRG_DICT_UPDATE");
138 char *remote= masprintf("%s/master-%s.txt%s", src, stem, suffix);
139 char *local= masprintf("_master-%s.txt%s", stem, suffix);
141 fprintf(stderr,"executing rsync to fetch %s to %s\n",remote,local);
142 char *opts= masprintf("-Lt%s%s",
144 DEBUGP(rsync) ? "v" : "");
145 execlp(rsync, "rsync",opts,"--",remote,local,(char*)0);
146 sysassert(!"exec rsync failed");
149 waitpid_check_exitstatus(fetcher, "rsync", 0);
152 void fetch_with_rsync_gz(const char *stem) { rsync_core(stem,".gz",""); }
153 void fetch_with_rsync(const char *stem) { rsync_core(stem,"","z"); }
155 static void set_server(const char *envname, const char *defprotocol,
156 const char *defvalue, const char *defvalue_test,
157 const char *userspecified,
161 if (!enable) { value= "0"; goto ok; }
164 value= userspecified;
165 else if ((value= getenv(envname)))
167 else if (o_flags & ff_testservers)
168 value= defvalue_test;
172 if (value[0]=='/' || (value[0]=='.' && value[1]=='/'))
173 /* absolute or relative pathname - or anyway, something with no hostname */
176 const char *colon= strchr(value, ':');
177 const char *slash= strchr(value, '/');
179 if (colon && (!slash || colon < slash))
180 /* colon before the first slash, if any */
181 /* rsync :: protocol specification - anyway, adding scheme:// won't help */
184 int vallen= strlen(value);
186 value= masprintf("%s%s%s", defprotocol, value,
187 vallen && value[vallen-1]=='/' ? "" : "/");
190 sysassert(! setenv(envname,value,1) );
193 static void outputmode(enum outmodekind kind, const char *str) {
194 OutputMode *om= o_outmodes;
195 OutputMode *sentinel= o_outmodes + ARRAYSIZE(o_outmodes) - 1;
197 if (om==sentinel) badusage("too many output modes specified");
198 if (!om->kind) break;
205 static void outputmode_uploads(void) {
206 outputmode(omk_upload_yarrg, "upload-yarrg");
207 outputmode(omk_upload_pctb, "upload-pctb");
210 int main(int argc, char **argv) {
213 sysassert( setlocale(LC_MESSAGES,"") );
214 sysassert( setlocale(LC_CTYPE,"en_GB.UTF-8") ||
215 setlocale(LC_CTYPE,"en.UTF-8") );
217 #define ARGVAL ((*++argv) ? *argv : \
218 (badusage("missing value for option %s",arg),(char*)0))
220 #define IS(s) (!strcmp(arg,(s)))
222 while ((arg=*++argv)) {
223 if (IS("--find-window-only")) o_mode= mode_findwindow;
224 else if (IS("--screenshot-only")) o_mode= mode_screenshot;
225 else if (IS("--show-charset")) o_mode= mode_showcharset;
226 else if (IS("--analyse-only") ||
227 IS("--same")) o_mode= mode_analyse;
228 else if (IS("--everything")) o_mode= mode_all;
229 else if (IS("--find-island")) o_flags |= ffs_printisland;
230 else if (IS("--single-page")) o_flags |= ff_singlepage;
231 else if (IS("--quiet")) o_quiet= 1;
232 else if (IS("--edit-charset")) o_flags |= ff_charset_edit;
233 else if (IS("--no-edit-charset")) o_flags &= ~(ffm_charset);
234 else if (IS("--test-servers")) o_flags |= ff_testservers;
235 else if (IS("--dict-local-only")) o_flags &= ~ffs_dict;
236 else if (IS("--dict-read-only")) o_flags &= (~ffs_dict | ff_dict_fetch);
237 else if (IS("--dict-anon")) o_flags &= ~ff_dict_pirate;
238 else if (IS("--dict-submit")) o_flags |= ff_dict_fetch|ff_dict_submit;
239 else if (IS("--raw-tsv")) outputmode(omk_raw,0);
240 else if (IS("--upload")) outputmode_uploads();
241 else if (IS("--upload-yarrg")) outputmode(omk_upload_yarrg,arg+2);
242 else if (IS("--upload-pctb")) outputmode(omk_upload_pctb,arg+2);
243 else if (IS("--arbitrage") ||
245 IS("--best-prices")) outputmode(omk_str,arg+2);
246 else if (IS("--screenshot-file")||
247 IS("--screenshots-file")) o_screenshot_fn= ARGVAL;
248 else if (IS("--yarrg-server")) o_serv_yarrg= ARGVAL;
249 else if (IS("--pctb-server")) o_serv_pctb= ARGVAL;
250 else if (IS("--dict-submit-server")) o_serv_dict_submit= ARGVAL;
251 else if (IS("--dict-update-server")) o_serv_dict_fetch= ARGVAL;
252 else if (IS("--ocean")) o_ocean= ARGVAL;
253 else if (IS("--pirate")) o_pirate= ARGVAL;
255 else if (IS("-D" #f)) \
256 debug_flags |= dbg_##f;
259 else if (IS("--window-id")) {
261 unsigned long windowid= strtoul(ARGVAL,&ep,0);
262 if (*ep) badusage("invalid window id");
263 set_yppclient_window(windowid);
265 badusage("unknown option `%s'",arg);
268 /* Consequential changes to options */
270 if (o_mode & mf_analyse) {
271 if (!o_outmodes[0].kind) {
272 if (o_flags & ff_printisland) {
273 o_flags |= ff_singlepage;
275 outputmode_uploads();
279 if (o_outmodes[0].kind)
280 badusage("overall mode does not include analysis but output option(s)"
281 " (eg `--%s') specified", o_outmodes[0].str);
285 for (om=o_outmodes; om->kind; om++) {
287 case omk_upload_yarrg: o_flags |= ffs_upload | ff_use_yarrg; break;
288 case omk_upload_pctb: o_flags |= ffs_upload | ff_use_pctb; break;
293 if ((o_flags & (ff_needisland|ff_upload)) &&
294 !(o_flags & (ffm_use)))
295 o_flags |= ffm_use; /* all */
297 if (o_serv_yarrg && !o_serv_dict_submit)
298 o_serv_dict_submit= o_serv_yarrg;
302 set_server("YPPSC_YARRG_YARRG",
303 "http://", "upload.yarrg.chiark.net",
304 "upload.yarrg.chiark.net/test",
305 o_serv_yarrg, o_flags & ff_use_yarrg);
307 set_server("YPPSC_YARRG_PCTB",
308 "http://", "pctb.ilk.org" /*pctb.crabdance.com*/,
310 o_serv_pctb, o_flags & ff_use_pctb);
312 set_server("YPPSC_YARRG_DICT_UPDATE",
313 "rsync://", "rsync.yarrg.chiark.net/pctb",
314 "rsync.yarrg.chiark.net/pctb/test",
315 o_serv_dict_fetch, o_flags & ff_dict_fetch);
317 set_server("YPPSC_YARRG_DICT_SUBMIT",
318 "http://", "upload.yarrg.chiark.net",
319 "upload.yarrg.chiark.net/test",
320 o_serv_dict_submit, o_flags & ff_dict_submit);
322 if (!o_screenshot_fn)
323 o_screenshot_fn= masprintf("%s/_pages.ppm.gz", get_vardir());
325 /* Actually do the work */
327 canon_colour_prepare();
329 if (o_mode & mf_findwindow) {
330 screenshot_startup();
331 find_yppclient_window();
333 if (!ocean) ocean= o_ocean;
334 if (!pirate) pirate= o_pirate;
336 if (o_flags & ff_needisland)
338 badusage("need --ocean option when not using actual YPP client window"
339 " (consider supplying --pirate too)");
341 sysassert(! setenv("YPPSC_OCEAN",ocean,1) );
342 if (pirate && (o_flags & ff_dict_pirate))
343 sysassert(! setenv("YPPSC_PIRATE",pirate,1) );
345 switch (o_mode & mfm_special) {
347 case mode_showcharset: ocr_showcharsets(); exit(0);
351 if (o_mode & mf_screenshot) {
352 open_screenshot_file(1);
353 if (o_flags & ff_singlepage) take_one_screenshot();
354 else take_screenshots();
355 progress_log("OK for you to move the mouse now, and you can"
356 " use the YPP client again.");
357 progress("Finishing handling screenshots...");
358 gzclose(&screenshot_file,&screenshot_compressor,"screenshots output");
360 if (o_mode & mf_readscreenshot) {
361 if ((o_flags & ff_upload) && !(o_flags & ff_testservers))
362 badusage("must not reuse screenshots for upload to live databases");
363 open_screenshot_file(0);
364 if (o_flags & ff_singlepage) read_one_screenshot();
365 else read_screenshots();
366 gzclose(&screenshot_file,&screenshot_compressor,"screenshots input");
368 if (o_mode & mf_analyse) {
369 if (o_flags & ff_needisland) {
371 if (o_flags & ff_printisland)
372 printf("%s, %s\n", archipelago, island);
373 sysassert(! setenv("YPPSC_ISLAND",island,1) );
375 if (o_outmodes[0].kind==omk_raw && o_outmodes[1].kind==omk_unset)
380 progress_log("Finished.");
387 DEFINE_VWRAPPERF(, progress, )
388 DEFINE_VWRAPPERF(, progress_log, )
389 DEFINE_VWRAPPERF(, progress_spinner, )
390 DEFINE_VWRAPPERF(, warning, )
391 DEFINE_VWRAPPERF(, fatal, NORET)
393 static int last_progress_len;
395 static void vprogress_core(int spinner, const char *fmt, va_list al) {
399 if (!debug_flags && !isatty(2)) return;
401 if (last_progress_len)
404 r= vfprintf(stderr,fmt,al);
407 putc(spinner,stderr);
411 if (r < last_progress_len) {
412 fprintf(stderr,"%*s", last_progress_len - r, "");
413 if (!r) putc('\r', stderr);
414 else while (last_progress_len-- > r) putc('\b',stderr);
416 last_progress_len= r;
418 if (ferror(stderr) || fflush(stderr)) _exit(16);
421 void vprogress(const char *fmt, va_list al) { vprogress_core(0,fmt,al); }
422 void vprogress_spinner(const char *fmt, va_list al) {
423 static const char spinchars[]="/-\\";
426 vprogress_core(spinchars[spinner],fmt,al);
428 spinner %= (sizeof(spinchars)-1);
431 void vprogress_log(const char *fmt, va_list al) {
435 vfprintf(stderr,fmt,al);
440 void vwarning(const char *fmt, va_list al) {
442 fputs("Warning: ",stderr);
443 vfprintf(stderr,fmt,al);
448 void vfatal(const char *fmt, va_list al) {
450 fputs("\n\nFatal error: ",stderr);
451 vfprintf(stderr,fmt,al);
453 fputs("\n\n",stderr);
457 void sysassert_fail(const char *file, int line, const char *what) {
461 "\nfatal operational error:\n"
462 " unsuccessful execution of: %s\n"
464 what, file,line, strerror(e));
468 void waitpid_check_exitstatus(pid_t pid, const char *what, int sigpipeok) {
472 got= waitpid(pid, &st, 0);
473 if (pid==-1) { sysassert(errno==EINTR); continue; }
476 sysassert( got==pid );
480 fatal("%s failed with nonzero exit status %d",
481 what, WEXITSTATUS(st));
482 } else if (WIFSIGNALED(st)) {
483 if (!sigpipeok || WTERMSIG(st) != SIGPIPE)
484 fatal("%s died due to signal %s%s", what,
485 strsignal(WTERMSIG(st)), WCOREDUMP(st)?" (core dumped)":"");
487 fatal("%s gave strange wait status %d", what, st);
491 char *masprintf(const char *fmt, ...) {
495 sysassert( vasprintf(&r,fmt,al) >= 0);