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