]> git.donarmstrong.com Git - kiibohd-kll.git/blob - backends/kiibohd.py
eff049060659b48ae2004c3c19e40edc249f65c9
[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.containers import *
33
34
35 ### Decorators ###
36
37  ## Print Decorator Variables
38 ERROR = '\033[5;1;31mERROR\033[0m:'
39 WARNING = '\033[5;1;33mWARNING\033[0m:'
40
41
42
43 ### Classes ###
44
45 class Backend:
46         # Initializes backend
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 ) )
52                         sys.exit( 1 )
53
54                 self.definesTemplatePath = definesTemplatePath
55                 self.templatePath = templatePath
56                 self.fill_dict = dict()
57
58                 # Generate list of fill tags
59                 self.tagList = []
60                 with open( templatePath, 'r' ) as openFile:
61                         for line in openFile:
62                                 match = re.findall( '<\|([^|>]+)\|>', line )
63                                 for item in match:
64                                         self.tagList.append( item )
65                 with open( definesTemplatePath, 'r' ) as openFile:
66                         for line in openFile:
67                                 match = re.findall( '<\|([^|>]+)\|>', line )
68                                 for item in match:
69                                         self.tagList.append( item )
70
71
72         # USB Code Capability Name
73         def usbCodeCapability( self ):
74                 return "usbKeyOut";
75
76
77         # TODO
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" )
83
84
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
88                 compilerArgs = ""
89                 for arg in sys.argv:
90                         if "--" in arg or ".py" in arg:
91                                 compilerArgs += "//    {0}\n".format( arg )
92                         else:
93                                 compilerArgs += "//      {0}\n".format( arg )
94
95                 # Build a string of modified files, if any
96                 gitChangesStr = "\n"
97                 if len( gitChanges ) > 0:
98                         for gitFile in gitChanges:
99                                 gitChangesStr += "//    {0}\n".format( gitFile )
100                 else:
101                         gitChangesStr = "    None\n"
102
103                 # Prepare BaseLayout and Layer Info
104                 baseLayoutInfo = ""
105                 defaultLayerInfo = ""
106                 partialLayersInfo = ""
107                 for file, name in zip( variables.baseLayout['*LayerFiles'], variables.baseLayout['*NameStack'] ):
108                         baseLayoutInfo += "//    {0}\n//      {1}\n".format( name, file )
109                 for file, name in zip( variables.layerVariables[0]['*LayerFiles'], variables.layerVariables[0]['*NameStack'] ):
110                         defaultLayerInfo += "//    {0}\n//      {1}\n".format( name, file )
111                 for layer in range( 1, len( variables.layerVariables ) ):
112                         partialLayersInfo += "//    Layer {0}\n".format( layer )
113                         for file, name in zip( variables.layerVariables[ layer ]['*LayerFiles'], variables.layerVariables[ layer ]['*NameStack'] ):
114                                 partialLayersInfo += "//     {0}\n//       {1}\n".format( name, file )
115
116
117                 ## Information ##
118                 self.fill_dict['Information']  = "// This file was generated by the kll compiler, DO NOT EDIT.\n"
119                 self.fill_dict['Information'] += "// Generation Date:    {0}\n".format( date.today() )
120                 self.fill_dict['Information'] += "// KLL Backend:        {0}\n".format( "kiibohd" )
121                 self.fill_dict['Information'] += "// KLL Git Rev:        {0}\n".format( gitRev )
122                 self.fill_dict['Information'] += "// KLL Git Changes:{0}".format( gitChangesStr )
123                 self.fill_dict['Information'] += "// Compiler arguments:\n{0}".format( compilerArgs )
124                 self.fill_dict['Information'] += "//\n"
125                 self.fill_dict['Information'] += "// - Base Layer -\n{0}".format( baseLayoutInfo )
126                 self.fill_dict['Information'] += "// - Default Layer -\n{0}".format( defaultLayerInfo )
127                 self.fill_dict['Information'] += "// - Partial Layers -\n{0}".format( partialLayersInfo )
128
129
130                 ## Variable Information ##
131                 self.fill_dict['VariableInformation'] = ""
132
133                 # Iterate through the variables, output, and indicate the last file that modified it's value
134                 # Output separate tables per file, per table and overall
135                 # TODO
136
137
138                 ## Defines ##
139                 self.fill_dict['Defines'] = ""
140
141                 # Iterate through defines and lookup the variables
142                 for define in variables.defines.keys():
143                         if define in variables.overallVariables.keys():
144                                 self.fill_dict['Defines'] += "\n#define {0} {1}".format( variables.defines[ define ], variables.overallVariables[ define ] )
145                         else:
146                                 print( "{0} '{1}' not defined...".format( WARNING, define ) )
147
148
149                 ## Capabilities ##
150                 self.fill_dict['CapabilitiesList'] = "const Capability CapabilitiesList[] = {\n"
151
152                 # Keys are pre-sorted
153                 for key in capabilities.keys():
154                         funcName = capabilities.funcName( key )
155                         argByteWidth = capabilities.totalArgBytes( key )
156                         self.fill_dict['CapabilitiesList'] += "\t{{ {0}, {1} }},\n".format( funcName, argByteWidth )
157
158                 self.fill_dict['CapabilitiesList'] += "};"
159
160
161                 ## Results Macros ##
162                 self.fill_dict['ResultMacros'] = ""
163
164                 # Iterate through each of the result macros
165                 for result in range( 0, len( macros.resultsIndexSorted ) ):
166                         self.fill_dict['ResultMacros'] += "Guide_RM( {0} ) = {{ ".format( result )
167
168                         # Add the result macro capability index guide (including capability arguments)
169                         # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
170                         for sequence in range( 0, len( macros.resultsIndexSorted[ result ] ) ):
171                                 # If the sequence is longer than 1, prepend a sequence spacer
172                                 # Needed for USB behaviour, otherwise, repeated keys will not work
173                                 if sequence > 0:
174                                         # <single element>, <usbCodeSend capability>, <USB Code 0x00>
175                                         self.fill_dict['ResultMacros'] += "1, {0}, 0x00, ".format( capabilities.getIndex( self.usbCodeCapability() ) )
176
177                                 # For each combo in the sequence, add the length of the combo
178                                 self.fill_dict['ResultMacros'] += "{0}, ".format( len( macros.resultsIndexSorted[ result ][ sequence ] ) )
179
180                                 # For each combo, add each of the capabilities used and their arguments
181                                 for combo in range( 0, len( macros.resultsIndexSorted[ result ][ sequence ] ) ):
182                                         resultItem = macros.resultsIndexSorted[ result ][ sequence ][ combo ]
183
184                                         # Add the capability index
185                                         self.fill_dict['ResultMacros'] += "{0}, ".format( capabilities.getIndex( resultItem[0] ) )
186
187                                         # Add each of the arguments of the capability
188                                         for arg in range( 0, len( resultItem[1] ) ):
189                                                 self.fill_dict['ResultMacros'] += "0x{0:02X}, ".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.usbCodeCapability() ) )
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                                         triggerItem = macros.triggersIndexSorted[ trigger ][ 0 ][ sequence ][ combo ]
231
232                                         # TODO Add support for Analog keys
233                                         # TODO Add support for LED states
234                                         self.fill_dict['TriggerMacros'] += "0x00, 0x01, 0x{0:02X}, ".format( triggerItem )
235
236                         # Add list ending 0 and end of list
237                         self.fill_dict['TriggerMacros'] += "0 };\n"
238                 self.fill_dict['TriggerMacros'] = self.fill_dict['TriggerMacros'][ :-1 ] # Remove last newline
239
240
241                 ## Trigger Macro List ##
242                 self.fill_dict['TriggerMacroList'] = "const TriggerMacro TriggerMacroList[] = {\n"
243
244                 # Iterate through each of the trigger macros
245                 for trigger in range( 0, len( macros.triggersIndexSorted ) ):
246                         # Use TriggerMacro Index, and the corresponding ResultMacro Index
247                         self.fill_dict['TriggerMacroList'] += "\tDefine_TM( {0}, {1} ),\n".format( trigger, macros.triggersIndexSorted[ trigger ][1] )
248                 self.fill_dict['TriggerMacroList'] += "};"
249
250
251                 ## Trigger Macro Record ##
252                 self.fill_dict['TriggerMacroRecord'] = "TriggerMacroRecord TriggerMacroRecordList[ TriggerMacroNum ];"
253
254
255                 ## Max Scan Code ##
256                 self.fill_dict['MaxScanCode'] = "#define MaxScanCode 0x{0:X}".format( macros.overallMaxScanCode )
257
258
259                 ## Default Layer and Default Layer Scan Map ##
260                 self.fill_dict['DefaultLayerTriggerList'] = ""
261                 self.fill_dict['DefaultLayerScanMap'] = "const nat_ptr_t *default_scanMap[] = {\n"
262
263                 # Iterate over triggerList and generate a C trigger array for the default map and default map array
264                 for triggerList in range( macros.firstScanCode[ 0 ], len( macros.triggerList[ 0 ] ) ):
265                         # Generate ScanCode index and triggerList length
266                         self.fill_dict['DefaultLayerTriggerList'] += "Define_TL( default, 0x{0:02X} ) = {{ {1}".format( triggerList, len( macros.triggerList[ 0 ][ triggerList ] ) )
267
268                         # Add scanCode trigger list to Default Layer Scan Map
269                         self.fill_dict['DefaultLayerScanMap'] += "default_tl_0x{0:02X}, ".format( triggerList )
270
271                         # Add each item of the trigger list
272                         for trigger in macros.triggerList[ 0 ][ triggerList ]:
273                                 self.fill_dict['DefaultLayerTriggerList'] += ", {0}".format( trigger )
274
275                         self.fill_dict['DefaultLayerTriggerList'] += " };\n"
276                 self.fill_dict['DefaultLayerTriggerList'] = self.fill_dict['DefaultLayerTriggerList'][:-1] # Remove last newline
277                 self.fill_dict['DefaultLayerScanMap'] = self.fill_dict['DefaultLayerScanMap'][:-2] # Remove last comma and space
278                 self.fill_dict['DefaultLayerScanMap'] += "\n};"
279
280
281                 ## Partial Layers and Partial Layer Scan Maps ##
282                 self.fill_dict['PartialLayerTriggerLists'] = ""
283                 self.fill_dict['PartialLayerScanMaps'] = ""
284
285                 # Iterate over each of the layers, excluding the default layer
286                 for layer in range( 1, len( macros.triggerList ) ):
287                         # Prepare each layer
288                         self.fill_dict['PartialLayerScanMaps'] += "// Partial Layer {0}\n".format( layer )
289                         self.fill_dict['PartialLayerScanMaps'] += "const nat_ptr_t *layer{0}_scanMap[] = {{\n".format( layer )
290                         self.fill_dict['PartialLayerTriggerLists'] += "// Partial Layer {0}\n".format( layer )
291
292                         # Iterate over triggerList and generate a C trigger array for the layer
293                         for triggerList in range( macros.firstScanCode[ layer ], len( macros.triggerList[ layer ] ) ):
294                                 # Generate ScanCode index and triggerList length
295                                 self.fill_dict['PartialLayerTriggerLists'] += "Define_TL( layer{0}, 0x{1:02X} ) = {{ {2}".format( layer, triggerList, len( macros.triggerList[ layer ][ triggerList ] ) )
296
297                                 # Add scanCode trigger list to Default Layer Scan Map
298                                 self.fill_dict['PartialLayerScanMaps'] += "layer{0}_tl_0x{1:02X}, ".format( layer, triggerList )
299
300                                 # Add each item of the trigger list
301                                 for trigger in macros.triggerList[ layer ][ triggerList ]:
302                                         self.fill_dict['PartialLayerTriggerLists'] += ", {0}".format( trigger )
303
304                                 self.fill_dict['PartialLayerTriggerLists'] += " };\n"
305                         self.fill_dict['PartialLayerTriggerLists'] += "\n"
306                         self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last comma and space
307                         self.fill_dict['PartialLayerScanMaps'] += "\n};\n\n"
308                 self.fill_dict['PartialLayerTriggerLists'] = self.fill_dict['PartialLayerTriggerLists'][:-2] # Remove last 2 newlines
309                 self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last 2 newlines
310
311
312                 ## Layer Index List ##
313                 self.fill_dict['LayerIndexList'] = "const Layer LayerIndex[] = {\n"
314
315                 # Iterate over each layer, adding it to the list
316                 for layer in range( 0, len( macros.triggerList ) ):
317                         # Lookup first scancode in map
318                         firstScanCode = macros.firstScanCode[ layer ]
319
320                         # Generate stacked name
321                         stackName = ""
322                         for name in range( 0, len( variables.layerVariables[ layer ]['*NameStack'] ) ):
323                                 stackName += "{0} + ".format( variables.layerVariables[ layer ]['*NameStack'][ name ] )
324                         stackName = stackName[:-3]
325
326                         # Default map is a special case, always the first index
327                         if layer == 0:
328                                 self.fill_dict['LayerIndexList'] += '\tLayer_IN( default_scanMap, "D: {1}", 0x{0:02X} ),\n'.format( firstScanCode, stackName )
329                         else:
330                                 self.fill_dict['LayerIndexList'] += '\tLayer_IN( layer{0}_scanMap, "{0}: {2}", 0x{1:02X} ),\n'.format( layer, firstScanCode, stackName )
331                 self.fill_dict['LayerIndexList'] += "};"
332
333
334                 ## Layer State ##
335                 self.fill_dict['LayerState'] = "uint8_t LayerState[ LayerNum ];"
336
337
338         # Generates the output keymap with fill tags filled
339         def generate( self, outputPath, definesOutputPath ):
340                 # Process each line of the template, outputting to the target path
341                 with open( outputPath, 'w' ) as outputFile:
342                         with open( self.templatePath, 'r' ) as templateFile:
343                                 for line in templateFile:
344                                         # TODO Support multiple replacements per line
345                                         # TODO Support replacement with other text inline
346                                         match = re.findall( '<\|([^|>]+)\|>', line )
347
348                                         # If match, replace with processed variable
349                                         if match:
350                                                 outputFile.write( self.fill_dict[ match[ 0 ] ] )
351                                                 outputFile.write("\n")
352
353                                         # Otherwise, just append template to output file
354                                         else:
355                                                 outputFile.write( line )
356
357                 # Process each line of the defines template, outputting to the target path
358                 with open( definesOutputPath, 'w' ) as outputFile:
359                         with open( self.definesTemplatePath, 'r' ) as templateFile:
360                                 for line in templateFile:
361                                         # TODO Support multiple replacements per line
362                                         # TODO Support replacement with other text inline
363                                         match = re.findall( '<\|([^|>]+)\|>', line )
364
365                                         # If match, replace with processed variable
366                                         if match:
367                                                 outputFile.write( self.fill_dict[ match[ 0 ] ] )
368                                                 outputFile.write("\n")
369
370                                         # Otherwise, just append template to output file
371                                         else:
372                                                 outputFile.write( line )
373