KLL Compiler
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

kiibohd.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. #!/usr/bin/env python3
  2. # KLL Compiler - Kiibohd Backend
  3. #
  4. # Backend code generator for the Kiibohd Controller firmware.
  5. #
  6. # Copyright (C) 2014-2015 by Jacob Alexander
  7. #
  8. # This file is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This file is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with this file. If not, see <http://www.gnu.org/licenses/>.
  20. ### Imports ###
  21. import os
  22. import sys
  23. import re
  24. from datetime import date
  25. # Modifying Python Path, which is dumb, but the only way to import up one directory...
  26. sys.path.append( os.path.expanduser('..') )
  27. from kll_lib.containers import *
  28. ### Decorators ###
  29. ## Print Decorator Variables
  30. ERROR = '\033[5;1;31mERROR\033[0m:'
  31. WARNING = '\033[5;1;33mWARNING\033[0m:'
  32. ### Classes ###
  33. class Backend:
  34. # Initializes backend
  35. # Looks for template file and builds list of fill tags
  36. def __init__( self, templatePath, definesTemplatePath ):
  37. # Does template exist?
  38. if not os.path.isfile( templatePath ):
  39. print ( "{0} '{1}' does not exist...".format( ERROR, templatePath ) )
  40. sys.exit( 1 )
  41. self.definesTemplatePath = definesTemplatePath
  42. self.templatePath = templatePath
  43. self.fill_dict = dict()
  44. # Generate list of fill tags
  45. self.tagList = []
  46. with open( templatePath, 'r' ) as openFile:
  47. for line in openFile:
  48. match = re.findall( '<\|([^|>]+)\|>', line )
  49. for item in match:
  50. self.tagList.append( item )
  51. with open( definesTemplatePath, 'r' ) as openFile:
  52. for line in openFile:
  53. match = re.findall( '<\|([^|>]+)\|>', line )
  54. for item in match:
  55. self.tagList.append( item )
  56. # USB Code Capability Name
  57. def usbCodeCapability( self ):
  58. return "usbKeyOut";
  59. # TODO
  60. def layerInformation( self, name, date, author ):
  61. self.fill_dict['Information'] += "// Name: {0}\n".format( "TODO" )
  62. self.fill_dict['Information'] += "// Version: {0}\n".format( "TODO" )
  63. self.fill_dict['Information'] += "// Date: {0}\n".format( "TODO" )
  64. self.fill_dict['Information'] += "// Author: {0}\n".format( "TODO" )
  65. # Processes content for fill tags and does any needed dataset calculations
  66. def process( self, capabilities, macros, variables, gitRev, gitChanges ):
  67. # Build string list of compiler arguments
  68. compilerArgs = ""
  69. for arg in sys.argv:
  70. if "--" in arg or ".py" in arg:
  71. compilerArgs += "// {0}\n".format( arg )
  72. else:
  73. compilerArgs += "// {0}\n".format( arg )
  74. # Build a string of modified files, if any
  75. gitChangesStr = "\n"
  76. if len( gitChanges ) > 0:
  77. for gitFile in gitChanges:
  78. gitChangesStr += "// {0}\n".format( gitFile )
  79. else:
  80. gitChangesStr = " None\n"
  81. # Prepare BaseLayout and Layer Info
  82. baseLayoutInfo = ""
  83. defaultLayerInfo = ""
  84. partialLayersInfo = ""
  85. for file, name in zip( variables.baseLayout['*LayerFiles'], variables.baseLayout['*NameStack'] ):
  86. baseLayoutInfo += "// {0}\n// {1}\n".format( name, file )
  87. for file, name in zip( variables.layerVariables[0]['*LayerFiles'], variables.layerVariables[0]['*NameStack'] ):
  88. defaultLayerInfo += "// {0}\n// {1}\n".format( name, file )
  89. for layer in range( 1, len( variables.layerVariables ) ):
  90. partialLayersInfo += "// Layer {0}\n".format( layer )
  91. for file, name in zip( variables.layerVariables[ layer ]['*LayerFiles'], variables.layerVariables[ layer ]['*NameStack'] ):
  92. partialLayersInfo += "// {0}\n// {1}\n".format( name, file )
  93. ## Information ##
  94. self.fill_dict['Information'] = "// This file was generated by the kll compiler, DO NOT EDIT.\n"
  95. self.fill_dict['Information'] += "// Generation Date: {0}\n".format( date.today() )
  96. self.fill_dict['Information'] += "// KLL Backend: {0}\n".format( "kiibohd" )
  97. self.fill_dict['Information'] += "// KLL Git Rev: {0}\n".format( gitRev )
  98. self.fill_dict['Information'] += "// KLL Git Changes:{0}".format( gitChangesStr )
  99. self.fill_dict['Information'] += "// Compiler arguments:\n{0}".format( compilerArgs )
  100. self.fill_dict['Information'] += "//\n"
  101. self.fill_dict['Information'] += "// - Base Layer -\n{0}".format( baseLayoutInfo )
  102. self.fill_dict['Information'] += "// - Default Layer -\n{0}".format( defaultLayerInfo )
  103. self.fill_dict['Information'] += "// - Partial Layers -\n{0}".format( partialLayersInfo )
  104. ## Variable Information ##
  105. self.fill_dict['VariableInformation'] = ""
  106. # Iterate through the variables, output, and indicate the last file that modified it's value
  107. # Output separate tables per file, per table and overall
  108. # TODO
  109. ## Defines ##
  110. self.fill_dict['Defines'] = ""
  111. # Iterate through defines and lookup the variables
  112. for define in variables.defines.keys():
  113. if define in variables.overallVariables.keys():
  114. self.fill_dict['Defines'] += "\n#define {0} {1}".format( variables.defines[ define ], variables.overallVariables[ define ] )
  115. else:
  116. print( "{0} '{1}' not defined...".format( WARNING, define ) )
  117. ## Capabilities ##
  118. self.fill_dict['CapabilitiesList'] = "const Capability CapabilitiesList[] = {\n"
  119. # Keys are pre-sorted
  120. for key in capabilities.keys():
  121. funcName = capabilities.funcName( key )
  122. argByteWidth = capabilities.totalArgBytes( key )
  123. self.fill_dict['CapabilitiesList'] += "\t{{ {0}, {1} }},\n".format( funcName, argByteWidth )
  124. self.fill_dict['CapabilitiesList'] += "};"
  125. ## Results Macros ##
  126. self.fill_dict['ResultMacros'] = ""
  127. # Iterate through each of the result macros
  128. for result in range( 0, len( macros.resultsIndexSorted ) ):
  129. self.fill_dict['ResultMacros'] += "Guide_RM( {0} ) = {{ ".format( result )
  130. # Add the result macro capability index guide (including capability arguments)
  131. # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
  132. for sequence in range( 0, len( macros.resultsIndexSorted[ result ] ) ):
  133. # If the sequence is longer than 1, prepend a sequence spacer
  134. # Needed for USB behaviour, otherwise, repeated keys will not work
  135. if sequence > 0:
  136. # <single element>, <usbCodeSend capability>, <USB Code 0x00>
  137. self.fill_dict['ResultMacros'] += "1, {0}, 0x00, ".format( capabilities.getIndex( self.usbCodeCapability() ) )
  138. # For each combo in the sequence, add the length of the combo
  139. self.fill_dict['ResultMacros'] += "{0}, ".format( len( macros.resultsIndexSorted[ result ][ sequence ] ) )
  140. # For each combo, add each of the capabilities used and their arguments
  141. for combo in range( 0, len( macros.resultsIndexSorted[ result ][ sequence ] ) ):
  142. resultItem = macros.resultsIndexSorted[ result ][ sequence ][ combo ]
  143. # Add the capability index
  144. self.fill_dict['ResultMacros'] += "{0}, ".format( capabilities.getIndex( resultItem[0] ) )
  145. # Add each of the arguments of the capability
  146. for arg in range( 0, len( resultItem[1] ) ):
  147. self.fill_dict['ResultMacros'] += "0x{0:02X}, ".format( resultItem[1][ arg ] )
  148. # If sequence is longer than 1, append a sequence spacer at the end of the sequence
  149. # Required by USB to end at sequence without holding the key down
  150. if len( macros.resultsIndexSorted[ result ] ) > 1:
  151. # <single element>, <usbCodeSend capability>, <USB Code 0x00>
  152. self.fill_dict['ResultMacros'] += "1, {0}, 0x00, ".format( capabilities.getIndex( self.usbCodeCapability() ) )
  153. # Add list ending 0 and end of list
  154. self.fill_dict['ResultMacros'] += "0 };\n"
  155. self.fill_dict['ResultMacros'] = self.fill_dict['ResultMacros'][:-1] # Remove last newline
  156. ## Result Macro List ##
  157. self.fill_dict['ResultMacroList'] = "const ResultMacro ResultMacroList[] = {\n"
  158. # Iterate through each of the result macros
  159. for result in range( 0, len( macros.resultsIndexSorted ) ):
  160. self.fill_dict['ResultMacroList'] += "\tDefine_RM( {0} ),\n".format( result )
  161. self.fill_dict['ResultMacroList'] += "};"
  162. ## Result Macro Record ##
  163. self.fill_dict['ResultMacroRecord'] = "ResultMacroRecord ResultMacroRecordList[ ResultMacroNum ];"
  164. ## Trigger Macros ##
  165. self.fill_dict['TriggerMacros'] = ""
  166. # Iterate through each of the trigger macros
  167. for trigger in range( 0, len( macros.triggersIndexSorted ) ):
  168. self.fill_dict['TriggerMacros'] += "Guide_TM( {0} ) = {{ ".format( trigger )
  169. # Add the trigger macro scan code guide
  170. # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
  171. for sequence in range( 0, len( macros.triggersIndexSorted[ trigger ][ 0 ] ) ):
  172. # For each combo in the sequence, add the length of the combo
  173. self.fill_dict['TriggerMacros'] += "{0}, ".format( len( macros.triggersIndexSorted[ trigger ][0][ sequence ] ) )
  174. # For each combo, add the key type, key state and scan code
  175. for combo in range( 0, len( macros.triggersIndexSorted[ trigger ][ 0 ][ sequence ] ) ):
  176. triggerItem = macros.triggersIndexSorted[ trigger ][ 0 ][ sequence ][ combo ]
  177. # TODO Add support for Analog keys
  178. # TODO Add support for LED states
  179. self.fill_dict['TriggerMacros'] += "0x00, 0x01, 0x{0:02X}, ".format( triggerItem )
  180. # Add list ending 0 and end of list
  181. self.fill_dict['TriggerMacros'] += "0 };\n"
  182. self.fill_dict['TriggerMacros'] = self.fill_dict['TriggerMacros'][ :-1 ] # Remove last newline
  183. ## Trigger Macro List ##
  184. self.fill_dict['TriggerMacroList'] = "const TriggerMacro TriggerMacroList[] = {\n"
  185. # Iterate through each of the trigger macros
  186. for trigger in range( 0, len( macros.triggersIndexSorted ) ):
  187. # Use TriggerMacro Index, and the corresponding ResultMacro Index
  188. self.fill_dict['TriggerMacroList'] += "\tDefine_TM( {0}, {1} ),\n".format( trigger, macros.triggersIndexSorted[ trigger ][1] )
  189. self.fill_dict['TriggerMacroList'] += "};"
  190. ## Trigger Macro Record ##
  191. self.fill_dict['TriggerMacroRecord'] = "TriggerMacroRecord TriggerMacroRecordList[ TriggerMacroNum ];"
  192. ## Max Scan Code ##
  193. self.fill_dict['MaxScanCode'] = "#define MaxScanCode 0x{0:X}".format( macros.overallMaxScanCode )
  194. ## Default Layer and Default Layer Scan Map ##
  195. self.fill_dict['DefaultLayerTriggerList'] = ""
  196. self.fill_dict['DefaultLayerScanMap'] = "const nat_ptr_t *default_scanMap[] = {\n"
  197. # Iterate over triggerList and generate a C trigger array for the default map and default map array
  198. for triggerList in range( macros.firstScanCode[ 0 ], len( macros.triggerList[ 0 ] ) ):
  199. # Generate ScanCode index and triggerList length
  200. self.fill_dict['DefaultLayerTriggerList'] += "Define_TL( default, 0x{0:02X} ) = {{ {1}".format( triggerList, len( macros.triggerList[ 0 ][ triggerList ] ) )
  201. # Add scanCode trigger list to Default Layer Scan Map
  202. self.fill_dict['DefaultLayerScanMap'] += "default_tl_0x{0:02X}, ".format( triggerList )
  203. # Add each item of the trigger list
  204. for trigger in macros.triggerList[ 0 ][ triggerList ]:
  205. self.fill_dict['DefaultLayerTriggerList'] += ", {0}".format( trigger )
  206. self.fill_dict['DefaultLayerTriggerList'] += " };\n"
  207. self.fill_dict['DefaultLayerTriggerList'] = self.fill_dict['DefaultLayerTriggerList'][:-1] # Remove last newline
  208. self.fill_dict['DefaultLayerScanMap'] = self.fill_dict['DefaultLayerScanMap'][:-2] # Remove last comma and space
  209. self.fill_dict['DefaultLayerScanMap'] += "\n};"
  210. ## Partial Layers and Partial Layer Scan Maps ##
  211. self.fill_dict['PartialLayerTriggerLists'] = ""
  212. self.fill_dict['PartialLayerScanMaps'] = ""
  213. # Iterate over each of the layers, excluding the default layer
  214. for layer in range( 1, len( macros.triggerList ) ):
  215. # Prepare each layer
  216. self.fill_dict['PartialLayerScanMaps'] += "// Partial Layer {0}\n".format( layer )
  217. self.fill_dict['PartialLayerScanMaps'] += "const nat_ptr_t *layer{0}_scanMap[] = {{\n".format( layer )
  218. self.fill_dict['PartialLayerTriggerLists'] += "// Partial Layer {0}\n".format( layer )
  219. # Iterate over triggerList and generate a C trigger array for the layer
  220. for triggerList in range( macros.firstScanCode[ layer ], len( macros.triggerList[ layer ] ) ):
  221. # Generate ScanCode index and triggerList length
  222. self.fill_dict['PartialLayerTriggerLists'] += "Define_TL( layer{0}, 0x{1:02X} ) = {{ {2}".format( layer, triggerList, len( macros.triggerList[ layer ][ triggerList ] ) )
  223. # Add scanCode trigger list to Default Layer Scan Map
  224. self.fill_dict['PartialLayerScanMaps'] += "layer{0}_tl_0x{1:02X}, ".format( layer, triggerList )
  225. # Add each item of the trigger list
  226. for trigger in macros.triggerList[ layer ][ triggerList ]:
  227. self.fill_dict['PartialLayerTriggerLists'] += ", {0}".format( trigger )
  228. self.fill_dict['PartialLayerTriggerLists'] += " };\n"
  229. self.fill_dict['PartialLayerTriggerLists'] += "\n"
  230. self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last comma and space
  231. self.fill_dict['PartialLayerScanMaps'] += "\n};\n\n"
  232. self.fill_dict['PartialLayerTriggerLists'] = self.fill_dict['PartialLayerTriggerLists'][:-2] # Remove last 2 newlines
  233. self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last 2 newlines
  234. ## Layer Index List ##
  235. self.fill_dict['LayerIndexList'] = "const Layer LayerIndex[] = {\n"
  236. # Iterate over each layer, adding it to the list
  237. for layer in range( 0, len( macros.triggerList ) ):
  238. # Lookup first scancode in map
  239. firstScanCode = macros.firstScanCode[ layer ]
  240. # Generate stacked name
  241. stackName = ""
  242. for name in range( 0, len( variables.layerVariables[ layer ]['*NameStack'] ) ):
  243. stackName += "{0} + ".format( variables.layerVariables[ layer ]['*NameStack'][ name ] )
  244. stackName = stackName[:-3]
  245. # Default map is a special case, always the first index
  246. if layer == 0:
  247. self.fill_dict['LayerIndexList'] += '\tLayer_IN( default_scanMap, "D: {1}", 0x{0:02X} ),\n'.format( firstScanCode, stackName )
  248. else:
  249. self.fill_dict['LayerIndexList'] += '\tLayer_IN( layer{0}_scanMap, "{0}: {2}", 0x{1:02X} ),\n'.format( layer, firstScanCode, stackName )
  250. self.fill_dict['LayerIndexList'] += "};"
  251. ## Layer State ##
  252. self.fill_dict['LayerState'] = "uint8_t LayerState[ LayerNum ];"
  253. # Generates the output keymap with fill tags filled
  254. def generate( self, outputPath, definesOutputPath ):
  255. # Process each line of the template, outputting to the target path
  256. with open( outputPath, 'w' ) as outputFile:
  257. with open( self.templatePath, 'r' ) as templateFile:
  258. for line in templateFile:
  259. # TODO Support multiple replacements per line
  260. # TODO Support replacement with other text inline
  261. match = re.findall( '<\|([^|>]+)\|>', line )
  262. # If match, replace with processed variable
  263. if match:
  264. outputFile.write( self.fill_dict[ match[ 0 ] ] )
  265. outputFile.write("\n")
  266. # Otherwise, just append template to output file
  267. else:
  268. outputFile.write( line )
  269. # Process each line of the defines template, outputting to the target path
  270. with open( definesOutputPath, 'w' ) as outputFile:
  271. with open( self.definesTemplatePath, 'r' ) as templateFile:
  272. for line in templateFile:
  273. # TODO Support multiple replacements per line
  274. # TODO Support replacement with other text inline
  275. match = re.findall( '<\|([^|>]+)\|>', line )
  276. # If match, replace with processed variable
  277. if match:
  278. outputFile.write( self.fill_dict[ match[ 0 ] ] )
  279. outputFile.write("\n")
  280. # Otherwise, just append template to output file
  281. else:
  282. outputFile.write( line )