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="templates/kiibohdKeymap.h",
87 help="Specify template used to generate the keymap.\n"
88 "Default: templates/kiibohdKeymap.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 ( 'Operator', ( r'=>|:\+|:-|:|=', ) ),
137 ( 'Comma', ( r',', ) ),
138 ( 'Dash', ( r'-', ) ),
139 ( 'Plus', ( 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 macros_map = Macros()
159 variable_dict = dict()
160 capabilities_dict = Capabilities()
165 def make_scanCode( token ):
166 scanCode = int( token[1:], 0 )
167 # Check size, to make sure it's valid
169 print ( "{0} ScanCode value {1} is larger than 255".format( ERROR, scanCode ) )
173 def make_usbCode( token ):
174 # If first character is a U, strip
178 # If using string representation of USB Code, do lookup, case-insensitive
181 usbCode = kll_hid_lookup_dictionary[ token[1:-1].upper() ]
182 except LookupError as err:
183 print ( "{0} {1} is an invalid USB Code Lookup...".format( ERROR, err ) )
186 usbCode = int( token, 0 )
188 # Check size, to make sure it's valid
190 print ( "{0} USBCode value {1} is larger than 255".format( ERROR, usbCode ) )
194 def make_seqString( token ):
195 # Shifted Characters, and amount to move by to get non-shifted version
198 ( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0x20 ),
215 shiftKey = kll_hid_lookup_dictionary["SHIFT"]
217 # Creates a list of USB codes from the string: sequence (list) of combos (lists)
218 for char in token[1:-1]:
221 # Whether or not to create a combo for this sequence with a shift
224 # Depending on the ASCII character, convert to single character or Shift + character
225 for pair in shiftCharacters:
228 processedChar = chr( ord( char ) + pair[1] )
231 # Do KLL HID Lookup on non-shifted character
232 # NOTE: Case-insensitive, which is why the shift must be pre-computed
233 usbCode = kll_hid_lookup_dictionary[ processedChar.upper() ]
235 # Create Combo for this character, add shift key if shifted
238 charCombo = [ [ shiftKey ] ]
239 charCombo.append( [ usbCode ] )
241 # Add to list of lists
242 listOfLists.append( charCombo )
246 def make_string( token ):
249 def make_number( token ):
250 return int( token, 0 )
252 # Range can go from high to low or low to high
253 def make_scanCode_range( rangeVals ):
257 # Swap start, end if start is greater than end
259 start, end = end, start
261 # Iterate from start to end, and generate the range
262 return list( range( start, end + 1 ) )
264 # Range can go from high to low or low to high
265 # Warn on 0-9 (as this does not do what one would expect) TODO
266 # Lookup USB HID tags and convert to a number
267 def make_usbCode_range( rangeVals ):
268 # Check if already integers
269 if isinstance( rangeVals[0], int ):
272 start = make_usbCode( rangeVals[0] )
274 if isinstance( rangeVals[1], int ):
277 end = make_usbCode( rangeVals[1] )
279 # Swap start, end if start is greater than end
281 start, end = end, start
283 # Iterate from start to end, and generate the range
284 return list( range( start, end + 1 ) )
290 const = lambda x: lambda _: x
291 unarg = lambda f: lambda x: f(*x)
292 flatten = lambda list: sum( list, [] )
294 tokenValue = lambda x: x.value
295 tokenType = lambda t: some( lambda x: x.type == t ) >> tokenValue
296 operator = lambda s: a( Token( 'Operator', s ) ) >> tokenValue
297 parenthesis = lambda s: a( Token( 'Parenthesis', s ) ) >> tokenValue
298 eol = a( Token( 'EndOfLine', ';' ) )
300 def listElem( item ):
303 def listToTuple( items ):
304 return tuple( items )
306 # Flatten only the top layer (list of lists of ...)
307 def oneLayerFlatten( items ):
309 for sublist in items:
311 mainList.append( item )
315 # Expand ranges of values in the 3rd dimension of the list, to a list of 2nd lists
316 # i.e. [ sequence, [ combo, [ range ] ] ] --> [ [ sequence, [ combo ] ], <option 2>, <option 3> ]
317 def optionExpansion( sequences ):
318 expandedSequences = []
320 # Total number of combinations of the sequence of combos that needs to be generated
321 totalCombinations = 1
323 # List of leaf lists, with number of leaves
326 # Traverse to the leaf nodes, and count the items in each leaf list
327 for sequence in sequences:
328 for combo in sequence:
329 rangeLen = len( combo )
330 totalCombinations *= rangeLen
331 maxLeafList.append( rangeLen )
333 # Counter list to keep track of which combination is being generated
334 curLeafList = [0] * len( maxLeafList )
336 # Generate a list of permuations of the sequence of combos
337 for count in range( 0, totalCombinations ):
338 expandedSequences.append( [] ) # Prepare list for adding the new combination
341 # Traverse sequence of combos to generate permuation
342 for sequence in sequences:
343 expandedSequences[ -1 ].append( [] )
344 for combo in sequence:
345 expandedSequences[ -1 ][ -1 ].append( combo[ curLeafList[ position ] ] )
348 # Increment combination tracker
349 for leaf in range( 0, len( curLeafList ) ):
350 curLeafList[ leaf ] += 1
352 # Reset this position, increment next position (if it exists), then stop
353 if curLeafList[ leaf ] >= maxLeafList[ leaf ]:
354 curLeafList[ leaf ] = 0
355 if leaf + 1 < len( curLeafList ):
356 curLeafList[ leaf + 1 ] += 1
359 return expandedSequences
362 # Converts USB Codes into Capabilities
363 def usbCodeToCapability( items ):
364 # Items already converted to variants using optionExpansion
365 for variant in range( 0, len( items ) ):
367 for sequence in range( 0, len( items[ variant ] ) ):
368 for combo in range( 0, len( items[ variant ][ sequence ] ) ):
369 # Only convert if an integer, otherwise USB Code doesn't need converting
370 if isinstance( items[ variant ][ sequence ][ combo ], int ):
371 # Use backend capability name and a single argument
372 items[ variant ][ sequence ][ combo ] = tuple( [ backend.usbCodeCapability(), tuple( [ items[ variant ][ sequence ][ combo ] ] ) ] )
379 def eval_scanCode( triggers, operator, results ):
380 # Convert to lists of lists of lists to tuples of tuples of tuples
381 # Tuples are non-mutable, and can be used has index items
382 triggers = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in triggers )
383 results = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in results )
385 # Iterate over all combinations of triggers and results
386 for trigger in triggers:
387 for result in results:
390 macros_map.appendScanCode( trigger, result )
393 elif operator == ":-":
394 macros_map.removeScanCode( trigger, result )
397 elif operator == ":":
398 macros_map.replaceScanCode( trigger, result )
400 def eval_usbCode( triggers, operator, results ):
401 # Convert to lists of lists of lists to tuples of tuples of tuples
402 # Tuples are non-mutable, and can be used has index items
403 triggers = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in triggers )
404 results = tuple( tuple( tuple( sequence ) for sequence in variant ) for variant in results )
406 # Iterate over all combinations of triggers and results
407 for trigger in triggers:
408 scanCodes = macros_map.lookupUSBCodes( trigger )
409 for scanCode in scanCodes:
410 for result in results:
411 # Cache assignment until file finishes processing
412 macros_map.cacheAssignment( operator, scanCode, result )
414 def eval_variable( name, content ):
415 # Content might be a concatenation of multiple data types, convert everything into a single string
416 assigned_content = ""
418 assigned_content += str( item )
420 variable_dict[ name ] = assigned_content
422 def eval_capability( name, function, args ):
423 capabilities_dict[ name ] = [ function, args ]
425 map_scanCode = unarg( eval_scanCode )
426 map_usbCode = unarg( eval_usbCode )
428 set_variable = unarg( eval_variable )
429 set_capability = unarg( eval_capability )
434 usbCode = tokenType('USBCode') >> make_usbCode
435 scanCode = tokenType('ScanCode') >> make_scanCode
436 name = tokenType('Name')
437 number = tokenType('Number') >> make_number
438 comma = tokenType('Comma')
439 dash = tokenType('Dash')
440 plus = tokenType('Plus')
441 content = tokenType('VariableContents')
442 string = tokenType('String') >> make_string
443 unString = tokenType('String') # When the double quotes are still needed for internal processing
444 seqString = tokenType('SequenceString') >> make_seqString
447 code_end = tokenType('CodeEnd')
450 scanCode_start = tokenType('ScanCodeStart')
451 scanCode_range = number + skip( dash ) + number >> make_scanCode_range
452 scanCode_listElem = number >> listElem
453 scanCode_innerList = oneplus( ( scanCode_range | scanCode_listElem ) + skip( maybe( comma ) ) ) >> flatten
454 scanCode_expanded = skip( scanCode_start ) + scanCode_innerList + skip( code_end )
455 scanCode_elem = scanCode >> listElem
456 scanCode_combo = oneplus( ( scanCode_expanded | scanCode_elem ) + skip( maybe( plus ) ) )
457 scanCode_sequence = oneplus( scanCode_combo + skip( maybe( comma ) ) )
460 usbCode_start = tokenType('USBCodeStart')
461 usbCode_range = ( number | unString ) + skip( dash ) + ( number | unString ) >> make_usbCode_range
462 usbCode_listElemTag = unString >> make_usbCode
463 usbCode_listElem = ( number | usbCode_listElemTag ) >> listElem
464 usbCode_innerList = oneplus( ( usbCode_range | usbCode_listElem ) + skip( maybe( comma ) ) ) >> flatten
465 usbCode_expanded = skip( usbCode_start ) + usbCode_innerList + skip( code_end )
466 usbCode_elem = usbCode >> listElem
467 usbCode_combo = oneplus( ( usbCode_expanded | usbCode_elem ) + skip( maybe( plus ) ) ) >> listElem
468 usbCode_sequence = oneplus( ( usbCode_combo | seqString ) + skip( maybe( comma ) ) ) >> oneLayerFlatten
471 capFunc_arguments = many( number + skip( maybe( comma ) ) ) >> listToTuple
472 capFunc_elem = name + skip( parenthesis('(') ) + capFunc_arguments + skip( parenthesis(')') ) >> listElem
473 capFunc_combo = oneplus( ( usbCode_expanded | usbCode_elem | capFunc_elem ) + skip( maybe( plus ) ) ) >> listElem
474 capFunc_sequence = oneplus( ( capFunc_combo | seqString ) + skip( maybe( comma ) ) ) >> oneLayerFlatten
476 # Trigger / Result Codes
477 triggerCode_outerList = scanCode_sequence >> optionExpansion
478 triggerUSBCode_outerList = usbCode_sequence >> optionExpansion >> usbCodeToCapability
479 resultCode_outerList = capFunc_sequence >> optionExpansion >> usbCodeToCapability
484 #| <variable> = <variable contents>;
485 variable_contents = name | content | string | number | comma | dash
486 variable_expression = name + skip( operator('=') ) + oneplus( variable_contents ) + skip( eol ) >> set_variable
488 #| <capability name> => <c function>;
489 capability_arguments = name + skip( operator(':') ) + number + skip( maybe( comma ) )
490 capability_expression = name + skip( operator('=>') ) + name + skip( parenthesis('(') ) + many( capability_arguments ) + skip( parenthesis(')') ) + skip( eol ) >> set_capability
492 #| <trigger> : <result>;
493 operatorTriggerResult = operator(':') | operator(':+') | operator(':-')
494 scanCode_expression = triggerCode_outerList + operatorTriggerResult + resultCode_outerList + skip( eol ) >> map_scanCode
495 usbCode_expression = triggerUSBCode_outerList + operatorTriggerResult + resultCode_outerList + skip( eol ) >> map_usbCode
497 def parse( tokenSequence ):
498 """Sequence(Token) -> object"""
501 expression = scanCode_expression | usbCode_expression | variable_expression | capability_expression
503 kll_text = many( expression )
504 kll_file = maybe( kll_text ) + skip( finished )
506 return kll_file.parse( tokenSequence )
510 ### Main Entry Point ###
512 if __name__ == '__main__':
513 (defaultFiles, partialFileSets, backend_name, template, output) = processCommandLineArgs()
515 # Load backend module
517 backend_import = importlib.import_module( "backends.{0}".format( backend_name ) )
518 backend = backend_import.Backend( template )
521 for filename in defaultFiles:
522 with open( filename ) as file:
525 tokenSequence = tokenize( data )
526 #print ( pformat( tokenSequence ) ) # Display tokenization
527 tree = parse( tokenSequence )
529 # Apply assignment cache, see 5.1.2 USB Codes for why this is necessary
530 macros_map.replayCachedAssignments()
532 # Do macro correlation and transformation
533 macros_map.generate()
535 # Process needed templating variables using backend
536 backend.process( capabilities_dict, macros_map )
538 # Generate output file using template and backend
539 backend.generate( output )
541 # Successful Execution