3 # Keyboard Layout Langauge
5 # Copyright (C) 2014 by Jacob Alexander
7 # This file is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This file is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this file. If not, see <http://www.gnu.org/licenses/>.
30 from tokenize import generate_tokens
31 from re import VERBOSE
32 from pprint import pformat
34 from kll_lib.hid_dict import *
35 from kll_lib.containers import *
37 from funcparserlib.lexer import make_tokenizer, Token, LexerError
38 from funcparserlib.parser import (some, a, many, oneplus, skip, finished, maybe, skip, forward_decl, NoParseError)
44 ## Print Decorator Variables
45 ERROR = '\033[5;1;31mERROR\033[0m:'
48 ## Python Text Formatting Fixer...
49 ## Because the creators of Python are averse to proper capitalization.
50 textFormatter_lookup = {
51 "usage: " : "Usage: ",
52 "optional arguments" : "Optional Arguments",
55 def textFormatter_gettext( s ):
56 return textFormatter_lookup.get( s, s )
58 argparse._ = textFormatter_gettext
62 ### Argument Parsing ###
64 def processCommandLineArgs():
65 # Setup argument processor
66 pArgs = argparse.ArgumentParser(
67 usage="%(prog)s [options] <file1>...",
68 description="Generates .h file state tables and pointer indices from KLL .kll files.",
69 epilog="Example: {0} TODO".format( os.path.basename( sys.argv[0] ) ),
70 formatter_class=argparse.RawTextHelpFormatter,
74 # Positional Arguments
75 pArgs.add_argument( 'files', type=str, nargs='+',
76 help=argparse.SUPPRESS ) # Suppressed help output, because Python output is verbosely ugly
79 pArgs.add_argument( '-b', '--backend', type=str, default="kiibohd",
80 help="Specify target backend for the KLL compiler.\n"
82 pArgs.add_argument( '-p', '--partial', type=str, nargs='+', action='append',
83 help="Specify .kll files to generate partial map, multiple files per flag.\n"
84 "Each -p defines another partial map.\n"
85 "Base .kll files (that define the scan code maps) must be defined for each partial map." )
86 pArgs.add_argument( '-t', '--template', type=str, default="templateKeymap.h",
87 help="Specify template used to generate the keymap.\n"
88 "Default: templateKeymap.h" )
89 pArgs.add_argument( '-o', '--output', type=str, default="templateKeymap.h",
90 help="Specify output file. Writes to current working directory by default.\n"
91 "Default: generatedKeymap.h" )
92 pArgs.add_argument( '-h', '--help', action="help",
93 help="This message." )
96 args = pArgs.parse_args()
99 defaultFiles = args.files
100 partialFileSets = args.partial
101 if partialFileSets is None:
102 partialFileSets = [[]]
104 # Check file existance
105 for filename in defaultFiles:
106 if not os.path.isfile( filename ):
107 print ( "{0} {1} does not exist...".format( ERROR, filename ) )
110 for partial in partialFileSets:
111 for filename in partial:
112 if not os.path.isfile( filename ):
113 print ( "{0} {1} does not exist...".format( ERROR, filename ) )
116 return (defaultFiles, partialFileSets, args.backend, args.template, args.output)
122 def tokenize( string ):
123 """str -> Sequence(Token)"""
127 ( 'Comment', ( r' *#.*', ) ),
128 ( 'Space', ( r'[ \t\r\n]+', ) ),
129 ( 'USBCode', ( r'U(("[^"]+")|(0x[0-9a-fA-F]+)|([0-9]+))', ) ),
130 ( 'USBCodeStart', ( r'U\[', ) ),
131 ( 'ScanCode', ( r'S((0x[0-9a-fA-F]+)|([0-9]+))', ) ),
132 ( 'ScanCodeStart', ( r'S\[', ) ),
133 ( 'CodeEnd', ( r'\]', ) ),
134 ( 'String', ( r'"[^"]*"', VERBOSE ) ),
135 ( 'SequenceString', ( r"'[^']*'", ) ),
136 ( 'Comma', ( r',', ) ),
137 ( 'Dash', ( r'-', ) ),
138 ( 'Plus', ( r'\+', ) ),
139 ( 'Operator', ( r'=>|:|=', ) ),
140 ( 'Parenthesis', ( r'\(|\)', ) ),
141 ( 'Number', ( r'-?(0x[0-9a-fA-F]+)|(0|([1-9][0-9]*))', VERBOSE ) ),
142 ( 'Name', ( r'[A-Za-z_][A-Za-z_0-9]*', ) ),
143 ( 'VariableContents', ( r'''[^"' ;:=>()]+''', ) ),
144 ( 'EndOfLine', ( r';', ) ),
147 # Tokens to filter out of the token stream
148 useless = ['Space', 'Comment']
150 tokens = make_tokenizer( specs )
151 return [x for x in tokens( string ) if x.type not in useless]
158 scanCode_map = [ None ] * 0xFF # Define 8 bit address width
159 usbCode_map = [ None ] * 0xFF # Define 8 bit address width
160 variable_dict = dict()
161 capabilities_dict = Capabilities()
166 def make_scanCode( token ):
167 scanCode = int( token[1:], 0 )
168 # Check size, to make sure it's valid
170 print ( "{0} ScanCode value {1} is larger than 255".format( ERROR, scanCode ) )
174 def make_usbCode( token ):
175 # If first character is a U, strip
179 # If using string representation of USB Code, do lookup, case-insensitive
182 usbCode = kll_hid_lookup_dictionary[ token[1:-1].upper() ]
183 except LookupError as err:
184 print ( "{0} {1} is an invalid USB Code Lookup...".format( ERROR, err ) )
187 usbCode = int( token, 0 )
189 # Check size, to make sure it's valid
191 print ( "{0} USBCode value {1} is larger than 255".format( ERROR, usbCode ) )
195 def make_seqString( token ):
196 # Shifted Characters, and amount to move by to get non-shifted version
199 ( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0x20 ),
216 shiftKey = kll_hid_lookup_dictionary["SHIFT"]
218 # Creates a list of USB codes from the string: sequence (list) of combos (lists)
219 for char in token[1:-1]:
222 # Whether or not to create a combo for this sequence with a shift
225 # Depending on the ASCII character, convert to single character or Shift + character
226 for pair in shiftCharacters:
229 processedChar = chr( ord( char ) + pair[1] )
232 # Do KLL HID Lookup on non-shifted character
233 # NOTE: Case-insensitive, which is why the shift must be pre-computed
234 usbCode = kll_hid_lookup_dictionary[ processedChar.upper() ]
236 # Create Combo for this character, add shift key if shifted
239 charCombo = [ [ shiftKey ] ]
240 charCombo.append( [ usbCode ] )
242 # Add to list of lists
243 listOfLists.append( charCombo )
247 def make_string( token ):
250 def make_number( token ):
251 return int( token, 0 )
253 # Range can go from high to low or low to high
254 def make_scanCode_range( rangeVals ):
258 # Swap start, end if start is greater than end
260 start, end = end, start
262 # Iterate from start to end, and generate the range
263 return list( range( start, end + 1 ) )
265 # Range can go from high to low or low to high
266 # Warn on 0-9 (as this does not do what one would expect) TODO
267 # Lookup USB HID tags and convert to a number
268 def make_usbCode_range( rangeVals ):
269 # Check if already integers
270 if isinstance( rangeVals[0], int ):
273 start = make_usbCode( rangeVals[0] )
275 if isinstance( rangeVals[1], int ):
278 end = make_usbCode( rangeVals[1] )
280 # Swap start, end if start is greater than end
282 start, end = end, start
284 # Iterate from start to end, and generate the range
285 return list( range( start, end + 1 ) )
291 const = lambda x: lambda _: x
292 unarg = lambda f: lambda x: f(*x)
293 flatten = lambda list: sum( list, [] )
295 tokenValue = lambda x: x.value
296 tokenType = lambda t: some( lambda x: x.type == t ) >> tokenValue
297 operator = lambda s: a( Token( 'Operator', s ) ) >> tokenValue
298 parenthesis = lambda s: a( Token( 'Parenthesis', s ) ) >> tokenValue
299 eol = a( Token( 'EndOfLine', ';' ) )
301 def listElem( item ):
304 # Flatten only the top layer (list of lists of ...)
305 def oneLayerFlatten( items ):
307 for sublist in items:
309 mainList.append( item )
313 # Expand ranges of values in the 3rd dimension of the list, to a list of 2nd lists
314 # i.e. [ sequence, [ combo, [ range ] ] ] --> [ [ sequence, [ combo ] ], <option 2>, <option 3> ]
315 def optionExpansion( sequences ):
316 expandedSequences = []
318 # Total number of combinations of the sequence of combos that needs to be generated
319 totalCombinations = 1
321 # List of leaf lists, with number of leaves
324 # Traverse to the leaf nodes, and count the items in each leaf list
325 for sequence in sequences:
326 for combo in sequence:
327 rangeLen = len( combo )
328 totalCombinations *= rangeLen
329 maxLeafList.append( rangeLen )
331 # Counter list to keep track of which combination is being generated
332 curLeafList = [0] * len( maxLeafList )
334 # Generate a list of permuations of the sequence of combos
335 for count in range( 0, totalCombinations ):
336 expandedSequences.append( [] ) # Prepare list for adding the new combination
339 # Traverse sequence of combos to generate permuation
340 for sequence in sequences:
341 expandedSequences[ -1 ].append( [] )
342 for combo in sequence:
343 expandedSequences[ -1 ][ -1 ].append( combo[ curLeafList[ position ] ] )
346 # Increment combination tracker
347 for leaf in range( 0, len( curLeafList ) ):
348 curLeafList[ leaf ] += 1
350 # Reset this position, increment next position (if it exists), then stop
351 if curLeafList[ leaf ] >= maxLeafList[ leaf ]:
352 curLeafList[ leaf ] = 0
353 if leaf + 1 < len( curLeafList ):
354 curLeafList[ leaf + 1 ] += 1
357 return expandedSequences
362 def eval_scanCode( trigger, result ):
363 # Convert to lists of lists of lists to tuples of tuples of tuples
364 trigger = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in trigger )
365 result = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in result )
367 # Add to the base scanCode map, overwrite if already defined
368 # if scanCode_map[ trigger ] != None:
369 # print ( "ScanCodeMap - Replacing '{0}' with '{1}' -> {2}".format( scanCode_map[ trigger ], result, trigger ) )
370 # scanCode_map[ trigger ] = result
372 def eval_usbCode( trigger, result ):
373 # Check if trigger is list
375 # Add to the base usbCode map, overwrite if already defined
376 if usbCode_map[ trigger ] != None:
377 print ( "USBCodeMap - Replacing '{0}' with '{1}' -> {2}".format( usbCode_map[ trigger ], result, trigger ) )
378 usbCode_map[ trigger ] = result
381 def eval_variable( name, content ):
382 # Content might be a concatenation of multiple data types, convert everything into a single string
383 assigned_content = ""
385 assigned_content += str( item )
387 variable_dict[ name ] = assigned_content
389 def eval_capability( name, function, args ):
390 capabilities_dict[ name ] = [ function, args ]
392 map_scanCode = unarg( eval_scanCode )
393 map_usbCode = unarg( eval_usbCode )
395 set_variable = unarg( eval_variable )
396 set_capability = unarg( eval_capability )
401 usbCode = tokenType('USBCode') >> make_usbCode
402 scanCode = tokenType('ScanCode') >> make_scanCode
403 name = tokenType('Name')
404 number = tokenType('Number') >> make_number
405 comma = tokenType('Comma')
406 dash = tokenType('Dash')
407 plus = tokenType('Plus')
408 content = tokenType('VariableContents')
409 string = tokenType('String') >> make_string
410 unString = tokenType('String') # When the double quotes are still needed for internal processing
411 seqString = tokenType('SequenceString') >> make_seqString
414 code_end = tokenType('CodeEnd')
417 scanCode_start = tokenType('ScanCodeStart')
418 scanCode_range = number + skip( dash ) + number >> make_scanCode_range
419 scanCode_listElem = number >> listElem
420 scanCode_innerList = oneplus( ( scanCode_range | scanCode_listElem ) + skip( maybe( comma ) ) ) >> flatten
421 scanCode_expanded = skip( scanCode_start ) + scanCode_innerList + skip( code_end )
422 scanCode_elem = scanCode >> listElem
423 scanCode_combo = oneplus( ( scanCode_expanded | scanCode_elem ) + skip( maybe( plus ) ) )
424 scanCode_sequence = oneplus( scanCode_combo + skip( maybe( comma ) ) )
427 usbCode_start = tokenType('USBCodeStart')
428 usbCode_range = ( number | unString ) + skip( dash ) + ( number | unString ) >> make_usbCode_range
429 usbCode_listElemTag = unString >> make_usbCode
430 usbCode_listElem = ( number | usbCode_listElemTag ) >> listElem
431 usbCode_innerList = oneplus( ( usbCode_range | usbCode_listElem ) + skip( maybe( comma ) ) ) >> flatten
432 usbCode_expanded = skip( usbCode_start ) + usbCode_innerList + skip( code_end )
433 usbCode_elem = usbCode >> listElem
434 usbCode_combo = oneplus( ( usbCode_expanded | usbCode_elem ) + skip( maybe( plus ) ) ) >> listElem
435 usbCode_sequence = oneplus( ( usbCode_combo | seqString ) + skip( maybe( comma ) ) ) >> oneLayerFlatten
438 capFunc_arguments = number + skip( maybe( comma ) )
439 capFunc_elem = name + skip( parenthesis('(') ) + many( capFunc_arguments ) + skip( parenthesis(')') ) >> listElem
440 capFunc_combo = oneplus( ( usbCode_expanded | usbCode_elem | capFunc_elem ) + skip( maybe( plus ) ) ) >> listElem
441 capFunc_sequence = oneplus( ( capFunc_combo | seqString ) + skip( maybe( comma ) ) ) >> oneLayerFlatten
443 # Trigger / Result Codes
444 triggerCode_outerList = scanCode_sequence >> optionExpansion
445 triggerUSBCode_outerList = usbCode_sequence >> optionExpansion
446 resultCode_outerList = capFunc_sequence >> optionExpansion
451 #| <variable> = <variable contents>;
452 variable_contents = name | content | string | number | comma | dash
453 variable_expression = name + skip( operator('=') ) + oneplus( variable_contents ) + skip( eol ) >> set_variable
455 #| <capability name> => <c function>;
456 capability_arguments = name + skip( operator(':') ) + number + skip( maybe( comma ) )
457 capability_expression = name + skip( operator('=>') ) + name + skip( parenthesis('(') ) + many( capability_arguments ) + skip( parenthesis(')') ) + skip( eol ) >> set_capability
459 #| <trigger> : <result>;
460 scanCode_expression = triggerCode_outerList + skip( operator(':') ) + resultCode_outerList + skip( eol ) >> map_scanCode
461 usbCode_expression = triggerUSBCode_outerList + skip( operator(':') ) + resultCode_outerList + skip( eol ) #>> map_usbCode
463 def parse( tokenSequence ):
464 """Sequence(Token) -> object"""
467 expression = scanCode_expression | usbCode_expression | variable_expression | capability_expression
469 kll_text = many( expression )
470 kll_file = maybe( kll_text ) + skip( finished )
472 return kll_file.parse( tokenSequence )
476 ### Main Entry Point ###
478 if __name__ == '__main__':
479 (defaultFiles, partialFileSets, backend_name, template, output) = processCommandLineArgs()
481 # Load backend module
483 backend_import = importlib.import_module( "backends.{0}".format( backend_name ) )
484 backend = backend_import.Backend( template )
487 for filename in defaultFiles:
488 with open( filename ) as file:
491 tokenSequence = tokenize( data )
492 print ( pformat( tokenSequence ) )
493 tree = parse( tokenSequence )
495 #print ( scanCode_map )
496 #print ( usbCode_map )
497 print ( variable_dict )
498 print ( capabilities_dict )
501 backend.process( capabilities_dict )
503 # Successful Execution