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