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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. #!/usr/bin/env python3
  2. '''
  3. KLL Compiler - Kiibohd Backend
  4. Backend code generator for the Kiibohd Controller firmware.
  5. '''
  6. # Copyright (C) 2014-2016 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.backends import *
  28. from kll_lib.containers import *
  29. from kll_lib.hid_dict import *
  30. ### Classes ###
  31. class Backend( BackendBase ):
  32. '''
  33. Kiibohd Code-Generation Backend
  34. Kiibohd specific code generation.
  35. '''
  36. # Default templates and output files
  37. templatePaths = ["templates/kiibohdKeymap.h", "templates/kiibohdDefs.h"]
  38. outputPaths = ["generatedKeymap.h", "kll_defs.h"]
  39. requiredCapabilities = {
  40. 'CONS' : 'consCtrlOut',
  41. 'NONE' : 'noneOut',
  42. 'SYS' : 'sysCtrlOut',
  43. 'USB' : 'usbKeyOut',
  44. }
  45. # Capability Lookup
  46. def capabilityLookup( self, type ):
  47. return self.requiredCapabilities[ type ];
  48. # TODO
  49. def layerInformation( self, name, date, author ):
  50. self.fill_dict['Information'] += "// Name: {0}\n".format( "TODO" )
  51. self.fill_dict['Information'] += "// Version: {0}\n".format( "TODO" )
  52. self.fill_dict['Information'] += "// Date: {0}\n".format( "TODO" )
  53. self.fill_dict['Information'] += "// Author: {0}\n".format( "TODO" )
  54. # Processes content for fill tags and does any needed dataset calculations
  55. def process( self, capabilities, macros, variables, gitRev, gitChanges ):
  56. # Build string list of compiler arguments
  57. compilerArgs = ""
  58. for arg in sys.argv:
  59. if "--" in arg or ".py" in arg:
  60. compilerArgs += "// {0}\n".format( arg )
  61. else:
  62. compilerArgs += "// {0}\n".format( arg )
  63. # Build a string of modified files, if any
  64. gitChangesStr = "\n"
  65. if len( gitChanges ) > 0:
  66. for gitFile in gitChanges:
  67. gitChangesStr += "// {0}\n".format( gitFile )
  68. else:
  69. gitChangesStr = " None\n"
  70. # Prepare BaseLayout and Layer Info
  71. baseLayoutInfo = ""
  72. defaultLayerInfo = ""
  73. partialLayersInfo = ""
  74. for file, name in zip( variables.baseLayout['*LayerFiles'], variables.baseLayout['*NameStack'] ):
  75. baseLayoutInfo += "// {0}\n// {1}\n".format( name, file )
  76. if '*LayerFiles' in variables.layerVariables[0].keys():
  77. for file, name in zip( variables.layerVariables[0]['*LayerFiles'], variables.layerVariables[0]['*NameStack'] ):
  78. defaultLayerInfo += "// {0}\n// {1}\n".format( name, file )
  79. if '*LayerFiles' in variables.layerVariables[1].keys():
  80. for layer in range( 1, len( variables.layerVariables ) ):
  81. partialLayersInfo += "// Layer {0}\n".format( layer )
  82. if len( variables.layerVariables[ layer ]['*LayerFiles'] ) > 0:
  83. for file, name in zip( variables.layerVariables[ layer ]['*LayerFiles'], variables.layerVariables[ layer ]['*NameStack'] ):
  84. partialLayersInfo += "// {0}\n// {1}\n".format( name, file )
  85. ## Information ##
  86. self.fill_dict['Information'] = "// This file was generated by the kll compiler, DO NOT EDIT.\n"
  87. self.fill_dict['Information'] += "// Generation Date: {0}\n".format( date.today() )
  88. self.fill_dict['Information'] += "// KLL Backend: {0}\n".format( "kiibohd" )
  89. self.fill_dict['Information'] += "// KLL Git Rev: {0}\n".format( gitRev )
  90. self.fill_dict['Information'] += "// KLL Git Changes:{0}".format( gitChangesStr )
  91. self.fill_dict['Information'] += "// Compiler arguments:\n{0}".format( compilerArgs )
  92. self.fill_dict['Information'] += "//\n"
  93. self.fill_dict['Information'] += "// - Base Layer -\n{0}".format( baseLayoutInfo )
  94. self.fill_dict['Information'] += "// - Default Layer -\n{0}".format( defaultLayerInfo )
  95. self.fill_dict['Information'] += "// - Partial Layers -\n{0}".format( partialLayersInfo )
  96. ## Variable Information ##
  97. self.fill_dict['VariableInformation'] = ""
  98. # Iterate through the variables, output, and indicate the last file that modified it's value
  99. # Output separate tables per file, per table and overall
  100. # TODO
  101. ## Defines ##
  102. self.fill_dict['Defines'] = ""
  103. stateWordSize = ""
  104. # Iterate through defines and lookup the variables
  105. for define in variables.defines.keys():
  106. if define in variables.overallVariables.keys():
  107. self.fill_dict['Defines'] += "\n#define {0} {1}".format( variables.defines[ define ], variables.overallVariables[ define ].replace( '\n', ' \\\n' ) )
  108. if define == "stateWordSize":
  109. stateWordSize = variables.overallVariables[ define ]
  110. else:
  111. print( "{0} '{1}' not defined...".format( WARNING, define ) )
  112. ## Capabilities ##
  113. self.fill_dict['CapabilitiesFuncDecl'] = ""
  114. self.fill_dict['CapabilitiesList'] = "const Capability CapabilitiesList[] = {\n"
  115. self.fill_dict['CapabilitiesIndices'] = "typedef enum CapabilityIndex {\n"
  116. # Keys are pre-sorted
  117. for key in capabilities.keys():
  118. funcName = capabilities.funcName( key )
  119. argByteWidth = capabilities.totalArgBytes( key )
  120. self.fill_dict['CapabilitiesList'] += "\t{{ {0}, {1} }},\n".format( funcName, argByteWidth )
  121. self.fill_dict['CapabilitiesFuncDecl'] += "void {0}( uint8_t state, uint8_t stateType, uint8_t *args );\n".format( funcName )
  122. self.fill_dict['CapabilitiesIndices'] += "\t{0}_index,\n".format( funcName )
  123. self.fill_dict['CapabilitiesList'] += "};"
  124. self.fill_dict['CapabilitiesIndices'] += "} CapabilityIndex;"
  125. # Define for total number of capabilities
  126. self.fill_dict['Defines'] += "\n#define CapabilitiesNum_KLL {0}".format( len( capabilities.keys() ) )
  127. ## Results Macros ##
  128. self.fill_dict['ResultMacros'] = ""
  129. # Iterate through each of the result macros
  130. for result in range( 0, len( macros.resultsIndexSorted ) ):
  131. self.fill_dict['ResultMacros'] += "Guide_RM( {0} ) = {{ ".format( result )
  132. # Add the result macro capability index guide (including capability arguments)
  133. # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
  134. for sequence in range( 0, len( macros.resultsIndexSorted[ result ] ) ):
  135. # If the sequence is longer than 1, prepend a sequence spacer
  136. # Needed for USB behaviour, otherwise, repeated keys will not work
  137. if sequence > 0:
  138. # <single element>, <usbCodeSend capability>, <USB Code 0x00>
  139. self.fill_dict['ResultMacros'] += "1, {0}, 0x00, ".format( capabilities.getIndex( self.capabilityLookup('USB') ) )
  140. # For each combo in the sequence, add the length of the combo
  141. self.fill_dict['ResultMacros'] += "{0}, ".format( len( macros.resultsIndexSorted[ result ][ sequence ] ) )
  142. # For each combo, add each of the capabilities used and their arguments
  143. for combo in range( 0, len( macros.resultsIndexSorted[ result ][ sequence ] ) ):
  144. resultItem = macros.resultsIndexSorted[ result ][ sequence ][ combo ]
  145. # Add the capability index
  146. self.fill_dict['ResultMacros'] += "{0}, ".format( capabilities.getIndex( resultItem[0] ) )
  147. # Add each of the arguments of the capability
  148. for arg in range( 0, len( resultItem[1] ) ):
  149. # Special cases
  150. if isinstance( resultItem[1][ arg ], str ):
  151. # If this is a CONSUMER_ element, needs to be split into 2 elements
  152. # AC_ and AL_ are other sections of consumer control
  153. if re.match( '^(CONSUMER|AC|AL)_', resultItem[1][ arg ] ):
  154. tag = resultItem[1][ arg ].split( '_', 1 )[1]
  155. if '_' in tag:
  156. tag = tag.replace( '_', '' )
  157. try:
  158. lookupNum = kll_hid_lookup_dictionary['ConsCode'][ tag ][1]
  159. except KeyError as err:
  160. print ( "{0} {1} Consumer HID kll bug...please report.".format( ERROR, err ) )
  161. raise
  162. byteForm = lookupNum.to_bytes( 2, byteorder='little' ) # XXX Yes, little endian from how the uC structs work
  163. self.fill_dict['ResultMacros'] += "{0}, {1}, ".format( *byteForm )
  164. continue
  165. # None, fall-through disable
  166. elif resultItem[0] is self.capabilityLookup('NONE'):
  167. continue
  168. self.fill_dict['ResultMacros'] += "{0}, ".format( resultItem[1][ arg ] )
  169. # If sequence is longer than 1, append a sequence spacer at the end of the sequence
  170. # Required by USB to end at sequence without holding the key down
  171. if len( macros.resultsIndexSorted[ result ] ) > 1:
  172. # <single element>, <usbCodeSend capability>, <USB Code 0x00>
  173. self.fill_dict['ResultMacros'] += "1, {0}, 0x00, ".format( capabilities.getIndex( self.capabilityLookup('USB') ) )
  174. # Add list ending 0 and end of list
  175. self.fill_dict['ResultMacros'] += "0 };\n"
  176. self.fill_dict['ResultMacros'] = self.fill_dict['ResultMacros'][:-1] # Remove last newline
  177. ## Result Macro List ##
  178. self.fill_dict['ResultMacroList'] = "const ResultMacro ResultMacroList[] = {\n"
  179. # Iterate through each of the result macros
  180. for result in range( 0, len( macros.resultsIndexSorted ) ):
  181. self.fill_dict['ResultMacroList'] += "\tDefine_RM( {0} ),\n".format( result )
  182. self.fill_dict['ResultMacroList'] += "};"
  183. results_count = len( macros.resultsIndexSorted )
  184. ## Result Macro Record ##
  185. self.fill_dict['ResultMacroRecord'] = "ResultMacroRecord ResultMacroRecordList[ ResultMacroNum ];"
  186. # Define for total number of Result Macros
  187. self.fill_dict['Defines'] += "\n#define ResultMacroNum_KLL {0}".format( len( macros.resultsIndexSorted ) )
  188. ## Trigger Macros ##
  189. self.fill_dict['TriggerMacros'] = ""
  190. # Iterate through each of the trigger macros
  191. triggers_count = len( macros.triggersIndexSorted );
  192. for trigger in range( 0, len( macros.triggersIndexSorted ) ):
  193. self.fill_dict['TriggerMacros'] += "Guide_TM( {0} ) = {{ ".format( trigger )
  194. # Add the trigger macro scan code guide
  195. # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
  196. for sequence in range( 0, len( macros.triggersIndexSorted[ trigger ][0] ) ):
  197. # For each combo in the sequence, add the length of the combo
  198. self.fill_dict['TriggerMacros'] += "{0}, ".format( len( macros.triggersIndexSorted[ trigger ][0][ sequence ] ) )
  199. # For each combo, add the key type, key state and scan code
  200. for combo in range( 0, len( macros.triggersIndexSorted[ trigger ][0][ sequence ] ) ):
  201. triggerItemId = macros.triggersIndexSorted[ trigger ][0][ sequence ][ combo ]
  202. # Lookup triggerItem in ScanCodeStore
  203. triggerItemObj = macros.scanCodeStore[ triggerItemId ]
  204. triggerItem = triggerItemObj.offset( macros.interconnectOffset )
  205. # TODO Add support for Analog keys
  206. # TODO Add support for LED states
  207. self.fill_dict['TriggerMacros'] += "0x00, 0x01, 0x{0:02X}, ".format( triggerItem )
  208. # Add list ending 0 and end of list
  209. self.fill_dict['TriggerMacros'] += "0 };\n"
  210. self.fill_dict['TriggerMacros'] = self.fill_dict['TriggerMacros'][ :-1 ] # Remove last newline
  211. # check for too small stateWordSize
  212. if stateWordSize == "8" and (triggers_count > 255 or results_count > 255):
  213. print ("{0} Over 255 trigger or result macros, changing stateWordSize from {1} to 16.".format( WARNING, stateWordSize ) )
  214. print( "Results count: ", results_count )
  215. print( "Triggers count: ", triggers_count )
  216. stateWordSize == "16"
  217. self.fill_dict['Defines'] = self.fill_dict['Defines'].replace("StateWordSize_define 8", "StateWordSize_define 16")
  218. ## Trigger Macro List ##
  219. self.fill_dict['TriggerMacroList'] = "const TriggerMacro TriggerMacroList[] = {\n"
  220. # Iterate through each of the trigger macros
  221. for trigger in range( 0, len( macros.triggersIndexSorted ) ):
  222. # Use TriggerMacro Index, and the corresponding ResultMacro Index
  223. self.fill_dict['TriggerMacroList'] += "\tDefine_TM( {0}, {1} ),\n".format( trigger, macros.triggersIndexSorted[ trigger ][1] )
  224. self.fill_dict['TriggerMacroList'] += "};"
  225. ## Trigger Macro Record ##
  226. self.fill_dict['TriggerMacroRecord'] = "TriggerMacroRecord TriggerMacroRecordList[ TriggerMacroNum ];"
  227. # Define for total number of Trigger Macros
  228. self.fill_dict['Defines'] += "\n#define TriggerMacroNum_KLL {0}".format( len( macros.triggersIndexSorted ) )
  229. ## Max Scan Code ##
  230. self.fill_dict['MaxScanCode'] = "#define MaxScanCode 0x{0:X}".format( macros.overallMaxScanCode )
  231. ## Interconnect ScanCode Offset List ##
  232. self.fill_dict['ScanCodeInterconnectOffsetList'] = "const uint8_t InterconnectOffsetList[] = {\n"
  233. for offset in range( 0, len( macros.interconnectOffset ) ):
  234. self.fill_dict['ScanCodeInterconnectOffsetList'] += "\t0x{0:02X},\n".format( macros.interconnectOffset[ offset ] )
  235. self.fill_dict['ScanCodeInterconnectOffsetList'] += "};"
  236. ## Max Interconnect Nodes ##
  237. self.fill_dict['InterconnectNodeMax'] = "#define InterconnectNodeMax 0x{0:X}\n".format( len( macros.interconnectOffset ) )
  238. ## Default Layer and Default Layer Scan Map ##
  239. self.fill_dict['DefaultLayerTriggerList'] = ""
  240. self.fill_dict['DefaultLayerScanMap'] = "const nat_ptr_t *default_scanMap[] = {\n"
  241. # Iterate over triggerList and generate a C trigger array for the default map and default map array
  242. for triggerList in range( macros.firstScanCode[0], len( macros.triggerList[0] ) ):
  243. # Generate ScanCode index and triggerList length
  244. self.fill_dict['DefaultLayerTriggerList'] += "Define_TL( default, 0x{0:02X} ) = {{ {1}".format( triggerList, len( macros.triggerList[0][ triggerList ] ) )
  245. # Add scanCode trigger list to Default Layer Scan Map
  246. self.fill_dict['DefaultLayerScanMap'] += "default_tl_0x{0:02X}, ".format( triggerList )
  247. # Add each item of the trigger list
  248. for triggerItem in macros.triggerList[0][ triggerList ]:
  249. self.fill_dict['DefaultLayerTriggerList'] += ", {0}".format( triggerItem )
  250. self.fill_dict['DefaultLayerTriggerList'] += " };\n"
  251. self.fill_dict['DefaultLayerTriggerList'] = self.fill_dict['DefaultLayerTriggerList'][:-1] # Remove last newline
  252. self.fill_dict['DefaultLayerScanMap'] = self.fill_dict['DefaultLayerScanMap'][:-2] # Remove last comma and space
  253. self.fill_dict['DefaultLayerScanMap'] += "\n};"
  254. ## Partial Layers and Partial Layer Scan Maps ##
  255. self.fill_dict['PartialLayerTriggerLists'] = ""
  256. self.fill_dict['PartialLayerScanMaps'] = ""
  257. # Iterate over each of the layers, excluding the default layer
  258. for layer in range( 1, len( macros.triggerList ) ):
  259. # Prepare each layer
  260. self.fill_dict['PartialLayerScanMaps'] += "// Partial Layer {0}\n".format( layer )
  261. self.fill_dict['PartialLayerScanMaps'] += "const nat_ptr_t *layer{0}_scanMap[] = {{\n".format( layer )
  262. self.fill_dict['PartialLayerTriggerLists'] += "// Partial Layer {0}\n".format( layer )
  263. # Iterate over triggerList and generate a C trigger array for the layer
  264. for triggerList in range( macros.firstScanCode[ layer ], len( macros.triggerList[ layer ] ) ):
  265. # Generate ScanCode index and triggerList length
  266. self.fill_dict['PartialLayerTriggerLists'] += "Define_TL( layer{0}, 0x{1:02X} ) = {{ {2}".format( layer, triggerList, len( macros.triggerList[ layer ][ triggerList ] ) )
  267. # Add scanCode trigger list to Default Layer Scan Map
  268. self.fill_dict['PartialLayerScanMaps'] += "layer{0}_tl_0x{1:02X}, ".format( layer, triggerList )
  269. # Add each item of the trigger list
  270. for trigger in macros.triggerList[ layer ][ triggerList ]:
  271. self.fill_dict['PartialLayerTriggerLists'] += ", {0}".format( trigger )
  272. self.fill_dict['PartialLayerTriggerLists'] += " };\n"
  273. self.fill_dict['PartialLayerTriggerLists'] += "\n"
  274. self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last comma and space
  275. self.fill_dict['PartialLayerScanMaps'] += "\n};\n\n"
  276. self.fill_dict['PartialLayerTriggerLists'] = self.fill_dict['PartialLayerTriggerLists'][:-2] # Remove last 2 newlines
  277. self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last 2 newlines
  278. ## Layer Index List ##
  279. self.fill_dict['LayerIndexList'] = "const Layer LayerIndex[] = {\n"
  280. # Iterate over each layer, adding it to the list
  281. for layer in range( 0, len( macros.triggerList ) ):
  282. # Lookup first scancode in map
  283. firstScanCode = macros.firstScanCode[ layer ]
  284. # Generate stacked name
  285. stackName = ""
  286. if '*NameStack' in variables.layerVariables[ layer ].keys():
  287. for name in range( 0, len( variables.layerVariables[ layer ]['*NameStack'] ) ):
  288. stackName += "{0} + ".format( variables.layerVariables[ layer ]['*NameStack'][ name ] )
  289. stackName = stackName[:-3]
  290. # Default map is a special case, always the first index
  291. if layer == 0:
  292. self.fill_dict['LayerIndexList'] += '\tLayer_IN( default_scanMap, "D: {1}", 0x{0:02X} ),\n'.format( firstScanCode, stackName )
  293. else:
  294. self.fill_dict['LayerIndexList'] += '\tLayer_IN( layer{0}_scanMap, "{0}: {2}", 0x{1:02X} ),\n'.format( layer, firstScanCode, stackName )
  295. self.fill_dict['LayerIndexList'] += "};"
  296. # Define for total number of Trigger Macros
  297. self.fill_dict['Defines'] += "\n#define LayerNum_KLL {0}".format( len( macros.triggerList ) )
  298. ## Layer State ##
  299. self.fill_dict['LayerState'] = "uint8_t LayerState[ LayerNum ];"