]> git.donarmstrong.com Git - kiibohd-kll.git/blob - backends/kiibohd.py
c035fb28f39b1fa31bf27b38779966a864c06165
[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 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 # Modifying Python Path, which is dumb, but the only way to import up one directory...
28 sys.path.append( os.path.expanduser('..') )
29
30 from kll_lib.containers import *
31
32
33 ### Decorators ###
34
35  ## Print Decorator Variables
36 ERROR = '\033[5;1;31mERROR\033[0m:'
37 WARNING = '\033[5;1;33mWARNING\033[0m:'
38
39
40
41 ### Classes ###
42
43 class Backend:
44         # Initializes backend
45         # Looks for template file and builds list of fill tags
46         def __init__( self, templatePath, definesTemplatePath ):
47                 # Does template exist?
48                 if not os.path.isfile( templatePath ):
49                         print ( "{0} '{1}' does not exist...".format( ERROR, templatePath ) )
50                         sys.exit( 1 )
51
52                 self.definesTemplatePath = definesTemplatePath
53                 self.templatePath = templatePath
54                 self.fill_dict = dict()
55
56                 # Generate list of fill tags
57                 self.tagList = []
58                 with open( templatePath, 'r' ) as openFile:
59                         for line in openFile:
60                                 match = re.findall( '<\|([^|>]+)\|>', line )
61                                 for item in match:
62                                         self.tagList.append( item )
63                 with open( definesTemplatePath, 'r' ) as openFile:
64                         for line in openFile:
65                                 match = re.findall( '<\|([^|>]+)\|>', line )
66                                 for item in match:
67                                         self.tagList.append( item )
68
69
70         # USB Code Capability Name
71         def usbCodeCapability( self ):
72                 return "usbKeyOut";
73
74
75         def layerInformation( self, name, date, author ):
76                 self.fill_dict['Information'] += "//  Name:    {0}\n".format( "TODO" )
77                 self.fill_dict['Information'] += "//  Version: {0}\n".format( "TODO" )
78                 self.fill_dict['Information'] += "//  Date:    {0}\n".format( "TODO" )
79                 self.fill_dict['Information'] += "//  Author:  {0}\n".format( "TODO" )
80
81
82         # Processes content for fill tags and does any needed dataset calculations
83         def process( self, capabilities, macros, variables ):
84                 ## Information ##
85                 # TODO
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( "TODO" )
88                 self.fill_dict['Information'] += "// Compiler arguments: {0}\n".format( "TODO" )
89                 self.fill_dict['Information'] += "// KLL Backend:        {0}\n".format( "kiibohd" )
90                 self.fill_dict['Information'] += "// KLL Git Rev:        {0}\n".format( "TODO" )
91                 self.fill_dict['Information'] += "//\n"
92                 self.fill_dict['Information'] += "// - Base Layer -\n"
93                 self.fill_dict['Information'] += "// - Default Layer -\n"
94                 self.fill_dict['Information'] += "// - Partial Layers -\n"
95
96
97                 ## Variable Information ##
98                 self.fill_dict['VariableInformation'] = ""
99
100                 # Iterate through the variables, output, and indicate the last file that modified it's value
101                 # Output separate tables per file, per table and overall
102                 # TODO
103
104
105                 ## Defines ##
106                 self.fill_dict['Defines'] = ""
107
108                 # Iterate through defines and lookup the variables
109                 for define in variables.defines.keys():
110                         if define in variables.overallVariables.keys():
111                                 self.fill_dict['Defines'] += "\n#define {0} {1}".format( variables.defines[ define ], variables.overallVariables[ define ] )
112                         else:
113                                 print( "{0} '{1}' not defined...".format( WARNING, define ) )
114
115
116                 ## Capabilities ##
117                 self.fill_dict['CapabilitiesList'] = "const Capability CapabilitiesList[] = {\n"
118
119                 # Keys are pre-sorted
120                 for key in capabilities.keys():
121                         funcName = capabilities.funcName( key )
122                         argByteWidth = capabilities.totalArgBytes( key )
123                         self.fill_dict['CapabilitiesList'] += "\t{{ {0}, {1} }},\n".format( funcName, argByteWidth )
124
125                 self.fill_dict['CapabilitiesList'] += "};"
126
127
128                 ## Results Macros ##
129                 self.fill_dict['ResultMacros'] = ""
130
131                 # Iterate through each of the result macros
132                 for result in range( 0, len( macros.resultsIndexSorted ) ):
133                         self.fill_dict['ResultMacros'] += "Guide_RM( {0} ) = {{ ".format( result )
134
135                         # Add the result macro capability index guide (including capability arguments)
136                         # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
137                         for sequence in range( 0, len( macros.resultsIndexSorted[ result ] ) ):
138                                 # If the sequence is longer than 1, prepend a sequence spacer
139                                 # Needed for USB behaviour, otherwise, repeated keys will not work
140                                 if sequence > 0:
141                                         # <single element>, <usbCodeSend capability>, <USB Code 0x00>
142                                         self.fill_dict['ResultMacros'] += "1, {0}, 0x00, ".format( capabilities.getIndex( self.usbCodeCapability() ) )
143
144                                 # For each combo in the sequence, add the length of the combo
145                                 self.fill_dict['ResultMacros'] += "{0}, ".format( len( macros.resultsIndexSorted[ result ][ sequence ] ) )
146
147                                 # For each combo, add each of the capabilities used and their arguments
148                                 for combo in range( 0, len( macros.resultsIndexSorted[ result ][ sequence ] ) ):
149                                         resultItem = macros.resultsIndexSorted[ result ][ sequence ][ combo ]
150
151                                         # Add the capability index
152                                         self.fill_dict['ResultMacros'] += "{0}, ".format( capabilities.getIndex( resultItem[0] ) )
153
154                                         # Add each of the arguments of the capability
155                                         for arg in range( 0, len( resultItem[1] ) ):
156                                                 self.fill_dict['ResultMacros'] += "0x{0:02X}, ".format( resultItem[1][ arg ] )
157
158                         # If sequence is longer than 1, append a sequence spacer at the end of the sequence
159                         # Required by USB to end at sequence without holding the key down
160                         if len( macros.resultsIndexSorted[ result ] ) > 1:
161                                 # <single element>, <usbCodeSend capability>, <USB Code 0x00>
162                                 self.fill_dict['ResultMacros'] += "1, {0}, 0x00, ".format( capabilities.getIndex( self.usbCodeCapability() ) )
163
164                         # Add list ending 0 and end of list
165                         self.fill_dict['ResultMacros'] += "0 };\n"
166                 self.fill_dict['ResultMacros'] = self.fill_dict['ResultMacros'][:-1] # Remove last newline
167
168
169                 ## Result Macro List ##
170                 self.fill_dict['ResultMacroList'] = "const ResultMacro ResultMacroList[] = {\n"
171
172                 # Iterate through each of the result macros
173                 for result in range( 0, len( macros.resultsIndexSorted ) ):
174                         self.fill_dict['ResultMacroList'] += "\tDefine_RM( {0} ),\n".format( result )
175                 self.fill_dict['ResultMacroList'] += "};"
176
177
178                 ## Result Macro Record ##
179                 self.fill_dict['ResultMacroRecord'] = "ResultMacroRecord ResultMacroRecordList[ ResultMacroNum ];"
180
181
182                 ## Trigger Macros ##
183                 self.fill_dict['TriggerMacros'] = ""
184
185                 # Iterate through each of the trigger macros
186                 for trigger in range( 0, len( macros.triggersIndexSorted ) ):
187                         self.fill_dict['TriggerMacros'] += "Guide_TM( {0} ) = {{ ".format( trigger )
188
189                         # Add the trigger macro scan code guide
190                         # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
191                         for sequence in range( 0, len( macros.triggersIndexSorted[ trigger ][ 0 ] ) ):
192                                 # For each combo in the sequence, add the length of the combo
193                                 self.fill_dict['TriggerMacros'] += "{0}, ".format( len( macros.triggersIndexSorted[ trigger ][0][ sequence ] ) )
194
195                                 # For each combo, add the key type, key state and scan code
196                                 for combo in range( 0, len( macros.triggersIndexSorted[ trigger ][ 0 ][ sequence ] ) ):
197                                         triggerItem = macros.triggersIndexSorted[ trigger ][ 0 ][ sequence ][ combo ]
198
199                                         # TODO Add support for Analog keys
200                                         # TODO Add support for LED states
201                                         self.fill_dict['TriggerMacros'] += "0x00, 0x01, 0x{0:02X}, ".format( triggerItem )
202
203                         # Add list ending 0 and end of list
204                         self.fill_dict['TriggerMacros'] += "0 };\n"
205                 self.fill_dict['TriggerMacros'] = self.fill_dict['TriggerMacros'][ :-1 ] # Remove last newline
206
207
208                 ## Trigger Macro List ##
209                 self.fill_dict['TriggerMacroList'] = "const TriggerMacro TriggerMacroList[] = {\n"
210
211                 # Iterate through each of the trigger macros
212                 for trigger in range( 0, len( macros.triggersIndexSorted ) ):
213                         # Use TriggerMacro Index, and the corresponding ResultMacro Index
214                         self.fill_dict['TriggerMacroList'] += "\tDefine_TM( {0}, {1} ),\n".format( trigger, macros.triggersIndexSorted[ trigger ][1] )
215                 self.fill_dict['TriggerMacroList'] += "};"
216
217
218                 ## Trigger Macro Record ##
219                 self.fill_dict['TriggerMacroRecord'] = "TriggerMacroRecord TriggerMacroRecordList[ TriggerMacroNum ];"
220
221
222                 ## Max Scan Code ##
223                 self.fill_dict['MaxScanCode'] = "#define MaxScanCode 0x{0:X}".format( macros.overallMaxScanCode )
224
225
226                 ## Default Layer and Default Layer Scan Map ##
227                 self.fill_dict['DefaultLayerTriggerList'] = ""
228                 self.fill_dict['DefaultLayerScanMap'] = "const nat_ptr_t *default_scanMap[] = {\n"
229
230                 # Iterate over triggerList and generate a C trigger array for the default map and default map array
231                 for triggerList in range( macros.firstScanCode[ 0 ], len( macros.triggerList[ 0 ] ) ):
232                         # Generate ScanCode index and triggerList length
233                         self.fill_dict['DefaultLayerTriggerList'] += "Define_TL( default, 0x{0:02X} ) = {{ {1}".format( triggerList, len( macros.triggerList[ 0 ][ triggerList ] ) )
234
235                         # Add scanCode trigger list to Default Layer Scan Map
236                         self.fill_dict['DefaultLayerScanMap'] += "default_tl_0x{0:02X}, ".format( triggerList )
237
238                         # Add each item of the trigger list
239                         for trigger in macros.triggerList[ 0 ][ triggerList ]:
240                                 self.fill_dict['DefaultLayerTriggerList'] += ", {0}".format( trigger )
241
242                         self.fill_dict['DefaultLayerTriggerList'] += " };\n"
243                 self.fill_dict['DefaultLayerTriggerList'] = self.fill_dict['DefaultLayerTriggerList'][:-1] # Remove last newline
244                 self.fill_dict['DefaultLayerScanMap'] = self.fill_dict['DefaultLayerScanMap'][:-2] # Remove last comma and space
245                 self.fill_dict['DefaultLayerScanMap'] += "\n};"
246
247
248                 ## Partial Layers and Partial Layer Scan Maps ##
249                 self.fill_dict['PartialLayerTriggerLists'] = ""
250                 self.fill_dict['PartialLayerScanMaps'] = ""
251
252                 # Iterate over each of the layers, excluding the default layer
253                 for layer in range( 1, len( macros.triggerList ) ):
254                         # Prepare each layer
255                         self.fill_dict['PartialLayerScanMaps'] += "// Partial Layer {0}\n".format( layer )
256                         self.fill_dict['PartialLayerScanMaps'] += "const nat_ptr_t *layer{0}_scanMap[] = {{\n".format( layer )
257                         self.fill_dict['PartialLayerTriggerLists'] += "// Partial Layer {0}\n".format( layer )
258
259                         # Iterate over triggerList and generate a C trigger array for the layer
260                         for triggerList in range( macros.firstScanCode[ layer ], len( macros.triggerList[ layer ] ) ):
261                                 # Generate ScanCode index and triggerList length
262                                 self.fill_dict['PartialLayerTriggerLists'] += "Define_TL( layer{0}, 0x{1:02X} ) = {{ {2}".format( layer, triggerList, len( macros.triggerList[ layer ][ triggerList ] ) )
263
264                                 # Add scanCode trigger list to Default Layer Scan Map
265                                 self.fill_dict['PartialLayerScanMaps'] += "layer{0}_tl_0x{1:02X}, ".format( layer, triggerList )
266
267                                 # Add each item of the trigger list
268                                 for trigger in macros.triggerList[ layer ][ triggerList ]:
269                                         self.fill_dict['PartialLayerTriggerLists'] += ", {0}".format( trigger )
270
271                                 self.fill_dict['PartialLayerTriggerLists'] += " };\n"
272                         self.fill_dict['PartialLayerTriggerLists'] += "\n"
273                         self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last comma and space
274                         self.fill_dict['PartialLayerScanMaps'] += "\n};\n\n"
275                 self.fill_dict['PartialLayerTriggerLists'] = self.fill_dict['PartialLayerTriggerLists'][:-2] # Remove last 2 newlines
276                 self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last 2 newlines
277
278
279                 ## Layer Index List ##
280                 self.fill_dict['LayerIndexList'] = "const Layer LayerIndex[] = {\n"
281
282                 # Iterate over each layer, adding it to the list
283                 for layer in range( 0, len( macros.triggerList ) ):
284                         # Lookup first scancode in map
285                         firstScanCode = macros.firstScanCode[ layer ]
286
287                         # Default map is a special case, always the first index
288                         # TODO Fix names
289                         if layer == 0:
290                                 self.fill_dict['LayerIndexList'] += '\tLayer_IN( default_scanMap, "DefaultMap", 0x{0:02X} ),\n'.format( firstScanCode )
291                         else:
292                                 self.fill_dict['LayerIndexList'] += '\tLayer_IN( layer{0}_scanMap, "Layer {0}", 0x{1:02X} ),\n'.format( layer, firstScanCode )
293                 self.fill_dict['LayerIndexList'] += "};"
294
295
296                 ## Layer State ##
297                 self.fill_dict['LayerState'] = "uint8_t LayerState[ LayerNum ];"
298
299
300         # Generates the output keymap with fill tags filled
301         def generate( self, outputPath, definesOutputPath ):
302                 # Process each line of the template, outputting to the target path
303                 with open( outputPath, 'w' ) as outputFile:
304                         with open( self.templatePath, 'r' ) as templateFile:
305                                 for line in templateFile:
306                                         # TODO Support multiple replacements per line
307                                         # TODO Support replacement with other text inline
308                                         match = re.findall( '<\|([^|>]+)\|>', line )
309
310                                         # If match, replace with processed variable
311                                         if match:
312                                                 outputFile.write( self.fill_dict[ match[ 0 ] ] )
313                                                 outputFile.write("\n")
314
315                                         # Otherwise, just append template to output file
316                                         else:
317                                                 outputFile.write( line )
318
319                 # Process each line of the defines template, outputting to the target path
320                 with open( definesOutputPath, 'w' ) as outputFile:
321                         with open( self.definesTemplatePath, 'r' ) as templateFile:
322                                 for line in templateFile:
323                                         # TODO Support multiple replacements per line
324                                         # TODO Support replacement with other text inline
325                                         match = re.findall( '<\|([^|>]+)\|>', line )
326
327                                         # If match, replace with processed variable
328                                         if match:
329                                                 outputFile.write( self.fill_dict[ match[ 0 ] ] )
330                                                 outputFile.write("\n")
331
332                                         # Otherwise, just append template to output file
333                                         else:
334                                                 outputFile.write( line )
335