You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
2.2 KiB

  1. """Convert raw KLE to JSON
  2. """
  3. import json
  4. import os
  5. from pathlib import Path
  6. from argcomplete.completers import FilesCompleter
  7. from milc import cli
  8. from kle2xy import KLE2xy
  9. from qmk.converter import kle2qmk
  10. from qmk.json_encoders import InfoJSONEncoder
  11. @cli.argument('filename', completer=FilesCompleter('.json'), help='The KLE raw txt to convert')
  12. @cli.argument('-f', '--force', action='store_true', help='Flag to overwrite current info.json')
  13. @cli.subcommand('Convert a KLE layout to a Configurator JSON', hidden=False if cli.config.user.developer else True)
  14. def kle2json(cli):
  15. """Convert a KLE layout to QMK's layout format.
  16. """ # If filename is a path
  17. if cli.args.filename.startswith("/") or cli.args.filename.startswith("./"):
  18. file_path = Path(cli.args.filename)
  19. # Otherwise assume it is a file name
  20. else:
  21. file_path = Path(os.environ['ORIG_CWD'], cli.args.filename)
  22. # Check for valid file_path for more graceful failure
  23. if not file_path.exists():
  24. cli.log.error('File {fg_cyan}%s{style_reset_all} was not found.', file_path)
  25. return False
  26. out_path = file_path.parent
  27. raw_code = file_path.read_text(encoding='utf-8')
  28. # Check if info.json exists, allow overwrite with force
  29. if Path(out_path, "info.json").exists() and not cli.args.force:
  30. cli.log.error('File {fg_cyan}%s/info.json{style_reset_all} already exists, use -f or --force to overwrite.', out_path)
  31. return False
  32. try:
  33. # Convert KLE raw to x/y coordinates (using kle2xy package from skullydazed)
  34. kle = KLE2xy(raw_code)
  35. except Exception as e:
  36. cli.log.error('Could not parse KLE raw data: %s', raw_code)
  37. cli.log.exception(e)
  38. return False
  39. keyboard = {
  40. 'keyboard_name': kle.name,
  41. 'url': '',
  42. 'maintainer': 'qmk',
  43. 'width': kle.columns,
  44. 'height': kle.rows,
  45. 'layouts': {
  46. 'LAYOUT': {
  47. 'layout': kle2qmk(kle)
  48. }
  49. },
  50. }
  51. # Write our info.json
  52. keyboard = json.dumps(keyboard, indent=4, separators=(', ', ': '), sort_keys=False, cls=InfoJSONEncoder)
  53. info_json_file = out_path / 'info.json'
  54. info_json_file.write_text(keyboard)
  55. cli.log.info('Wrote out {fg_cyan}%s/info.json', out_path)