Debian Codegraph @

texmf-dist/source/latex/wargame/utils/wgmakenato.py

raw
1 #!/usr/bin/env python
2
3 # ====================================================================
4 def ensure_list(what):
5 if not what:
6 return None
7
8 if isinstance(what,str):
9 return [what]
10
11 return what
12
13 # --------------------------------------------------------------------
14 def clean(base, suffixes):
15 from pathlib import Path
16
17 if not isinstance(base,Path):
18 base = Path(base)
19
20 for suffix in suffixes:
21 tgt = base.with_suffix(suffix)
22 tgt.unlink(missing_ok=True)
23
24 # ====================================================================
25 possible_commands = ['air',
26 'land',
27 'equipment',
28 'installation',
29 'sea surface',
30 'sub surface',
31 'space',
32 'activity',
33 'dismounted']
34 possible_factions = ['friendly',
35 'hostile',
36 'neutral',
37 'unknown']
38 echelon_mapping = {'': 'team',
39 '*': 'squad',
40 '**': 'section',
41 '***': 'platoon',
42 '|': 'company',
43 '||': 'battalion',
44 '|||': 'regiment',
45 'x': 'brigade',
46 'xx': 'division',
47 'xxx': 'corps',
48 'xxxx': 'army',
49 'xxxxx': 'army group',
50 'xxxxxx': 'theater'}
51 possible_echelons = list(echelon_mapping.values())+list(echelon_mapping.keys())
52
53 # ====================================================================
54 def make_picture(command,
55 faction,
56 echelon,
57 main,
58 top=None,
59 bottom=None,
60 left=None,
61 right=None,
62 below=None,
63 decoy=False,
64 line_width='1pt',
65 scale=.45,
66 more=None,
67 **kwargs):
68 '''Create latex code for the NATO App6 symbol - a single tikzpicture
69
70 Parameters
71 ----------
72 command : str
73 Command (base symbol)
74 faction : str
75 Faction (base symbol)
76 echelon : str or None
77 Echelon (top of base symbol
78 main : str or list of str
79 Main symbols
80 top : str or list of str
81 Top modifiers
82 bottom : str or list of str
83 Bottom modifiers
84 left : str or list of str
85 Left modifiers
86 right : str or list of str
87 Right modifiers
88 below : str or list of str
89 Below base frame
90 decoy : bool
91 True if it should be a decoy
92 line_width : str
93 Line width, including unit
94 scale : float
95 Scaling of image
96
97 Return
98 ------
99 out : str
100 LaTeX code to write to file
101 '''
102 ind = ' '
103 def add_line(out,key,what,ind=ind):
104 '''Adds a line with a key'''
105 lwhat = ensure_list(what)
106 if not lwhat:
107 return out
108
109 swhat = ",".join(lwhat)
110
111 return out+f'{ind} {key}={{{swhat}}},%'+'\n'
112
113
114 out = fr'''\begin{{tikzpicture}}%
115 \natoapp[%
116 scale={scale},%
117 scale line widths,%
118 line width={line_width},%
119 command={command},%
120 faction={faction},%'''+'\n'
121
122 out = add_line(out,'echelon',echelon)
123 out = add_line(out,'main', main)
124 out = add_line(out,'top', top)
125 out = add_line(out,'bottom', bottom)
126 out = add_line(out,'left', left)
127 out = add_line(out,'right', right)
128 out = add_line(out,'below', below)
129 if more:
130 out += f'{ind} {more}%'+'\n'
131
132 out += fr''' ];%
133 \end{{tikzpicture}}%
134 '''
135 lout = out.split('\n')
136 lout = [l[len(ind):] if l.startswith(ind) else l for l in lout]
137 return '\n'.join(lout)
138
139 # --------------------------------------------------------------------
140 def make_latex(db):
141 '''Create latex code for the all NATO App6 symbols -
142 a complete document
143
144 Parameters
145 ----------
146 db : list of dict
147 Configurations of each symbol
148
149 Return
150 ------
151 out : str
152 LaTeX code to write to file
153 '''
154
155 ind = ' '
156 out = r'''\documentclass[tikz,11pt]{standalone}
157 \usepackage{wargame}
158 \begin{document}%'''+'\n'
159
160 for entry in db:
161 out += make_picture(**entry)
162
163 out += r'\end{document}'
164
165 lout = out.split('\n')
166 lout = [l[len(ind):] if l.startswith(ind) else l for l in lout]
167 return '\n'.join(lout)
168
169
170 # --------------------------------------------------------------------
171 def make_name(command,
172 faction,
173 echelon,
174 main,
175 top=None,
176 bottom=None,
177 left=None,
178 right=None,
179 below=None,
180 decoy=False,
181 output=None,
182 **kwargs):
183 '''Create the file name
184
185 Parameters
186 ----------
187 command : str
188 Command (base symbol)
189 faction : str
190 Faction (base symbol)
191 echelon : str or None
192 Echelon (top of base symbol
193 main : str or list of str
194 Main symbols
195 top : str or list of str
196 Top modifiers
197 bottom : str or list of str
198 Bottom modifiers
199 left : str or list of str
200 Left modifiers
201 right : str or list of str
202 Right modifiers
203 decoy : bool
204 True if it should be a decoy
205
206 Return
207 ------
208 out : str
209 Output file name
210 '''
211 if output:
212 return output.format(command=command,
213 faction=faction,
214 echelon=echelon)\
215 .replace(' ','-')\
216 .replace('=','-')
217
218 def clean_sub(what):
219 from re import sub
220
221 res = what
222 while True:
223 old = res
224 res = sub(r'\[[^]]+\]','',res)
225 res = sub(r'\{[^}]+\}','',res)
226 if res == old:
227 break
228
229 return res
230
231 def add_component(out, what,sep='-'):
232
233 lwhat = ensure_list(what)
234
235 if not lwhat:
236 return out
237
238 return out+'_'+sep.join([clean_sub(l) for l in lwhat])
239
240 def add_front(out,what,sep='_'):
241 if not what:
242 return out
243
244 if len(out) > 0: out += sep
245 return out + what
246
247 out = ''
248 out = add_front(out,faction)
249 out = add_front(out,command.replace(' ','-'))
250 out = add_front(out,echelon.replace(' ','-'))
251 out = add_component(out,main)
252 out = add_component(out,top)
253 out = add_component(out,bottom)
254 out = add_component(out,left)
255 out = add_component(out,right)
256 out = add_component(out,below)
257
258 return out.replace(' ','-').replace('=','-')
259
260
261 # ====================================================================
262 default_latex_flags = ['-interaction=nonstopmode',
263 '-file-line-error',
264 '-synctex','15',
265 '-shell-escape']
266 default_latex_command = 'pdflatex'
267
268 # --------------------------------------------------------------------
269 def create_process(args,verbose=False):
270 '''Create a subprocess with arguments
271
272 Returns
273 -------
274 proc : Popen
275 Process with stdout and stderr as pipes (fifos)
276 '''
277 from os import environ
278 from subprocess import Popen, PIPE
279
280 if verbose:
281 print(f'Will run: "{" ".join(args)}"')
282
283 return Popen(args,env=environ.copy(),stdout=PIPE,stderr=PIPE)
284
285 # --------------------------------------------------------------------
286 default_timeout = None
287 default_keep = False
288 # --------------------------------------------------------------------
289 def run_latex(file,
290 content,
291 latex_cmd = default_latex_command,
292 latex_flags = default_latex_flags,
293 timeout = default_timeout,
294 keep = default_keep,
295 verbose = False):
296 '''Run latex on generated content
297
298 Parameters
299 ----------
300 filename : str
301 The file to write
302 content : str
303 Content to write to source file
304 latex_cmd : str
305 LaTeX command to run e.g., 'pdflatex'
306 latex_flags : list of str
307 Flags to pass to the LaTeX command line
308 timeout : int
309 Process timeout
310 keep : bool
311 If true, keep intermediate files
312
313 Returns
314 -------
315 None
316 '''
317 from pathlib import Path
318
319 fpath = Path(file.name).with_suffix('')
320 csuf = ['.aux','.log','.out','.synctex','.synctex.gz','.tex']
321
322 file.write(content)
323 file.close()
324
325 lflags = ensure_list(latex_flags)
326
327 args = [latex_cmd] + (lflags if lflags else + []) + \
328 [fpath.with_suffix('.tex').name]
329
330 proc = create_process(args,verbose=verbose)
331
332 try:
333 out, err = proc.communicate(timeout=timeout)
334
335 sout = out.decode()
336 if 'Error' in sout or \
337 'Emergency stop' in sout or \
338 not Path(fpath).with_suffix('.pdf').is_file():
339 raise RuntimeError(sout)
340
341 except Exception as e:
342 proc.kill()
343 proc.communicate()
344 if not keep:
345 clean(base=fpath,suffixes=csuf+['.pdf'])
346
347 raise RuntimeError(f'Failed on "{" ".join(args)}" with:\n'+
348 str(e) + '\n--- Start LaTeX code -------\n'+
349 content+ '\n--- End LaTeX code ---------')
350
351 if not keep:
352 clean(base=fpath,suffixes=csuf)
353
354 # --------------------------------------------------------------------
355 possible_formats = ['png','svg','jpg','tiff']
356 default_format = possible_formats[0]
357 default_resolution = 150
358
359 # --------------------------------------------------------------------
360 def run_cairo(filename,
361 npages,
362 format = default_format,
363 resolution = default_resolution,
364 timeout = default_timeout,
365 keep = default_keep,
366 verbose = False):
367 '''Run 'pdftocairo' on generated PDF
368
369 Parameters
370 ----------
371 filename : str
372 The file to write
373 format : str
374 Image format to write
375 resolution : int
376 Pixels Per Inch (PPI)
377 timeout : int
378 Process timeout
379 keep : bool
380 If true, keep intermediate files
381
382 Returns
383 -------
384 None
385 '''
386 from pathlib import Path
387
388 fpath = Path(filename)
389 args = ['pdftocairo']
390 if format != 'svg':
391 args.extend(['-transp'])
392
393 args.extend(['-r',str(resolution),f'-{format}'])
394
395 inpdf = fpath.with_suffix('.pdf').name
396
397 def runit(args,pdf=inpdf,outimg=None):
398 args.append(inpdf)
399 if outimg: args.append(outimg)
400
401 proc = create_process(args,verbose)
402
403 try:
404 out, err = proc.communicate(timeout=timeout)
405
406 except Exception as e:
407 proc.kill()
408 proc.communicate()
409 if not keep:
410 clean(base=fpath,suffixes=[f'.{format}','.pdf'])
411
412 raise RuntimeError(f'Failed on "{" ".join(args)}" with:\n'+e)
413
414 if format != 'svg':
415 runit(args)
416 else:
417 from math import ceil, log10
418
419 base = fpath.stem
420 wn = ceil(log10(npages))
421 for no in range(1,npages+1):
422 no_args = args.copy()
423 no_args.extend(['-f',str(no),'-l',str(no)])
424
425 runit(no_args,outimg=base+f'-{no:0{wn}d}.{format}')
426
427 if not keep:
428 clean(base=fpath,suffixes=['.pdf'])
429
430 # --------------------------------------------------------------------
431 def make_images(db,
432 base_name,
433 format = default_format,
434 verbose = False):
435 from math import ceil, log10
436 from pathlib import Path
437
438 results = []
439 ndb = len(db)
440 wn = ceil(log10(ndb))
441 for no,entry in enumerate(db):
442 output = entry['output']+'.'+format
443 inpath = Path(f'{base_name}-{no+1:0{wn}d}.{format}')
444
445 inpath.rename(output)
446 results.append(output)
447 if verbose:
448 print(f'{no+1:0{wn}d}/{ndb}: {output}')
449
450 return results
451
452 # --------------------------------------------------------------------
453 default_xml = False
454
455 # --------------------------------------------------------------------
456 def write_xmls(db,
457 format = default_format,
458 verbose = False):
459 '''Build an XML snippet of a prototype'''
460
461 ndb = len(db)
462 wn = ceil(log10(ndb))
463 for no,entry in enumerate(db):
464 if verbose:
465 print(f'{no+1:0{wn}d}/{ndb} ...{entry["output"]}.xml')
466
467 write_xml(**entry,format=format)
468
469 # --------------------------------------------------------------------
470 def write_xml(command = None,
471 faction = None,
472 echelon = None,
473 main = None,
474 top = None,
475 bottom = None,
476 left = None,
477 right = None,
478 below = None,
479 decoy = False,
480 output = None,
481 format = default_format,
482 **kwargs):
483 '''Build an XML snippet of a prototype'''
484 from xml.dom.minidom import Document
485 from wgexport import LayerTrait, Prototype, MarkTrait, \
486 BasicTrait, BuildFile
487
488 doc = BuildFile()
489 hasEchelon = echelon and len(echelon) > 0
490
491 yoff = -8 if main else -10 if echelon else -8
492 traits = [
493 LayerTrait(
494 images = [f'{output}.{format}'],
495 newNames = [''],
496 activateName = '',
497 activateMask = '',
498 activateChar = '',
499 increaseName = '',
500 increaseMask = '',
501 increaseChar = '',
502 decreaseName = '',
503 decreaseMask = '',
504 decreaseChar = '',
505 resetName = '',
506 resetKey = '',
507 resetLevel = 1,
508 under = False,
509 underXoff = 0,
510 underYoff = yoff,
511 loop = False,
512 name = ('NATOAPP6_command_faction'
513 +('_main' if main else '')
514 +('_echelon' if hasEchelon else '')),
515 description = 'NATO App6 symbology',
516 randomKey = '',
517 randomName = '',
518 follow = False,
519 expression = '',
520 first = 1,
521 version = 1,
522 always = True,
523 activateKey = '',
524 increaseKey = '',
525 decreaseKey = '',
526 scale = 1.)]
527
528 if command:
529 traits.append(MarkTrait(name = 'NATOAPP6_command',
530 value = command))
531 if main:
532 traits.append(MarkTrait(name = 'NATOAPP6_type',
533 value = make_name(command = '',
534 faction = '',
535 echelon = '',
536 main = main,
537 top = top,
538 bottom = bottom,
539 left = left,
540 right = right,
541 below = below,
542 decoy = decoy)))
543 if echelon:
544 traits.append(MarkTrait(name = 'NATOAPP6_echelon',
545 value = echelon))
546
547 traits.append(BasicTrait())
548
549
550 proto = Prototype(doc,
551 name = output,
552 traits = traits,
553 description = 'NATO App6 symbol')
554
555 doc._node.insertBefore(
556 doc._root.createComment('Created via LaTeX wargame package, '
557 'licensed under the CreativeCommons '
558 'Share-Alike, '
559 '© 2024 Christian Holm Christensen'),
560 proto._node)
561 xml_out = doc.encode()
562
563 with open(output+'.xml','wb') as out:
564 out.write(xml_out)
565
566
567 # ====================================================================
568 def create_images(db,
569 latex_command = default_latex_command,
570 latex_flags = default_latex_flags,
571 timeout = default_timeout,
572 resolution = default_resolution,
573 format = default_format,
574 keep = default_keep,
575 verbose = False,
576 xml = default_xml):
577 from tempfile import NamedTemporaryFile
578 from pathlib import Path
579
580 result = []
581
582
583 with NamedTemporaryFile(mode='w',suffix='.tex',dir='.',
584 delete=not keep,
585 delete_on_close=False) as texfile:
586 if verbose:
587 print(f'Temporary file: {texfile.name}')
588
589 base_name = Path(texfile.name).stem
590 latex_code = make_latex(db)
591 try:
592 run_latex(texfile,
593 latex_code,
594 latex_cmd = latex_command,
595 latex_flags = latex_flags,
596 timeout = timeout,
597 keep = keep,
598 verbose = verbose)
599
600 run_cairo(base_name,
601 npages = len(db),
602 format = format,
603 resolution = resolution,
604 timeout = timeout,
605 keep = keep,
606 verbose = verbose)
607
608 result = make_images(db,
609 base_name,
610 format = format,
611 verbose = verbose)
612
613 if xml:
614 write_xmls(db)
615
616 except Exception as e:
617 import traceback
618 print(traceback.format_exc())
619 print(e)
620 return None
621
622 return result
623
624
625 # ====================================================================
626 #
627 # Main program
628 #
629 if __name__ == '__main__':
630 from argparse import ArgumentParser, FileType
631 from pprint import pprint
632
633 ap = ArgumentParser(description='Create an image of NATO App6 symbol')
634 ap.add_argument('-c','--command',type=str,choices=possible_commands,
635 help='Select command',default=possible_commands[1])
636 ap.add_argument('-f','--faction',type=str,choices=possible_factions,
637 help='Select faction',default=possible_factions[0])
638 ap.add_argument('-e','--echelon',type=str,choices=possible_echelons,
639 help='Select echelon')
640 ap.add_argument('-m','--main',type=str,nargs='*',
641 help='Select main symbol(s)')
642 ap.add_argument('-t','--top',type=str,nargs='*',
643 help='Select top modifier(s)')
644 ap.add_argument('-b','--bottom',type=str,nargs='*',
645 help='Select bottom modifier(s)')
646 ap.add_argument('-l','--left',type=str,nargs='*',
647 help='Select left modifier(s)')
648 ap.add_argument('-r','--right',type=str,nargs='*',
649 help='Select left modifier(s)')
650 ap.add_argument('-B','--below',type=str,nargs='*',
651 help='Select below (mobility) modifier(s)')
652 ap.add_argument('-d','--decoy',action='store_true',
653 help='Mark as decoy')
654 ap.add_argument('-w','--line-width',default='1pt',type=str,
655 help='Line width, including unit')
656 ap.add_argument('-s','--scale',default=0.45,type=float,
657 help='Scaling of symbol (width in centimetre)')
658 ap.add_argument('-I','--format',default=default_format,
659 choices=possible_formats,type=str,
660 help='Output image format')
661 ap.add_argument('-L','--latex-command',default=default_latex_command,
662 help='Set the LaTeX command to use',type=str)
663 ap.add_argument('-F','--latex-flags',default=default_latex_flags,
664 help='Set the LaTeX command to use',type=str,nargs='*')
665 ap.add_argument('-T','--timeout',default=default_timeout,type=int,
666 help='Timeout of sub-processes')
667 ap.add_argument('-R','--resolution',default=default_resolution,type=int,
668 help='Resolution out output image (ppi)')
669 ap.add_argument('-k','--keep',action='store_true',
670 help='Leave intermediate files')
671 ap.add_argument('-o','--output',type=str,
672 help='Set output file name, default is autogenerated')
673 ap.add_argument('-j','--json',type=str,nargs='*',
674 help='Read symbols to create from JSON file')
675 ap.add_argument('-v','--verbose',action='store_true')
676 ap.add_argument('-X','--xml',action='store_true',
677 help='Also output XML snippets')
678
679 args = ap.parse_args()
680 vargs = vars(args)
681 oargs = {}
682 to_remove = ['latex_command',
683 'latex_flags',
684 'resolution',
685 'format',
686 'timeout',
687 'keep',
688 'json',
689 'verbose',
690 'xml']
691 for key in to_remove:
692 if key not in vargs:
693 continue
694
695 oargs[key] = vargs[key]
696 del vargs[key]
697
698 commons = ['infantry',
699 'armoured',
700 'armoured+infantry',
701 'reconnaissance',
702 'armoured+reconnaissance',
703 '[fill=pgfstrokecolor]artillery',
704 'armoured+[fill=pgfstrokecolor]artillery',
705 'text=SF']
706
707
708 db = None
709 main = vargs['main']
710 injson = oargs.pop('json',None)
711
712 #pprint(vargs)
713 #pprint(oargs)
714
715 if injson:
716 from json import load
717
718 db = []
719 for j in injson:
720 print(f'=== JSON input: {j}')
721 with open(j,'r') as jin:
722 db.extend(load(jin))
723
724 elif main and len(main) == 1 and main[0] == 'common':
725 db = [{'main': w.split('+')} for w in commons]
726 else:
727 db = [vargs]
728
729 if not db:
730 raise RuntimeError('Noting to do')
731
732 from math import log10, ceil
733
734 def ensure(d, key, default):
735 if key not in d and default:
736 d[key] = default[key]
737
738 results = []
739 ndb = len(db)
740 wn = ceil(log10(ndb))
741 for no,entry in enumerate(db):
742 print(f'{no:{wn}d} of {ndb} ...',end='')
743 if not isinstance(entry,dict):
744 print(' skipped')
745 continue
746
747 for key in vargs.keys():
748 ensure(entry,key,vargs)
749 entry['output'] = make_name(**entry)
750 print(entry['output'])
751
752
753 results = create_images(db,**oargs)
754 #
755 #
756 #