2 # KLL Compiler - Kiibohd Backend
4 # Backend code generator for the Kiibohd Controller firmware.
6 # Copyright (C) 2014-2015 by Jacob Alexander
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.
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.
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/>.
27 from datetime import date
29 # Modifying Python Path, which is dumb, but the only way to import up one directory...
30 sys.path.append( os.path.expanduser('..') )
32 from kll_lib.containers import *
37 ## Print Decorator Variables
38 ERROR = '\033[5;1;31mERROR\033[0m:'
39 WARNING = '\033[5;1;33mWARNING\033[0m:'
47 # Looks for template file and builds list of fill tags
48 def __init__( self, templatePath, definesTemplatePath ):
49 # Does template exist?
50 if not os.path.isfile( templatePath ):
51 print ( "{0} '{1}' does not exist...".format( ERROR, templatePath ) )
54 self.definesTemplatePath = definesTemplatePath
55 self.templatePath = templatePath
56 self.fill_dict = dict()
58 # Generate list of fill tags
60 with open( templatePath, 'r' ) as openFile:
62 match = re.findall( '<\|([^|>]+)\|>', line )
64 self.tagList.append( item )
65 with open( definesTemplatePath, 'r' ) as openFile:
67 match = re.findall( '<\|([^|>]+)\|>', line )
69 self.tagList.append( item )
72 # USB Code Capability Name
73 def usbCodeCapability( self ):
78 def layerInformation( self, name, date, author ):
79 self.fill_dict['Information'] += "// Name: {0}\n".format( "TODO" )
80 self.fill_dict['Information'] += "// Version: {0}\n".format( "TODO" )
81 self.fill_dict['Information'] += "// Date: {0}\n".format( "TODO" )
82 self.fill_dict['Information'] += "// Author: {0}\n".format( "TODO" )
85 # Processes content for fill tags and does any needed dataset calculations
86 def process( self, capabilities, macros, variables, gitRev, gitChanges ):
87 # Build string list of compiler arguments
90 if "--" in arg or ".py" in arg:
91 compilerArgs += "// {0}\n".format( arg )
93 compilerArgs += "// {0}\n".format( arg )
95 # Build a string of modified files, if any
97 if len( gitChanges ) > 0:
98 for gitFile in gitChanges:
99 gitChangesStr += "// {0}\n".format( gitFile )
101 gitChangesStr = " None\n"
105 self.fill_dict['Information'] = "// This file was generated by the kll compiler, DO NOT EDIT.\n"
106 self.fill_dict['Information'] += "// Generation Date: {0}\n".format( date.today() )
107 self.fill_dict['Information'] += "// KLL Backend: {0}\n".format( "kiibohd" )
108 self.fill_dict['Information'] += "// KLL Git Rev: {0}\n".format( gitRev )
109 self.fill_dict['Information'] += "// KLL Git Changes:{0}".format( gitChangesStr )
110 self.fill_dict['Information'] += "// Compiler arguments:\n{0}".format( compilerArgs )
111 self.fill_dict['Information'] += "//\n"
112 self.fill_dict['Information'] += "// - Base Layer -\n"
113 self.fill_dict['Information'] += "// - Default Layer -\n"
114 self.fill_dict['Information'] += "// - Partial Layers -\n"
117 ## Variable Information ##
118 self.fill_dict['VariableInformation'] = ""
120 # Iterate through the variables, output, and indicate the last file that modified it's value
121 # Output separate tables per file, per table and overall
126 self.fill_dict['Defines'] = ""
128 # Iterate through defines and lookup the variables
129 for define in variables.defines.keys():
130 if define in variables.overallVariables.keys():
131 self.fill_dict['Defines'] += "\n#define {0} {1}".format( variables.defines[ define ], variables.overallVariables[ define ] )
133 print( "{0} '{1}' not defined...".format( WARNING, define ) )
137 self.fill_dict['CapabilitiesList'] = "const Capability CapabilitiesList[] = {\n"
139 # Keys are pre-sorted
140 for key in capabilities.keys():
141 funcName = capabilities.funcName( key )
142 argByteWidth = capabilities.totalArgBytes( key )
143 self.fill_dict['CapabilitiesList'] += "\t{{ {0}, {1} }},\n".format( funcName, argByteWidth )
145 self.fill_dict['CapabilitiesList'] += "};"
149 self.fill_dict['ResultMacros'] = ""
151 # Iterate through each of the result macros
152 for result in range( 0, len( macros.resultsIndexSorted ) ):
153 self.fill_dict['ResultMacros'] += "Guide_RM( {0} ) = {{ ".format( result )
155 # Add the result macro capability index guide (including capability arguments)
156 # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
157 for sequence in range( 0, len( macros.resultsIndexSorted[ result ] ) ):
158 # If the sequence is longer than 1, prepend a sequence spacer
159 # Needed for USB behaviour, otherwise, repeated keys will not work
161 # <single element>, <usbCodeSend capability>, <USB Code 0x00>
162 self.fill_dict['ResultMacros'] += "1, {0}, 0x00, ".format( capabilities.getIndex( self.usbCodeCapability() ) )
164 # For each combo in the sequence, add the length of the combo
165 self.fill_dict['ResultMacros'] += "{0}, ".format( len( macros.resultsIndexSorted[ result ][ sequence ] ) )
167 # For each combo, add each of the capabilities used and their arguments
168 for combo in range( 0, len( macros.resultsIndexSorted[ result ][ sequence ] ) ):
169 resultItem = macros.resultsIndexSorted[ result ][ sequence ][ combo ]
171 # Add the capability index
172 self.fill_dict['ResultMacros'] += "{0}, ".format( capabilities.getIndex( resultItem[0] ) )
174 # Add each of the arguments of the capability
175 for arg in range( 0, len( resultItem[1] ) ):
176 self.fill_dict['ResultMacros'] += "0x{0:02X}, ".format( resultItem[1][ arg ] )
178 # If sequence is longer than 1, append a sequence spacer at the end of the sequence
179 # Required by USB to end at sequence without holding the key down
180 if len( macros.resultsIndexSorted[ result ] ) > 1:
181 # <single element>, <usbCodeSend capability>, <USB Code 0x00>
182 self.fill_dict['ResultMacros'] += "1, {0}, 0x00, ".format( capabilities.getIndex( self.usbCodeCapability() ) )
184 # Add list ending 0 and end of list
185 self.fill_dict['ResultMacros'] += "0 };\n"
186 self.fill_dict['ResultMacros'] = self.fill_dict['ResultMacros'][:-1] # Remove last newline
189 ## Result Macro List ##
190 self.fill_dict['ResultMacroList'] = "const ResultMacro ResultMacroList[] = {\n"
192 # Iterate through each of the result macros
193 for result in range( 0, len( macros.resultsIndexSorted ) ):
194 self.fill_dict['ResultMacroList'] += "\tDefine_RM( {0} ),\n".format( result )
195 self.fill_dict['ResultMacroList'] += "};"
198 ## Result Macro Record ##
199 self.fill_dict['ResultMacroRecord'] = "ResultMacroRecord ResultMacroRecordList[ ResultMacroNum ];"
203 self.fill_dict['TriggerMacros'] = ""
205 # Iterate through each of the trigger macros
206 for trigger in range( 0, len( macros.triggersIndexSorted ) ):
207 self.fill_dict['TriggerMacros'] += "Guide_TM( {0} ) = {{ ".format( trigger )
209 # Add the trigger macro scan code guide
210 # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
211 for sequence in range( 0, len( macros.triggersIndexSorted[ trigger ][ 0 ] ) ):
212 # For each combo in the sequence, add the length of the combo
213 self.fill_dict['TriggerMacros'] += "{0}, ".format( len( macros.triggersIndexSorted[ trigger ][0][ sequence ] ) )
215 # For each combo, add the key type, key state and scan code
216 for combo in range( 0, len( macros.triggersIndexSorted[ trigger ][ 0 ][ sequence ] ) ):
217 triggerItem = macros.triggersIndexSorted[ trigger ][ 0 ][ sequence ][ combo ]
219 # TODO Add support for Analog keys
220 # TODO Add support for LED states
221 self.fill_dict['TriggerMacros'] += "0x00, 0x01, 0x{0:02X}, ".format( triggerItem )
223 # Add list ending 0 and end of list
224 self.fill_dict['TriggerMacros'] += "0 };\n"
225 self.fill_dict['TriggerMacros'] = self.fill_dict['TriggerMacros'][ :-1 ] # Remove last newline
228 ## Trigger Macro List ##
229 self.fill_dict['TriggerMacroList'] = "const TriggerMacro TriggerMacroList[] = {\n"
231 # Iterate through each of the trigger macros
232 for trigger in range( 0, len( macros.triggersIndexSorted ) ):
233 # Use TriggerMacro Index, and the corresponding ResultMacro Index
234 self.fill_dict['TriggerMacroList'] += "\tDefine_TM( {0}, {1} ),\n".format( trigger, macros.triggersIndexSorted[ trigger ][1] )
235 self.fill_dict['TriggerMacroList'] += "};"
238 ## Trigger Macro Record ##
239 self.fill_dict['TriggerMacroRecord'] = "TriggerMacroRecord TriggerMacroRecordList[ TriggerMacroNum ];"
243 self.fill_dict['MaxScanCode'] = "#define MaxScanCode 0x{0:X}".format( macros.overallMaxScanCode )
246 ## Default Layer and Default Layer Scan Map ##
247 self.fill_dict['DefaultLayerTriggerList'] = ""
248 self.fill_dict['DefaultLayerScanMap'] = "const nat_ptr_t *default_scanMap[] = {\n"
250 # Iterate over triggerList and generate a C trigger array for the default map and default map array
251 for triggerList in range( macros.firstScanCode[ 0 ], len( macros.triggerList[ 0 ] ) ):
252 # Generate ScanCode index and triggerList length
253 self.fill_dict['DefaultLayerTriggerList'] += "Define_TL( default, 0x{0:02X} ) = {{ {1}".format( triggerList, len( macros.triggerList[ 0 ][ triggerList ] ) )
255 # Add scanCode trigger list to Default Layer Scan Map
256 self.fill_dict['DefaultLayerScanMap'] += "default_tl_0x{0:02X}, ".format( triggerList )
258 # Add each item of the trigger list
259 for trigger in macros.triggerList[ 0 ][ triggerList ]:
260 self.fill_dict['DefaultLayerTriggerList'] += ", {0}".format( trigger )
262 self.fill_dict['DefaultLayerTriggerList'] += " };\n"
263 self.fill_dict['DefaultLayerTriggerList'] = self.fill_dict['DefaultLayerTriggerList'][:-1] # Remove last newline
264 self.fill_dict['DefaultLayerScanMap'] = self.fill_dict['DefaultLayerScanMap'][:-2] # Remove last comma and space
265 self.fill_dict['DefaultLayerScanMap'] += "\n};"
268 ## Partial Layers and Partial Layer Scan Maps ##
269 self.fill_dict['PartialLayerTriggerLists'] = ""
270 self.fill_dict['PartialLayerScanMaps'] = ""
272 # Iterate over each of the layers, excluding the default layer
273 for layer in range( 1, len( macros.triggerList ) ):
275 self.fill_dict['PartialLayerScanMaps'] += "// Partial Layer {0}\n".format( layer )
276 self.fill_dict['PartialLayerScanMaps'] += "const nat_ptr_t *layer{0}_scanMap[] = {{\n".format( layer )
277 self.fill_dict['PartialLayerTriggerLists'] += "// Partial Layer {0}\n".format( layer )
279 # Iterate over triggerList and generate a C trigger array for the layer
280 for triggerList in range( macros.firstScanCode[ layer ], len( macros.triggerList[ layer ] ) ):
281 # Generate ScanCode index and triggerList length
282 self.fill_dict['PartialLayerTriggerLists'] += "Define_TL( layer{0}, 0x{1:02X} ) = {{ {2}".format( layer, triggerList, len( macros.triggerList[ layer ][ triggerList ] ) )
284 # Add scanCode trigger list to Default Layer Scan Map
285 self.fill_dict['PartialLayerScanMaps'] += "layer{0}_tl_0x{1:02X}, ".format( layer, triggerList )
287 # Add each item of the trigger list
288 for trigger in macros.triggerList[ layer ][ triggerList ]:
289 self.fill_dict['PartialLayerTriggerLists'] += ", {0}".format( trigger )
291 self.fill_dict['PartialLayerTriggerLists'] += " };\n"
292 self.fill_dict['PartialLayerTriggerLists'] += "\n"
293 self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last comma and space
294 self.fill_dict['PartialLayerScanMaps'] += "\n};\n\n"
295 self.fill_dict['PartialLayerTriggerLists'] = self.fill_dict['PartialLayerTriggerLists'][:-2] # Remove last 2 newlines
296 self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last 2 newlines
299 ## Layer Index List ##
300 self.fill_dict['LayerIndexList'] = "const Layer LayerIndex[] = {\n"
302 # Iterate over each layer, adding it to the list
303 for layer in range( 0, len( macros.triggerList ) ):
304 # Lookup first scancode in map
305 firstScanCode = macros.firstScanCode[ layer ]
307 # Default map is a special case, always the first index
310 self.fill_dict['LayerIndexList'] += '\tLayer_IN( default_scanMap, "DefaultMap", 0x{0:02X} ),\n'.format( firstScanCode )
312 self.fill_dict['LayerIndexList'] += '\tLayer_IN( layer{0}_scanMap, "Layer {0}", 0x{1:02X} ),\n'.format( layer, firstScanCode )
313 self.fill_dict['LayerIndexList'] += "};"
317 self.fill_dict['LayerState'] = "uint8_t LayerState[ LayerNum ];"
320 # Generates the output keymap with fill tags filled
321 def generate( self, outputPath, definesOutputPath ):
322 # Process each line of the template, outputting to the target path
323 with open( outputPath, 'w' ) as outputFile:
324 with open( self.templatePath, 'r' ) as templateFile:
325 for line in templateFile:
326 # TODO Support multiple replacements per line
327 # TODO Support replacement with other text inline
328 match = re.findall( '<\|([^|>]+)\|>', line )
330 # If match, replace with processed variable
332 outputFile.write( self.fill_dict[ match[ 0 ] ] )
333 outputFile.write("\n")
335 # Otherwise, just append template to output file
337 outputFile.write( line )
339 # Process each line of the defines template, outputting to the target path
340 with open( definesOutputPath, 'w' ) as outputFile:
341 with open( self.definesTemplatePath, 'r' ) as templateFile:
342 for line in templateFile:
343 # TODO Support multiple replacements per line
344 # TODO Support replacement with other text inline
345 match = re.findall( '<\|([^|>]+)\|>', line )
347 # If match, replace with processed variable
349 outputFile.write( self.fill_dict[ match[ 0 ] ] )
350 outputFile.write("\n")
352 # Otherwise, just append template to output file
354 outputFile.write( line )