]> git.donarmstrong.com Git - kiibohd-kll.git/blob - backends/kiibohd.py
e25c64c8b2058398fd093d1c1fd7b8912f1acd55
[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
38
39
40 ### Classes ###
41
42 class Backend:
43         # Initializes backend
44         # Looks for template file and builds list of fill tags
45         def __init__( self, templatePath ):
46                 # Does template exist?
47                 if not os.path.isfile( templatePath ):
48                         print ( "{0} '{1}' does not exist...".format( ERROR, templatePath ) )
49                         sys.exit( 1 )
50
51                 self.templatePath = templatePath
52                 self.fill_dict = dict()
53
54                 # Generate list of fill tags
55                 self.tagList = []
56                 with open( templatePath, 'r' ) as openFile:
57                         for line in openFile:
58                                 match = re.findall( '<\|([^|>]+)\|>', line )
59                                 for item in match:
60                                         self.tagList.append( item )
61
62
63         # USB Code Capability Name
64         def usbCodeCapability( self ):
65                 return "usbKeyOut";
66
67
68         # Processes content for fill tags and does any needed dataset calculations
69         def process( self, capabilities, macros ):
70                 ## Capabilities ##
71                 self.fill_dict['CapabilitiesList'] = "const Capability CapabilitiesList[] = {\n"
72
73                 # Keys are pre-sorted
74                 for key in capabilities.keys():
75                         funcName = capabilities.funcName( key )
76                         argByteWidth = capabilities.totalArgBytes( key )
77                         self.fill_dict['CapabilitiesList'] += "\t{{ {0}, {1} }},\n".format( funcName, argByteWidth )
78
79                 self.fill_dict['CapabilitiesList'] += "};"
80
81
82                 ## Results Macros ##
83                 self.fill_dict['ResultMacros'] = ""
84
85                 # Iterate through each of the result macros
86                 for result in range( 0, len( macros.resultsIndexSorted ) ):
87                         self.fill_dict['ResultMacros'] += "Guide_RM( {0} ) = {{ ".format( result )
88
89                         # Add the result macro capability index guide (including capability arguments)
90                         # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
91                         for sequence in range( 0, len( macros.resultsIndexSorted[ result ] ) ):
92                                 # For each combo in the sequence, add the length of the combo
93                                 self.fill_dict['ResultMacros'] += "{0}, ".format( len( macros.resultsIndexSorted[ result ][ sequence ] ) )
94
95                                 # For each combo, add each of the capabilities used and their arguments
96                                 for combo in range( 0, len( macros.resultsIndexSorted[ result ][ sequence ] ) ):
97                                         resultItem = macros.resultsIndexSorted[ result ][ sequence ][ combo ]
98
99                                         # Add the capability index
100                                         self.fill_dict['ResultMacros'] += "{0}, ".format( capabilities.getIndex( resultItem[0] ) )
101
102                                         # Add each of the arguments of the capability
103                                         for arg in range( 0, len( resultItem[1] ) ):
104                                                 self.fill_dict['ResultMacros'] += "0x{0:02X}, ".format( resultItem[1][ arg ] )
105
106                         # Add list ending 0 and end of list
107                         self.fill_dict['ResultMacros'] += "0 };\n"
108                 self.fill_dict['ResultMacros'] = self.fill_dict['ResultMacros'][:-1] # Remove last newline
109
110
111                 ## Result Macro List ##
112                 self.fill_dict['ResultMacroList'] = "ResultMacro ResultMacroList[] = {\n"
113
114                 # Iterate through each of the result macros
115                 for result in range( 0, len( macros.resultsIndexSorted ) ):
116                         self.fill_dict['ResultMacroList'] += "\tDefine_RM( {0} ),\n".format( result )
117                 self.fill_dict['ResultMacroList'] += "};"
118
119
120                 ## Trigger Macros ##
121                 self.fill_dict['TriggerMacros'] = ""
122
123                 # Iterate through each of the trigger macros
124                 for trigger in range( 0, len( macros.triggersIndexSorted ) ):
125                         self.fill_dict['TriggerMacros'] += "Guide_TM( {0} ) = {{ ".format( trigger )
126
127                         # Add the trigger macro scan code guide
128                         # See kiibohd controller Macros/PartialMap/kll.h for exact formatting details
129                         for sequence in range( 0, len( macros.triggersIndexSorted[ trigger ][ 0 ] ) ):
130                                 # For each combo in the sequence, add the length of the combo
131                                 self.fill_dict['TriggerMacros'] += "{0}, ".format( len( macros.triggersIndexSorted[ trigger ][0][ sequence ] ) )
132
133                                 # For each combo, add the key type, key state and scan code
134                                 for combo in range( 0, len( macros.triggersIndexSorted[ trigger ][ 0 ][ sequence ] ) ):
135                                         triggerItem = macros.triggersIndexSorted[ trigger ][ 0 ][ sequence ][ combo ]
136
137                                         # TODO Add support for Analog keys
138                                         # TODO Add support for LED states
139                                         self.fill_dict['TriggerMacros'] += "0x00, 0x01, 0x{0:02X}, ".format( triggerItem )
140
141                         # Add list ending 0 and end of list
142                         self.fill_dict['TriggerMacros'] += "0 };\n"
143                 self.fill_dict['TriggerMacros'] = self.fill_dict['TriggerMacros'][ :-1 ] # Remove last newline
144
145
146                 ## Trigger Macro List ##
147                 self.fill_dict['TriggerMacroList'] = "TriggerMacro TriggerMacroList[] = {\n"
148
149                 # Iterate through each of the trigger macros
150                 for trigger in range( 0, len( macros.triggersIndexSorted ) ):
151                         # Use TriggerMacro Index, and the corresponding ResultMacro Index
152                         self.fill_dict['TriggerMacroList'] += "\tDefine_TM( {0}, {1} ),\n".format( trigger, macros.triggersIndexSorted[ trigger ][1] )
153                 self.fill_dict['TriggerMacroList'] += "};"
154
155
156                 ## Max Scan Code ##
157                 self.fill_dict['MaxScanCode'] = "#define MaxScanCode 0x{0:X}".format( macros.overallMaxScanCode )
158
159
160                 ## Default Layer and Default Layer Scan Map ##
161                 self.fill_dict['DefaultLayerTriggerList'] = ""
162                 self.fill_dict['DefaultLayerScanMap'] = "const unsigned int *default_scanMap[] = {\n"
163
164                 # Iterate over triggerList and generate a C trigger array for the default map and default map array
165                 for triggerList in range( 0, len( macros.triggerList[ 0 ] ) ):
166                         # Generate ScanCode index and triggerList length
167                         self.fill_dict['DefaultLayerTriggerList'] += "Define_TL( default, 0x{0:02X} ) = {{ {1}".format( triggerList, len( macros.triggerList[ 0 ][ triggerList ] ) )
168
169                         # Add scanCode trigger list to Default Layer Scan Map
170                         self.fill_dict['DefaultLayerScanMap'] += "default_tl_0x{0:02X}, ".format( triggerList )
171
172                         # Add each item of the trigger list
173                         for trigger in macros.triggerList[ 0 ][ triggerList ]:
174                                 self.fill_dict['DefaultLayerTriggerList'] += ", {0}".format( trigger )
175
176                         self.fill_dict['DefaultLayerTriggerList'] += " };\n"
177                 self.fill_dict['DefaultLayerTriggerList'] = self.fill_dict['DefaultLayerTriggerList'][:-1] # Remove last newline
178                 self.fill_dict['DefaultLayerScanMap'] = self.fill_dict['DefaultLayerScanMap'][:-2] # Remove last comma and space
179                 self.fill_dict['DefaultLayerScanMap'] += "\n};"
180
181
182                 ## Partial Layers and Partial Layer Scan Maps ##
183                 self.fill_dict['PartialLayerTriggerLists'] = ""
184                 self.fill_dict['PartialLayerScanMaps'] = ""
185
186                 # Iterate over each of the layers, excluding the default layer
187                 for layer in range( 1, len( macros.triggerList ) ):
188                         # Prepare each layer
189                         self.fill_dict['PartialLayerScanMaps'] += "// Partial Layer {0}\n".format( layer )
190                         self.fill_dict['PartialLayerScanMaps'] += "const unsigned int *layer{0}_scanMap[] = {{\n".format( layer )
191                         self.fill_dict['PartialLayerTriggerLists'] += "// Partial Layer {0}\n".format( layer )
192
193                         # Iterate over triggerList and generate a C trigger array for the layer
194                         for triggerList in range( 0, len( macros.triggerList[ layer ] ) ):
195                                 # Generate ScanCode index and triggerList length
196                                 self.fill_dict['PartialLayerTriggerLists'] += "Define_TL( layer{0}, 0x{1:02X} ) = {{ {2}".format( layer, triggerList, len( macros.triggerList[ 0 ][ triggerList ] ) )
197
198                                 # Add scanCode trigger list to Default Layer Scan Map
199                                 self.fill_dict['PartialLayerScanMaps'] += "layer{0}_tl_0x{1:02X}, ".format( layer, triggerList )
200
201                                 # Add each item of the trigger list
202                                 for trigger in macros.triggerList[ 0 ][ triggerList ]:
203                                         self.fill_dict['PartialLayerTriggerLists'] += ", {0}".format( trigger )
204
205                                 self.fill_dict['PartialLayerTriggerLists'] += " };\n"
206                         self.fill_dict['PartialLayerTriggerLists'] += "\n"
207                         self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last comma and space
208                         self.fill_dict['PartialLayerScanMaps'] += "\n};\n\n"
209                 self.fill_dict['PartialLayerTriggerLists'] = self.fill_dict['PartialLayerTriggerLists'][:-2] # Remove last 2 newlines
210                 self.fill_dict['PartialLayerScanMaps'] = self.fill_dict['PartialLayerScanMaps'][:-2] # Remove last 2 newlines
211
212
213                 ## Layer Index List ##
214                 self.fill_dict['LayerIndexList'] = "Layer LayerIndex[] = {\n"
215
216                 # Iterate over each layer, adding it to the list
217                 for layer in range( 0, len( macros.triggerList ) ):
218                         # Default map is a special case, always the first index
219                         # TODO Fix names
220                         if layer == 0:
221                                 self.fill_dict['LayerIndexList'] += '\tLayer_IN( default_scanMap, "DefaultMap" ),\n'
222                         else:
223                                 self.fill_dict['LayerIndexList'] += '\tLayer_IN( layer{0}_scanMap, "Layer {0}" ),\n'.format( layer )
224                 self.fill_dict['LayerIndexList'] += "};"
225
226
227         # Generates the output keymap with fill tags filled
228         def generate( self, filepath ):
229                 # Process each line of the template, outputting to the target path
230                 with open( filepath, 'w' ) as outputFile:
231                         with open( self.templatePath, 'r' ) as templateFile:
232                                 for line in templateFile:
233                                         # TODO Support multiple replacements per line
234                                         # TODO Support replacement with other text inline
235                                         match = re.findall( '<\|([^|>]+)\|>', line )
236
237                                         # If match, replace with processed variable
238                                         if match:
239                                                 outputFile.write( self.fill_dict[ match[ 0 ] ] )
240                                                 outputFile.write("\n")
241
242                                         # Otherwise, just append template to output file
243                                         else:
244                                                 outputFile.write( line )
245