3 KLL Compiler - Kiibohd Backend
5 Backend code generator for the Kiibohd Controller firmware.
7 # Copyright (C) 2014-2016 by Jacob Alexander
9 # This file is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
14 # This file is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with this file. If not, see <http://www.gnu.org/licenses/>.
28 from datetime import date
30 # Modifying Python Path, which is dumb, but the only way to import up one directory...
31 sys.path.append( os.path.expanduser('..') )
33 from kll_lib.backends import *
34 from kll_lib.containers import *
35 from kll_lib.hid_dict import *
40 class Backend( BackendBase ):
42 Kiibohd Code-Generation Backend
44 Kiibohd specific code generation.
46 # Default templates and output files
47 templatePaths = ["templates/kiibohdKeymap.h", "templates/kiibohdDefs.h"]
48 outputPaths = ["generatedKeymap.h", "kll_defs.h"]
50 requiredCapabilities = {
51 'CONS' : 'consCtrlOut',
58 def capabilityLookup( self, type ):
59 return self.requiredCapabilities[ type ];
63 def layerInformation( self, name, date, author ):
64 self.fill_dict['Information'] += "// Name: {0}\n".format( "TODO" )
65 self.fill_dict['Information'] += "// Version: {0}\n".format( "TODO" )
66 self.fill_dict['Information'] += "// Date: {0}\n".format( "TODO" )
67 self.fill_dict['Information'] += "// Author: {0}\n".format( "TODO" )
70 # Processes content for fill tags and does any needed dataset calculations
71 def process( self, capabilities, macros, variables, gitRev, gitChanges ):
72 # Build string list of compiler arguments
75 if "--" in arg or ".py" in arg:
76 compilerArgs += "// {0}\n".format( arg )
78 compilerArgs += "// {0}\n".format( arg )
80 # Build a string of modified files, if any
82 if len( gitChanges ) > 0:
83 for gitFile in gitChanges:
84 gitChangesStr += "// {0}\n".format( gitFile )
86 gitChangesStr = " None\n"
88 # Prepare BaseLayout and Layer Info
91 partialLayersInfo = ""
92 for file, name in zip( variables.baseLayout['*LayerFiles'], variables.baseLayout['*NameStack'] ):
93 baseLayoutInfo += "// {0}\n// {1}\n".format( name, file )
94 if '*LayerFiles' in variables.layerVariables[0].keys():
95 for file, name in zip( variables.layerVariables[0]['*LayerFiles'], variables.layerVariables[0]['*NameStack'] ):
96 defaultLayerInfo += "// {0}\n// {1}\n".format( name, file )
97 if '*LayerFiles' in variables.layerVariables[1].keys():
98 for layer in range( 1, len( variables.layerVariables ) ):
99 partialLayersInfo += "// Layer {0}\n".format( layer )
100 if len( variables.layerVariables[ layer ]['*LayerFiles'] ) > 0:
101 for file, name in zip( variables.layerVariables[ layer ]['*LayerFiles'], variables.layerVariables[ layer ]['*NameStack'] ):
102 partialLayersInfo += "// {0}\n// {1}\n".format( name, file )
106 self.fill_dict['Information'] = "// This file was generated by the kll compiler, DO NOT EDIT.\n"
107 self.fill_dict['Information'] += "// Generation Date: {0}\n".format( date.today() )
108 self.fill_dict['Information'] += "// KLL Backend: {0}\n".format( "kiibohd" )
109 self.fill_dict['Information'] += "// KLL Git Rev: {0}\n".format( gitRev )
110 self.fill_dict['Information'] += "// KLL Git Changes:{0}".format( gitChangesStr )
111 self.fill_dict['Information'] += "// Compiler arguments:\n{0}".format( compilerArgs )
112 self.fill_dict['Information'] += "//\n"
113 self.fill_dict['Information'] += "// - Base Layer -\n{0}".format( baseLayoutInfo )
114 self.fill_dict['Information'] += "// - Default Layer -\n{0}".format( defaultLayerInfo )
115 self.fill_dict['Information'] += "// - Partial Layers -\n{0}".format( partialLayersInfo )
118 ## Variable Information ##
119 self.fill_dict['VariableInformation'] = ""
121 # Iterate through the variables, output, and indicate the last file that modified it's value
122 # Output separate tables per file, per table and overall
127 self.fill_dict['Defines'] = ""
130 # Iterate through defines and lookup the variables
131 for define in variables.defines.keys():
132 if define in variables.overallVariables.keys():
133 self.fill_dict['Defines'] += "\n#define {0} {1}".format( variables.defines[ define ], variables.overallVariables[ define ].replace( '\n', ' \\\n' ) )
134 if define == "stateWordSize":
135 stateWordSize = variables.overallVariables[ define ]
137 print( "{0} '{1}' not defined...".format( WARNING, define ) )
141 self.fill_dict['CapabilitiesFuncDecl'] = ""
142 self.fill_dict['CapabilitiesList'] = "const Capability CapabilitiesList[] = {\n"
143 self.fill_dict['CapabilitiesIndices'] = "typedef enum CapabilityIndex {\n"
145 # Keys are pre-sorted
146 for key in capabilities.keys():
147 funcName = capabilities.funcName( key )
148 argByteWidth = capabilities.totalArgBytes( key )
149 self.fill_dict['CapabilitiesList'] += "\t{{ {0}, {1} }},\n".format( funcName, argByteWidth )
150 self.fill_dict['CapabilitiesFuncDecl'] += "void {0}( uint8_t state, uint8_t stateType, uint8_t *args );\n".format( funcName )
151 self.fill_dict['CapabilitiesIndices'] += "\t{0}_index,\n".format( funcName )
153 self.fill_dict['CapabilitiesList'] += "};"
154 self.fill_dict['CapabilitiesIndices'] += "} CapabilityIndex;"
156 # Define for total number of capabilities
157 self.fill_dict['Defines'] += "\n#define CapabilitiesNum_KLL {0}".format( len( capabilities.keys() ) )
161 self.fill_dict['ResultMacros'] = ""
163 # Iterate through each of the result macros
164 for result in range( 0, len( macros.resultsIndexSorted ) ):
165 self.fill_dict['ResultMacros'] += "Guide_RM( {0} ) = {{ ".format( result )
167 # Add the result macro capability index guide (including capability arguments)
168 # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
169 for sequence in range( 0, len( macros.resultsIndexSorted[ result ] ) ):
170 # If the sequence is longer than 1, prepend a sequence spacer
171 # Needed for USB behaviour, otherwise, repeated keys will not work
173 # <single element>, <usbCodeSend capability>, <USB Code 0x00>
174 self.fill_dict['ResultMacros'] += "1, {0}, 0x00, ".format( capabilities.getIndex( self.capabilityLookup('USB') ) )
176 # For each combo in the sequence, add the length of the combo
177 self.fill_dict['ResultMacros'] += "{0}, ".format( len( macros.resultsIndexSorted[ result ][ sequence ] ) )
179 # For each combo, add each of the capabilities used and their arguments
180 for combo in range( 0, len( macros.resultsIndexSorted[ result ][ sequence ] ) ):
181 resultItem = macros.resultsIndexSorted[ result ][ sequence ][ combo ]
183 # Add the capability index
184 self.fill_dict['ResultMacros'] += "{0}, ".format( capabilities.getIndex( resultItem[0] ) )
186 # Add each of the arguments of the capability
187 for arg in range( 0, len( resultItem[1] ) ):
189 if isinstance( resultItem[1][ arg ], str ):
190 # If this is a CONSUMER_ element, needs to be split into 2 elements
191 # AC_ and AL_ are other sections of consumer control
192 if re.match( '^(CONSUMER|AC|AL)_', resultItem[1][ arg ] ):
193 tag = resultItem[1][ arg ].split( '_', 1 )[1]
195 tag = tag.replace( '_', '' )
197 lookupNum = kll_hid_lookup_dictionary['ConsCode'][ tag ][1]
198 except KeyError as err:
199 print ( "{0} {1} Consumer HID kll bug...please report.".format( ERROR, err ) )
201 byteForm = lookupNum.to_bytes( 2, byteorder='little' ) # XXX Yes, little endian from how the uC structs work
202 self.fill_dict['ResultMacros'] += "{0}, {1}, ".format( *byteForm )
205 # None, fall-through disable
206 elif resultItem[0] is self.capabilityLookup('NONE'):
209 self.fill_dict['ResultMacros'] += "{0}, ".format( resultItem[1][ arg ] )
211 # If sequence is longer than 1, append a sequence spacer at the end of the sequence
212 # Required by USB to end at sequence without holding the key down
213 if len( macros.resultsIndexSorted[ result ] ) > 1:
214 # <single element>, <usbCodeSend capability>, <USB Code 0x00>
215 self.fill_dict['ResultMacros'] += "1, {0}, 0x00, ".format( capabilities.getIndex( self.capabilityLookup('USB') ) )
217 # Add list ending 0 and end of list
218 self.fill_dict['ResultMacros'] += "0 };\n"
219 self.fill_dict['ResultMacros'] = self.fill_dict['ResultMacros'][:-1] # Remove last newline
222 ## Result Macro List ##
223 self.fill_dict['ResultMacroList'] = "const ResultMacro ResultMacroList[] = {\n"
225 # Iterate through each of the result macros
226 for result in range( 0, len( macros.resultsIndexSorted ) ):
227 self.fill_dict['ResultMacroList'] += "\tDefine_RM( {0} ),\n".format( result )
228 self.fill_dict['ResultMacroList'] += "};"
230 results_count = len( macros.resultsIndexSorted )
233 ## Result Macro Record ##
234 self.fill_dict['ResultMacroRecord'] = "ResultMacroRecord ResultMacroRecordList[ ResultMacroNum ];"
236 # Define for total number of Result Macros
237 self.fill_dict['Defines'] += "\n#define ResultMacroNum_KLL {0}".format( len( macros.resultsIndexSorted ) )
241 self.fill_dict['TriggerMacros'] = ""
243 # Iterate through each of the trigger macros
244 triggers_count = len( macros.triggersIndexSorted );
245 for trigger in range( 0, len( macros.triggersIndexSorted ) ):
246 self.fill_dict['TriggerMacros'] += "Guide_TM( {0} ) = {{ ".format( trigger )
248 # Add the trigger macro scan code guide
249 # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
250 for sequence in range( 0, len( macros.triggersIndexSorted[ trigger ][0] ) ):
251 # For each combo in the sequence, add the length of the combo
252 self.fill_dict['TriggerMacros'] += "{0}, ".format( len( macros.triggersIndexSorted[ trigger ][0][ sequence ] ) )
254 # For each combo, add the key type, key state and scan code
255 for combo in range( 0, len( macros.triggersIndexSorted[ trigger ][0][ sequence ] ) ):
256 triggerItemId = macros.triggersIndexSorted[ trigger ][0][ sequence ][ combo ]
258 # Lookup triggerItem in ScanCodeStore
259 triggerItemObj = macros.scanCodeStore[ triggerItemId ]
260 triggerItem = triggerItemObj.offset( macros.interconnectOffset )
262 # TODO Add support for Analog keys
263 # TODO Add support for LED states
264 self.fill_dict['TriggerMacros'] += "0x00, 0x01, 0x{0:02X}, ".format( triggerItem )
266 # Add list ending 0 and end of list
267 self.fill_dict['TriggerMacros'] += "0 };\n"
268 self.fill_dict['TriggerMacros'] = self.fill_dict['TriggerMacros'][ :-1 ] # Remove last newline
270 # check for too small stateWordSize
271 if stateWordSize == "8" and (triggers_count > 255 or results_count > 255):
272 print ("{0} Over 255 trigger or result macros, changing stateWordSize from {1} to 16.".format( WARNING, stateWordSize ) )
273 print( "Results count: ", results_count )
274 print( "Triggers count: ", triggers_count )
275 stateWordSize == "16"
276 self.fill_dict['Defines'] = self.fill_dict['Defines'].replace("StateWordSize_define 8", "StateWordSize_define 16")
278 ## Trigger Macro List ##
279 self.fill_dict['TriggerMacroList'] = "const TriggerMacro TriggerMacroList[] = {\n"
281 # Iterate through each of the trigger macros
282 for trigger in range( 0, len( macros.triggersIndexSorted ) ):
283 # Use TriggerMacro Index, and the corresponding ResultMacro Index
284 self.fill_dict['TriggerMacroList'] += "\tDefine_TM( {0}, {1} ),\n".format( trigger, macros.triggersIndexSorted[ trigger ][1] )
285 self.fill_dict['TriggerMacroList'] += "};"
288 ## Trigger Macro Record ##
289 self.fill_dict['TriggerMacroRecord'] = "TriggerMacroRecord TriggerMacroRecordList[ TriggerMacroNum ];"
291 # Define for total number of Trigger Macros
292 self.fill_dict['Defines'] += "\n#define TriggerMacroNum_KLL {0}".format( len( macros.triggersIndexSorted ) )
296 self.fill_dict['MaxScanCode'] = "#define MaxScanCode 0x{0:X}".format( macros.overallMaxScanCode )
299 ## Interconnect ScanCode Offset List ##
300 self.fill_dict['ScanCodeInterconnectOffsetList'] = "const uint8_t InterconnectOffsetList[] = {\n"
301 for offset in range( 0, len( macros.interconnectOffset ) ):
302 self.fill_dict['ScanCodeInterconnectOffsetList'] += "\t0x{0:02X},\n".format( macros.interconnectOffset[ offset ] )
303 self.fill_dict['ScanCodeInterconnectOffsetList'] += "};"
306 ## Max Interconnect Nodes ##
307 self.fill_dict['InterconnectNodeMax'] = "#define InterconnectNodeMax 0x{0:X}\n".format( len( macros.interconnectOffset ) )
310 ## Default Layer and Default Layer Scan Map ##
311 self.fill_dict['DefaultLayerTriggerList'] = ""
312 self.fill_dict['DefaultLayerScanMap'] = "const nat_ptr_t *default_scanMap[] = {\n"
314 # Iterate over triggerList and generate a C trigger array for the default map and default map array
315 for triggerList in range( macros.firstScanCode[0], len( macros.triggerList[0] ) ):
316 # Generate ScanCode index and triggerList length
317 self.fill_dict['DefaultLayerTriggerList'] += "Define_TL( default, 0x{0:02X} ) = {{ {1}".format( triggerList, len( macros.triggerList[0][ triggerList ] ) )
319 # Add scanCode trigger list to Default Layer Scan Map
320 self.fill_dict['DefaultLayerScanMap'] += "default_tl_0x{0:02X}, ".format( triggerList )
322 # Add each item of the trigger list
323 for triggerItem in macros.triggerList[0][ triggerList ]:
324 self.fill_dict['DefaultLayerTriggerList'] += ", {0}".format( triggerItem )
326 self.fill_dict['DefaultLayerTriggerList'] += " };\n"
327 self.fill_dict['DefaultLayerTriggerList'] = self.fill_dict['DefaultLayerTriggerList'][:-1] # Remove last newline
328 self.fill_dict['DefaultLayerScanMap'] = self.fill_dict['DefaultLayerScanMap'][:-2] # Remove last comma and space
329 self.fill_dict['DefaultLayerScanMap'] += "\n};"
332 ## Partial Layers and Partial Layer Scan Maps ##
333 self.fill_dict['PartialLayerTriggerLists'] = ""
334 self.fill_dict['PartialLayerScanMaps'] = ""
336 # Iterate over each of the layers, excluding the default layer
337 for layer in range( 1, len( macros.triggerList ) ):
339 self.fill_dict['PartialLayerScanMaps'] += "// Partial Layer {0}\n".format( layer )
340 self.fill_dict['PartialLayerScanMaps'] += "const nat_ptr_t *layer{0}_scanMap[] = {{\n".format( layer )
341 self.fill_dict['PartialLayerTriggerLists'] += "// Partial Layer {0}\n".format( layer )
343 # Iterate over triggerList and generate a C trigger array for the layer
344 for triggerList in range( macros.firstScanCode[ layer ], len( macros.triggerList[ layer ] ) ):
345 # Generate ScanCode index and triggerList length
346 self.fill_dict['PartialLayerTriggerLists'] += "Define_TL( layer{0}, 0x{1:02X} ) = {{ {2}".format( layer, triggerList, len( macros.triggerList[ layer ][ triggerList ] ) )
348 # Add scanCode trigger list to Default Layer Scan Map
349 self.fill_dict['PartialLayerScanMaps'] += "layer{0}_tl_0x{1:02X}, ".format( layer, triggerList )
351 # Add each item of the trigger list
352 for trigger in macros.triggerList[ layer ][ triggerList ]:
353 self.fill_dict['PartialLayerTriggerLists'] += ", {0}".format( trigger )
355 self.fill_dict['PartialLayerTriggerLists'] += " };\n"
356 self.fill_dict['PartialLayerTriggerLists'] += "\n"
357 self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last comma and space
358 self.fill_dict['PartialLayerScanMaps'] += "\n};\n\n"
359 self.fill_dict['PartialLayerTriggerLists'] = self.fill_dict['PartialLayerTriggerLists'][:-2] # Remove last 2 newlines
360 self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last 2 newlines
363 ## Layer Index List ##
364 self.fill_dict['LayerIndexList'] = "const Layer LayerIndex[] = {\n"
366 # Iterate over each layer, adding it to the list
367 for layer in range( 0, len( macros.triggerList ) ):
368 # Lookup first scancode in map
369 firstScanCode = macros.firstScanCode[ layer ]
371 # Generate stacked name
373 if '*NameStack' in variables.layerVariables[ layer ].keys():
374 for name in range( 0, len( variables.layerVariables[ layer ]['*NameStack'] ) ):
375 stackName += "{0} + ".format( variables.layerVariables[ layer ]['*NameStack'][ name ] )
376 stackName = stackName[:-3]
378 # Default map is a special case, always the first index
380 self.fill_dict['LayerIndexList'] += '\tLayer_IN( default_scanMap, "D: {1}", 0x{0:02X} ),\n'.format( firstScanCode, stackName )
382 self.fill_dict['LayerIndexList'] += '\tLayer_IN( layer{0}_scanMap, "{0}: {2}", 0x{1:02X} ),\n'.format( layer, firstScanCode, stackName )
383 self.fill_dict['LayerIndexList'] += "};"
385 # Define for total number of Trigger Macros
386 self.fill_dict['Defines'] += "\n#define LayerNum_KLL {0}".format( len( macros.triggerList ) )
390 self.fill_dict['LayerState'] = "uint8_t LayerState[ LayerNum ];"