Skip to content

Instantly share code, notes, and snippets.

@Blakeinstein
Last active June 20, 2020 10:31
Show Gist options
  • Save Blakeinstein/c349216ac1de86c66024d607140c9dfb to your computer and use it in GitHub Desktop.
Save Blakeinstein/c349216ac1de86c66024d607140c9dfb to your computer and use it in GitHub Desktop.
Uses imagemagick to prepare toolbar button icons and update items.json for chemical pfd tool
from subprocess import call
from os import walk, curdir, name, makedirs as mkdir, remove
from os.path import join, splitext, split
from json import load, dump
from re import compile
from collections import defaultdict
from sys import argv
from shutil import rmtree, copy
def repl(x):
return f"{x[0][0]} {x[0][1].lower()}"
regex = compile(r"([a-z][A-Z])")
regex2 = compile(r"[(|,|)|0-9]")
convert = "magick.exe convert" if name == "nt" else "convert"
classList = defaultdict(False)
if __name__ == "__main__":
if len(argv) == 2 and argv[1]=='clean':
remove(join(curdir, "config", "items.json"))
rmtree(join(curdir, "toolbar"))
rmtree(join(curdir, "svg"))
mkdir(join(curdir, "config"), exist_ok=True)
try:
with open(join(curdir, "config", "items.json"), "r") as file:
dict = load(file)
except FileNotFoundError:
dict = {}
for dir, _, fileList in walk("."):
if dir == join(curdir, "svg"):
break
for file in fileList:
fileName = splitext(file)[0]
if file.endswith(".svg"):
mkdir(join(curdir, 'zztemp', dir), exist_ok = True)
mkdir(join(curdir, 'svg', dir), exist_ok = True)
_ = call(f'inkscape "{join(curdir, dir, file)}" --export-filename="{join(curdir, "zztemp", dir, fileName+".png")}"', shell=True)
copy(join(curdir, dir, file), join(curdir, "svg", dir, file))
fileDir = join(curdir, "zztemp")
file = fileName + ".png"
elif file.endswith(".png"):
fileDir = curdir
else:
break
subpath = join(curdir, 'toolbar', dir)
mkdir(subpath, exist_ok = True)
_ = call(f'{convert} "{join(fileDir, dir, file)}" -thumbnail "64x64>" -gravity center -background transparent -extent 64X64 "{join(subpath, file)}"', shell=True)
if split(dir)[-1] not in dict:
dict[split(dir)[-1]] = {}
elif fileName not in dict[split(dir)[-1]]:
dict[split(dir)[-1]][fileName] = {}
className = regex2.sub('', ''.join(x for x in fileName.title() if not x.isspace()))
if classList['className']:
className += "1"
while (classList['className']):
className[-1] = str(int(className[-1]+1))
classList['className'] = True
dict[split(dir)[-1]][fileName] = {
'name': regex2.sub('', regex.sub(repl, file)[:-4]),
'icon': join(dir, fileName+'.png'),
'class': dir[2:],
'object': className,
'args': [],
}
with open(join(curdir, "config", "items.json"), "w") as file:
dump(dict, file, indent=4)
rmtree(join(curdir, "zztemp"))
if len(argv) == 2 and argv[1]=='test':
remove(join(curdir, "config", "items.json"))
rmtree(join(curdir, "toolbar"))
rmtree(join(curdir, "svg"))
@Blakeinstein
Copy link
Author

USAGE

  1. Install ImageMagick

    • For windows,
      • use chocolatey(recommended)
         choco install imagemagick
        
    • For mac,
      • use homebrew
         brew install imagemagick
        
    • For linux
      • use your package manager
        • Ubuntu
           apt install imagemagick
          
        • Redhat
           yum install imagemagick
          
    • Alternatively, you can fetch binaries from their webpage
  2. Copy the script to same directory as the svg files, the categories will be maintained. Clone the tool's repo if not already.

  3. Check for consistency, by running

python ./script.py test
  1. Finalize by running
python ./script.py
  1. Copy svg, toolbar and config to src/main/resources/base

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment